21 Sticks
This example shows how to create an app where the user plays the game 21 sticks against the computer.
class MyApp extends App{
numberOfSticksLeft = 21
take3Sticks(){
a.numberOfSticksLeft -= 3
}
take2Sticks(){
a.numberOfSticksLeft -= 2
}
take1Stick(){
a.numberOfSticksLeft -= 1
}
createStartPage(){
return AskUserToMakeAMove
}
}
class AskUserToMakeAMove extends Page{
createGui(){
return Rows.children(
Space,
Text.text(`There are ${a.numberOfSticksLeft} sticks left.`),
Space,
Text.text(`How many sticks do you want to take?`),
Columns.children(
Space,
Button.text(`1 sticks`).onClick(a.take1Stick),
Space,
Button.keepIf(2 <= a.numberOfSticksLeft).text(`2 sticks`).onClick(a.take2Sticks),
Space.keepIf(2 <= a.numberOfSticksLeft),
Button.keepIf(3 <= a.numberOfSticksLeft).text(`3 sticks`).onClick(a.take3Sticks),
Space.keepIf(3 <= a.numberOfSticksLeft),
),
Space,
)
}
createAfterDirections(){
return [
Direction.page(ComputerWon).when(a.numberOfSticksLeft == 0).text(`The computer won`),
Direction.page(ShowGameAfterUserMove).when(true).text(`Game not finished`),
]
}
}
class ShowGameAfterUserMove extends Page{
createGui(){
return Rows.children(
Space,
Text.text(`There are ${a.numberOfSticksLeft} sticks left.`),
Space,
Columns.children(
Space,
Button.text(`The computer's turn...`).page(ShowGameAfterComputerMove),
Space,
),
Space,
)
}
}
class ShowGameAfterComputerMove extends Page{
numberOfSticksTheComputerTakes = 0
onBefore(){
// Compute how many sticks the computer may take.
const maxSticksToTake = m.lowest(3, a.numberOfSticksLeft)
// Then the computer will get a random number of sticks.
p.numberOfSticksTheComputerTakes = m.randomInt(1, maxSticksToTake)
a.numberOfSticksLeft -= p.numberOfSticksTheComputerTakes
}
createGui(){
return Rows.children(
Space,
Text.text(`The computer takes ${p.numberOfSticksTheComputerTakes} sticks.`),
Space,
Text.text(`Now there are ${a.numberOfSticksLeft} sticks left.`),
Space,
Button.text(`OK`),
Space,
)
}
createAfterDirections(){
return [
Direction.page(PlayerWon).when(a.numberOfSticksLeft == 0).text(`The player won`),
Direction.page(AskUserToMakeAMove).when(true).text(`Game not finished`),
]
}
}
class ComputerWon extends Page{
createGui(){
return Rows.children(
Space,
Text.text(`Too bad, the computer won âšī¸`),
Space,
)
}
}
class PlayerWon extends Page{
createGui(){
return Rows.children(
Space,
Text.text(`Congratulation, you won! đ`),
Space,
)
}
}