Last active
July 25, 2017 20:30
-
-
Save Yardanico/a9128ee017ff5ff33f5dc6d953e6cd06 to your computer and use it in GitHub Desktop.
Nim game ported from Python: https://github.com/3noch/nim-python/blob/master/nim.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{.noforward: on.} | |
import math, strutils | |
type | |
NimGame = ref object | |
players: seq[string] | |
board: seq[int] | |
proc initGame(): NimGame = | |
new(result) | |
result.players = @["Player 1", "Player 2"] | |
result.board = @[1, 2, 3, 4, 5] | |
proc play(self: NimGame) = | |
while true: | |
for player in self.players: | |
self.takeTurn(player) | |
if sum(self.board) == 0: | |
echo player & " won!" | |
return | |
proc takeTurn(self: NimGame, player: string) = | |
echo player & "'s turn: " | |
self.displayBoard() | |
let row = self.getRow() | |
let count = self.getInt("How many stars? ", 1, self.board[row - 1]) | |
self.board[row - 1] = self.board[row - 1] - count | |
proc getRow(self: NimGame): int = | |
result = -1 | |
while result == -1: | |
let row = self.getInt("Which row? ", 1, len(self.board)) | |
if self.board[row - 1] == 0: | |
echo "That row is empty!" | |
else: | |
result = row | |
proc getInt(self: NimGame, prompt: string, minValue, maxValue: int): int = | |
result = -1 | |
while result == -1: | |
stdout.write(prompt) | |
let resp = stdin.readLine() | |
try: | |
let converted = resp.parseInt() | |
if converted < minValue: echo "That number is too small." | |
elif converted > maxValue: echo "That number is too big." | |
else: result = converted | |
except ValueError: | |
echo "That is not a number!" | |
proc displayBoard(self: NimGame) = | |
for index in countdown(len(self.board), 1): | |
echo $index & " : " & "*".repeat(self.board[index - 1]) | |
when isMainModule: | |
let nim = initGame() | |
nim.play() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment