Skip to content

Instantly share code, notes, and snippets.

@scottdomes
Last active April 11, 2016 20:10
Show Gist options
  • Save scottdomes/50c9ebdf6effbb62ec6e8c5f1b9f9f13 to your computer and use it in GitHub Desktop.
Save scottdomes/50c9ebdf6effbb62ec6e8c5f1b9f9f13 to your computer and use it in GitHub Desktop.
Node betting game
var color = require('colors');
var fs = require('fs');
var player1 = {
cash: 50,
wins: 0
};
var player2 = {
cash: 50,
wins: 0
};
var players = [player1, player2];
var playerInput = require('./module');
var current_player = player1;
function startRound() {
player = current_player;
var number = Math.floor(Math.random() + 1);
if ((player.cash - player.bet) >= 0) {
evaluteGuess(player, number);
} else {
console.log(color.red(player.name + ", you don't have enough money!"));
}
}
function endRound() {
if (current_player === player1) {
current_player = player2;
startRound();
} else {
current_player = player1;
fs.readFile('leaderboard.txt', function(err, res) {
if (err) {
console.log(err);
} else {
console.log(res.toString());
playerInput(players, startRound);
}
});
}
}
function evaluteGuess(player, number) {
if (correctGuess(player.guess, number)) {
player.wins += 1;
updateLeaderboard(number);
} else if (closeGuess(player.guess, number)) {
console.log(color.yellow("You're close!"));
displayResult(player, number, false);
} else {
displayResult(player, number, false);
}
}
function correctGuess(guess, actual) {
if (guess == actual) {
return true;
} else {
return false;
}
}
function closeGuess(guess, actual) {
if ((guess - 1) == actual || (guess + 1) == actual) {
return true;
} else {
return false;
}
}
function displayResult(player, number, correct) {
if (correct) {
console.log(color.green(player.name + ", you're right!"));
player.cash += parseInt(player.bet);
} else {
console.log(color.red(player.name + ", you're wrong!"));
player.cash -= player.bet;
}
console.log("The number was " + number);
console.log(player.name + ", you have " + player.cash);
endRound();
}
function updateLeaderboard(number) {
var data = "Player 1 has " + players[0].wins + ".\n";
data += "Player 2 has " + players[1].wins + ".";
fs.writeFile('leaderboard.txt', data, function(err) {
if (err) return console.log(err);
console.log("Written!");
displayResult(player, number, true);
});
}
playerInput(players, startRound);
var prompt = require('prompt-sync')();
module.exports = function getInput(players, callback) {
for (var i = 0; i < players.length; i++) {
if (players[i].name === undefined){
players[i].number = (i + 1);
players[i].name = prompt("Player " + players[i].number + ", what's your name?");
}
players[i].bet = prompt(players[i].name + ", name your bet!");
players[i].guess = prompt(players[i].name + ", guess a number!");
}
callback(players);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment