use
node dice_game.js
dice_game.js
class Dice {
static roll() {
return Math.floor(Math.random() * 6) + 1;
}
}
class ThreeDices {
dice1;
dice2;
dice3;
total;
size;
roll() {
this.dice1 = Dice.roll();
this.dice2 = Dice.roll();
this.dice3 = Dice.roll();
this.total = this.dice1 + this.dice2 + this.dice3;
this.size = this.total > 10 ? "大" : "小";
}
toString() {
return `\n掷出的骰子: ${this.dice1}, ${this.dice2}, ${this.dice3}\n总点数: ${this.total}\n结果:${this.size}\n`;
}
}
class Player {
constructor(name, balance) {
this.name = name;
this.balance = balance;
}
win(amount) {
this.balance += amount;
}
lost(amount) {
if (amount > this.balance) {
throw new Error(`${this.name}资金不足`);
}
this.balance -= amount;
}
toString() {
return `${this.name} (${this.balance})`;
}
}
class Banker extends Player {
constructor(balance) {
super("庄家", balance);
}
}
class Table {
constructor(player, banker) {
this.player = player;
this.banker = banker;
this.bet = 0; // 当前轮次的赌注
this.threeDices = new ThreeDices();
}
placeBet(bet) {
this.player.lost(bet);
this.banker.lost(bet);
this.bet += bet * 2;
}
payout(winner) {
winner.win(this.bet);
this.bet = 0;
}
}
class Game {
constructor(table) {
this.table = table;
}
async play() {
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
let rounds = 0;
const threeDices = this.table.threeDices;
const player = this.table.player;
const banker = this.table.banker;
console.log(player.toString(), banker.toString());
while (true) {
threeDices.roll();
console.log(`===========================================`);
try {
const input =
(await new Promise((resolve) => {
readline.question("请输入1大2小(默认大) 空格 赌注(默认20): ", resolve);
})) || "1 20"; // 默认值为 "1 10" 表示大和10的赌注
const [guessStr, betStr] = input.split(' ');
const bet = parseInt(betStr, 10) || 20; // 如果没有提供赌注,默认为10
const guess = guessStr == "1" ? "大" : "小";
this.table.placeBet(bet); // 放置赌注到赌桌上
console.log(threeDices.toString());
if (guess === threeDices.size) {
console.log("你赢了!");
this.table.payout(player); // 赢家获得赔付
} else {
console.log("你输了。");
this.table.payout(banker);
}
console.log(player.toString(), banker.toString());
rounds++;
} catch (error) {
console.error(error.message);
break;
}
}
console.log("游戏结束!");
console.log(`共进行了 ${rounds} 轮游戏。`);
readline.close();
}
}
const player = new Player("玩家", 100);
const banker = new Banker(200);
const table = new Table(player, banker);
const game = new Game(table);
game.play();