Skip to content

Instantly share code, notes, and snippets.

@jilmun
Created March 29, 2016 14:25
Show Gist options
  • Save jilmun/de47790258e1fe35222e to your computer and use it in GitHub Desktop.
Save jilmun/de47790258e1fe35222e to your computer and use it in GitHub Desktop.
# TIC TAC TOE
# Run function ttt(n) to begin
ttt <- function (n = 3) {
# set up board variables
board <- matrix(rep(".", (n+1)^2), ncol=n+1)
board[,1] <- c("/", 1:n)
board[1,] <- c("/", 1:n)
players <- c("X", "O")
# start game message
cat("Welcome to tic-tac-toe! Press <esc> to exit game at any time.\n\n")
write.table(format(board, justify="centre"), quote=F, row.names=F, col.names=F, file="")
ttt.status <- list(win = 0, msg = "No one", me = "X", turn.player = TRUE) # default player starts
resp.in <- readline(prompt="Do you want to play 'X'? (y/n): ")
if (resp.in == "n")
ttt.status$turn.player <- FALSE
# main loop
while (ttt.status$win == 0) {
# update board with new move
new.pos <- ttt_move(board, ttt.status$turn.player)
board[new.pos$row, new.pos$col] <- ttt.status$me
write.table(format(board, justify="centre"), quote=F, row.names=F, col.names=F, file="")
# check win status, need to connect n
mat <- board[-1,-1]
if (all(diag(mat) == ttt.status$me) | all(diag(mat[,n:1]) == ttt.status$me)) { # check diagonals
ttt.status$win <- 1
ttt.status$msg <- c("Congrats, player", "Sorry, computer")[c(ttt.status$turn.player,!ttt.status$turn.player)]
}
for (i in 1:n) {
if (all(mat[i,] == ttt.status$me) | all(mat[,i] == ttt.status$me)) { # check rows and cols
ttt.status$win <- 1
ttt.status$msg <- c("Congrats, player", "Sorry, computer")[c(ttt.status$turn.player,!ttt.status$turn.player)]
}
}
# check if board is full
if (sum(mat == ".") == 0)
ttt.status$win <- 1
# update status for next turn
ttt.status$me <- players[!players %in% ttt.status$me]
ttt.status$turn.player <- !ttt.status$turn.player
}
message(paste("Game over.", ttt.status$msg, "wins!!"))
}
ttt_move <- function(mat, turn.p) {
pos.next <- list(row = 0, col = 0)
if (turn.p == TRUE) {
message("Your move!")
pos.next$row <- as.numeric(readline(prompt="Enter the row ID of where you'd like to move: ")) + 1
pos.next$col <- as.numeric(readline(prompt="Enter the column ID of where you'd like to move: ")) + 1
}
else {
Sys.sleep(0.5)
message("Computer move!")
Sys.sleep(0.5)
# naive AI: pick random empty spot
empty <- which(mat==".", arr.ind=T)
move.random <- empty[sample(1:nrow(empty), 1),]
pos.next$row <- move.random[1]
pos.next$col <- move.random[2]
}
return(pos.next)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment