Skip to content

Commit 8d06a43

Browse files
Merge pull request #337 from LukasMurdock/edits
Further change Acey Ducey JavaScript
2 parents a01f9d2 + f63c258 commit 8d06a43

File tree

4 files changed

+215
-122
lines changed

4 files changed

+215
-122
lines changed
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"trailingComma": "es5",
3+
"tabWidth": 4,
4+
"semi": true,
5+
"singleQuote": true
6+
}
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<!DOCTYPE html>
2-
<meta charset="utf-8">
3-
<meta name="viewport" content="width=device-width">
2+
<meta charset="utf-8" />
3+
<meta name="viewport" content="width=device-width" />
44
<title>ACEY DUCEY</title>
55

6-
<pre id="output" style="font-size: 12pt;"></pre>
7-
<script type="module" src="aceyducey.js"></script>
6+
<pre id="output" style="font-size: 12pt"></pre>
7+
<script src="aceyducey.js"></script>

01_Acey_Ducey/javascript/aceyducey.js

Lines changed: 205 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,100 +1,216 @@
1-
import { readLine, print, spaces } from "./io.js";
2-
3-
const minFaceCard = 11;
4-
const faceCards = {
5-
11: "JACK",
6-
12: "QUEEN",
7-
13: "KING",
8-
14: "ACE"
9-
};
10-
11-
function randomCard() {
12-
return Math.floor(Math.random() * 13 + 2);
1+
// UTILITY VARIABLES
2+
3+
// By default:
4+
// — Browsers have a window object
5+
// — Node.js does not
6+
// Checking for an undefined window object is a loose check
7+
// to enable browser and Node.js support
8+
const isRunningInBrowser = typeof window !== 'undefined';
9+
10+
// To easily validate input strings with utility functions
11+
const validLowerCaseYesStrings = ['yes', 'y'];
12+
const validLowerCaseNoStrings = ['no', 'n'];
13+
const validLowerCaseYesAndNoStrings = [
14+
...validLowerCaseYesStrings,
15+
...validLowerCaseNoStrings,
16+
];
17+
// UTILITY VARIABLES
18+
19+
// Function to get a random number (card) 2-14 (ACE is 14)
20+
function getRandomCard() {
21+
// In our game, the value of ACE is greater than face cards;
22+
// instead of having the value of ACE be 1, we’ll have it be 14.
23+
// So, we want to shift the range of random numbers from 1-13 to 2-14
24+
let min = 2;
25+
let max = 14;
26+
// Return random integer between two values, inclusive
27+
return Math.floor(Math.random() * (max - min + 1) + min);
28+
}
29+
30+
function newGameCards() {
31+
let cardOne = getRandomCard();
32+
let cardTwo = getRandomCard();
33+
let cardThree = getRandomCard();
34+
// We want:
35+
// 1. cardOne and cardTwo to be different cards
36+
// 2. cardOne to be lower than cardTwo
37+
// So, while cardOne is greater than or equal too cardTwo
38+
// we will continue to generate random cards.
39+
while (cardOne >= cardTwo) {
40+
cardOne = getRandomCard();
41+
cardTwo = getRandomCard();
42+
}
43+
return [cardOne, cardTwo, cardThree];
1344
}
1445

15-
function printCard(card) {
16-
if (card < minFaceCard) {
17-
print(card);
18-
} else {
19-
print(faceCards[card]);
20-
}
21-
print("\n");
46+
// Function to get card value
47+
function getCardValue(card) {
48+
let faceOrAce = {
49+
11: 'JACK',
50+
12: 'QUEEN',
51+
13: 'KING',
52+
14: 'ACE',
53+
};
54+
// If card value matches a key in faceOrAce, use faceOrAce value;
55+
// Else, return undefined and handle with the Nullish Coalescing Operator (??)
56+
// and default to card value.
57+
let cardValue = faceOrAce[card] ?? card;
58+
return cardValue;
2259
}
2360

24-
print(spaces(26) + "ACEY DUCEY CARD GAME\n");
25-
print(spaces(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n\n");
26-
print("ACEY-DUCEY IS PLAYED IN THE FOLLOWING MANNER\n");
27-
print("THE DEALER (COMPUTER) DEALS TWO CARDS FACE UP\n");
28-
print("YOU HAVE AN OPTION TO BET OR NOT BET DEPENDING\n");
29-
print("ON WHETHER OR NOT YOU FEEL THE CARD WILL HAVE\n");
30-
print("A VALUE BETWEEN THE FIRST TWO.\n");
31-
print("IF YOU DO NOT WANT TO BET, INPUT '0'\n");
32-
33-
let currentMoney = 100;
34-
while (true) {
35-
print(`YOU NOW HAVE ${currentMoney} DOLLARS.\n\n`);
36-
37-
let card1, card2, currentBet;
38-
do {
39-
print("HERE ARE YOUR NEXT TWO CARDS: \n");
40-
[card1, card2] = [randomCard(), randomCard()];
41-
42-
// Ensure we always show cards in order of lowest to highest, and we never
43-
// get two of the same card.
44-
do {
45-
card1 = randomCard();
46-
card2 = randomCard();
47-
} while (card1 >= card2);
48-
49-
printCard(card1);
50-
printCard(card2);
51-
print("\n");
61+
print(spaces(26) + 'ACEY DUCEY CARD GAME');
62+
print(spaces(15) + 'CREATIVE COMPUTING MORRISTOWN, NEW JERSEY\n\n');
63+
print('ACEY-DUCEY IS PLAYED IN THE FOLLOWING MANNER');
64+
print('THE DEALER (COMPUTER) DEALS TWO CARDS FACE UP');
65+
print('YOU HAVE AN OPTION TO BET OR NOT BET DEPENDING');
66+
print('ON WHETHER OR NOT YOU FEEL THE CARD WILL HAVE');
67+
print('A VALUE BETWEEN THE FIRST TWO.');
68+
print("IF YOU DO NOT WANT TO BET, INPUT '0'");
69+
70+
main();
71+
72+
async function main() {
73+
let bet;
74+
let availableDollars = 100;
5275

76+
// Loop game forever
5377
while (true) {
54-
print("\nWHAT IS YOUR BET? ");
55-
currentBet = parseInt(await readLine(), 10);
56-
57-
if (currentBet > 0) {
58-
if (currentBet > currentMoney) {
59-
print("SORRY, MY FRIEND, BUT YOU BET TOO MUCH.\n");
60-
print(`YOU HAVE ONLY ${currentMoney} DOLLARS TO BET.\n`);
61-
continue;
78+
let [cardOne, cardTwo, cardThree] = newGameCards();
79+
80+
print(`YOU NOW HAVE ${availableDollars} DOLLARS.\n`);
81+
82+
print('HERE ARE YOUR NEXT TWO CARDS: ');
83+
print(getCardValue(cardOne));
84+
print(getCardValue(cardTwo));
85+
print('');
86+
87+
// Loop until receiving a valid bet
88+
let validBet = false;
89+
while (!validBet) {
90+
print('\nWHAT IS YOUR BET? ');
91+
bet = parseInt(await input(), 10);
92+
let minimumRequiredBet = 0;
93+
if (bet > minimumRequiredBet) {
94+
if (bet > availableDollars) {
95+
print('SORRY, MY FRIEND, BUT YOU BET TOO MUCH.');
96+
print(`YOU HAVE ONLY ${availableDollars} DOLLARS TO BET.`);
97+
} else {
98+
validBet = true;
99+
}
100+
} else {
101+
// Does not meet minimum required bet
102+
print('CHICKEN!!');
103+
print('');
104+
}
62105
}
63-
break;
64-
}
65-
66-
// Invalid bet value. Output an error message and reset to undefined to
67-
// restart the loop with new cards.
68-
currentBet = undefined;
69-
print("CHICKEN!!\n");
70-
print("\n");
71-
break;
106+
107+
print('\n\nHERE IS THE CARD WE DREW: ');
108+
print(getCardValue(cardThree));
109+
110+
// Determine if player won or lost
111+
if (cardThree > cardOne && cardThree < cardTwo) {
112+
print('YOU WIN!!!');
113+
availableDollars = availableDollars + bet;
114+
} else {
115+
print('SORRY, YOU LOSE');
116+
117+
if (bet >= availableDollars) {
118+
print('');
119+
print('');
120+
print('SORRY, FRIEND, BUT YOU BLEW YOUR WAD.');
121+
print('');
122+
print('');
123+
print('TRY AGAIN (YES OR NO)');
124+
125+
let tryAgainInput = await input();
126+
127+
print('');
128+
print('');
129+
130+
if (isValidYesNoString(tryAgainInput)) {
131+
availableDollars = 100;
132+
} else {
133+
print('O.K., HOPE YOU HAD FUN!');
134+
break;
135+
}
136+
} else {
137+
availableDollars = availableDollars - bet;
138+
}
139+
}
140+
}
141+
}
142+
143+
// UTILITY FUNCTIONS
144+
function isValidYesNoString(string) {
145+
return validLowerCaseYesAndNoStrings.includes(string.toLowerCase());
146+
}
147+
148+
function isValidYesString(string) {
149+
return validLowerCaseYesStrings.includes(string.toLowerCase());
150+
}
151+
152+
function isValidNoString(string) {
153+
return validLowerCaseNoStrings.includes(string.toLowerCase());
154+
}
155+
156+
function print(string) {
157+
if (isRunningInBrowser) {
158+
// Adds trailing newline to match console.log behavior
159+
document
160+
.getElementById('output')
161+
.appendChild(document.createTextNode(string + '\n'));
162+
} else {
163+
console.log(string);
72164
}
73-
} while (currentBet === undefined);
74-
75-
const actualCard = randomCard();
76-
print("\n\nHERE IS THE CARD WE DREW:\n")
77-
printCard(actualCard);
78-
print("\n\n");
79-
80-
if (actualCard > card1 && actualCard < card2) {
81-
print("YOU WIN!!!\n");
82-
currentMoney += currentBet;
83-
} else {
84-
print("SORRY, YOU LOSE\n");
85-
if (currentBet < currentMoney) {
86-
currentMoney -= currentBet;
165+
}
166+
167+
function input() {
168+
if (isRunningInBrowser) {
169+
// Accept input from the browser DOM input
170+
return new Promise((resolve) => {
171+
const outputElement = document.querySelector('#output');
172+
const inputElement = document.createElement('input');
173+
outputElement.append(inputElement);
174+
inputElement.focus();
175+
176+
inputElement.addEventListener('keydown', (event) => {
177+
if (event.key === 'Enter') {
178+
const result = inputElement.value;
179+
inputElement.remove();
180+
print(result);
181+
print('');
182+
resolve(result);
183+
}
184+
});
185+
});
87186
} else {
88-
print("\n\nSORRY, FRIEND, BUT YOU BLEW YOUR WAD.\n\n\n");
89-
print("TRY AGAIN (YES OR NO)");
90-
const tryAgain = await readLine();
91-
print("\n\n");
92-
if (tryAgain.toLowerCase() === "yes") {
93-
currentMoney = 100;
94-
} else {
95-
print("O.K., HOPE YOU HAD FUN!");
96-
break;
97-
}
187+
// Accept input from the command line in Node.js
188+
// See: https://nodejs.dev/learn/accept-input-from-the-command-line-in-nodejs
189+
return new Promise(function (resolve) {
190+
const readline = require('readline').createInterface({
191+
input: process.stdin,
192+
output: process.stdout,
193+
});
194+
readline.question('', function (input) {
195+
resolve(input);
196+
readline.close();
197+
});
198+
});
98199
}
99-
}
100200
}
201+
202+
function printInline(string) {
203+
if (isRunningInBrowser) {
204+
document
205+
.getElementById('output')
206+
.appendChild(document.createTextNode(string));
207+
} else {
208+
process.stdout.write(string);
209+
}
210+
}
211+
212+
function spaces(numberOfSpaces) {
213+
return ' '.repeat(numberOfSpaces);
214+
}
215+
216+
// UTILITY FUNCTIONS

01_Acey_Ducey/javascript/io.js

Lines changed: 0 additions & 29 deletions
This file was deleted.

0 commit comments

Comments
 (0)