MCPcopy Create free account
hub / github.com/asweigart/PythonStdioGames / main

Function main

javascript_games/snailrace.js:20–101  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

18
19
20async function main() {
21 console.log('Snail Race, by Al Sweigart al@inventwithpython.com\n\n @v <-- snail\n\n');
22
23 // Ask how many snails to race:
24 while (true) {
25 console.log('How many snails will race? Max:', MAX_NUM_SNAILS);
26 let response = readlineSync.question('> ');
27 if (!isNaN(response)) {
28 var numSnailsRacing = Number(response);
29 if (1 < numSnailsRacing <= MAX_NUM_SNAILS) {
30 break;
31 }
32 }
33 console.log('Enter a number between 2 and', MAX_NUM_SNAILS);
34 }
35
36 // Enter the names of each snail:
37 let snailNames = []; // Array of the string snail names.
38 for (let i = 1; i <= numSnailsRacing; i++) {
39 while (true) { // Keep asking until the player enters a valid name.
40 console.log('Enter snail #' + i.toString() + "'s name:");
41 var name = readlineSync.question('> ');
42 if (name.length === 0) {
43 console.log('Please enter a name.');
44 } else if (snailNames.includes(name)) {
45 console.log('Choose a name that has not already been used.');
46 } else {
47 break; // The entered name is acceptable.
48 }
49 }
50 snailNames.push(name);
51 }
52
53 // Display each snail at the start line.
54 console.log('\n'.repeat(40));
55 console.log('START' + ' '.repeat(FINISH_LINE - 'START'.length) + 'FINISH');
56 console.log('|' + (' '.repeat(FINISH_LINE - '|'.length)) + '|');
57 let snailProgress = {};
58 for (let i = 0; i < snailNames.length; i++) {
59 let snailName = snailNames[i];
60 console.log(snailName.substr(0, MAX_NAME_LENGTH));
61 console.log('@v');
62 snailProgress[snailName] = 0;
63 }
64
65 await sleep(1.5); // The pause right before the race starts.
66
67 while (true) { // Main program loop.
68 // Pick random snails to move forward:
69 let numSnailsToMove = Math.floor(Math.random() * Math.floor(numSnailsRacing / 2)) + 1;
70 for (let i = 0; i < numSnailsToMove; i++) {
71 let randomSnailName = snailNames[Math.floor(Math.random() * snailNames.length)];
72 snailProgress[randomSnailName] += 1;
73
74 // Check if a snail has reached the finish line:
75 if (snailProgress[randomSnailName] == FINISH_LINE) {
76 console.log(randomSnailName, 'has won!');
77 return;

Callers 1

snailrace.jsFile · 0.70

Calls 1

sleepFunction · 0.70

Tested by

no test coverage detected