Skip to content

Instantly share code, notes, and snippets.

@imRohan
Created June 17, 2018 20:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save imRohan/a2bbe9c4be482bff85313fb08a69598e to your computer and use it in GitHub Desktop.
A javascript class representing a game of Blackjack
const https = require('https')
module.exports = class BlackJackGame {
constructor() {
this.game = {
deckId: null,
remaining: null,
player: {
hand: [],
count: 0
},
dealer: {
hand: [],
count: 0
},
}
}
newDeck() {
return new Promise((resolve, reject) => {
https.get('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1', (response) => {
let _body = ''
response.on('data', (data) => {
_body += data
})
response.on('end', () => {
this.game.deckId = JSON.parse(_body).deck_id
console.log(`New Deck Created ${this.game.deckId}`)
resolve()
})
})
})
}
dealCard(dealer = false) {
if(this.game.deckId) {
return new Promise((resolve, reject) => {
https.get(`https://deckofcardsapi.com/api/deck/${this.game.deckId}/draw/?count=1`, (response) => {
let _body = ''
response.on('data', (data) => {
_body += data
})
response.on('end', () => {
const _response = JSON.parse(_body)
if(dealer) {
this.assignCard('dealer', _response)
} else {
this.assignCard('player', _response)
}
this.remaining = _response.remaining
resolve(_response.cards[0])
})
})
})
}
}
assignCard(person, response) {
const _card = response.cards[0]
const { code } = _card
const _cardValue = this.getValueOfCard(_card)
this.game[person].hand.push(code)
this.game[person].count += _cardValue
console.log(`Assigning card ${code} to ${person}`)
}
getValueOfCard(card) {
const VALUES_MAPPED = {
JACK: 10,
QUEEN: 10,
KING: 10,
ACE: 10,
}
const _value = card.value
const _integer = parseInt(_value)
return _integer ? _integer : VALUES_MAPPED[_value]
}
getPlayerHand(person) {
return this.game[person].hand
}
getPlayerHandCount(person) {
return this.game[person].count
}
getWinner() {
const _playerCount = this.getPlayerHandCount('player')
const _dealerCount = this.getPlayerHandCount('dealer')
return _playerCount > _dealerCount ? 'player' : 'dealer'
}
isPersonBust(person) {
return this.getPlayerHandCount(person) > 21
}
isThereWinner() {
if(this.isPersonBust('dealer')) {
console.log('Dealer Busts')
return { player: this.game.player.count }
} else if(this.isPersonBust('player')) {
console.log('Player Busts')
return { dealer: this.game.dealer.count }
} else {
console.log('No Winner Yet')
return {
none: {
player: this.game.player.count,
dealer: this.game.dealer.count
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment