Last active
June 13, 2017 12:10
-
-
Save expersso/d442b06837126dbd8f1192e8d7daf95d to your computer and use it in GitHub Desktop.
Implementation of Nim in R
This file contains hidden or 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
## Nim | |
next_player <- function(player) if(player == 1) 2 else 1 | |
valid_move <- function(board, row, num) board[row] >= num | |
finished <- function(board) all(board == 0) | |
update <- function(board, row, num) `[<-`(board, row, board[row] - num) | |
disp_row <- function(row, num) cat(row, ":", rep("*", num), "\n") | |
disp_board <- function(board) purrr::walk2(seq_along(board), board, disp_row) | |
nim <- function(board = 5:1, player = 1) { | |
if(finished(board)) { | |
cat("Game over. Player", next_player(player), "wins!") | |
return(invisible()) | |
} | |
disp_board(board) | |
cat("Player", player) | |
row <- as.integer(readline("Choose a row: ")) | |
num <- as.integer(readline("Number of stars to remove: ")) | |
if(!valid_move(board, row, num)) { | |
cat("Not a valid move. Try again.\n") | |
nim(board, player) | |
} else nim(update(board, row, num), next_player(player)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment