Skip to content

Instantly share code, notes, and snippets.

@cbenz
Last active January 27, 2021 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbenz/c2abb2cbc1daa5af7567c34c6f0dcf1a to your computer and use it in GitHub Desktop.
Save cbenz/c2abb2cbc1daa5af7567c34c6f0dcf1a to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// interface Player {
// name: string
// stack: number
// cards: Array<Card>
// bet: number
// }
const PRE_FLOP = "PRE_FLOP"
const FLOP = "FLOP"
const TURN = "TURN"
const RIVER = "RIVER"
const pokerMachine = Machine({
id: "poker",
context: {
dealerIndex: null,
pot: null,
players: [
{name: "Henri", stack: 100, cards: null, bet: null},
{name: "Laeti", stack: 1000, cards: null},
{name: "Sandra", stack: 350, cards: null},
],
minPlayers: 3,
maxPlayers: 5,
blindAmount: 2,
stage: PRE_FLOP,
},
initial: "waiting",
states: {
waiting: {
on: {
START_GAME: {
target: "dealingCards",
cond: ({players, minPlayers}) => players.length >= minPlayers,
actions: assign({
dealerIndex: ({players}) => getRandomItemIndex(players),
})
},
SIT_DOWN: {
target: "",
cond: ({players, maxPlayers}) => players.length < maxPlayers,
actions: assign({
players: (context, event) => append(context.players, event.player)
})
}
}
},
dealingCards: {
on: {
"": {
target: "betting",
actions: assign({
players: ({players}) => dealPlayerCards(players),
})
}
}
},
betting: {
initial: "payingBlinds",
states: {
payingBlinds: {
on: {
"": {
target: "betting",
actions: assign({
players: ({players, dealerIndex, blindAmount}) => payBlinds(players, dealerIndex, blindAmount)
})
}
}
},
betting: {
on: {
SET_BET: {
target: ""
}
}
}
},
},
game: {},
}
});
function append(array, item) {
return [...array, item]
}
function getRandomItemIndex(array) {
return Math.floor(Math.random() * array.length)
}
function getRandomCardColor() {
return "spades"
}
function getRandomCardValue() {
return "king"
}
function getRandomCard() {
return {
color: getRandomCardColor(),
value: getRandomCardValue(),
}
}
function getRandomCards(n) {
return Array(2).fill(null).map(() => getRandomCard())
}
function dealPlayerCards(players) {
return players.map(player => ({
...player,
cards: getRandomCards(2),
}))
}
function payBlinds(players, dealerIndex, blindAmount) {
const newPlayers = [...players]
const smallBlindPlayerIndex = (dealerIndex + 1) % players.length
newPlayers[smallBlindPlayerIndex] = {
...newPlayers[smallBlindPlayerIndex],
bet: blindAmount,
}
const bigBlindPlayerIndex = (dealerIndex + 2) % players.length
newPlayers[smallBlindPlayerIndex] = {
...newPlayers[bigBlindPlayerIndex],
bet: blindAmount * 2,
}
return newPlayers
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment