Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.36 KB | None | 0 0
  1. ##############################
  2. # Populate winning positions #
  3. ##############################
  4.  
  5. get_winning_combinations <- function(k = 3) {
  6.  
  7. # Sanity check
  8. if (k%%1 != 0 || k < 3) stop ('k is not an integer or less than 3')
  9.  
  10. # Create a k by k matrix
  11. winning_mat<-matrix(seq(1:k^2), nrow = k, byrow = TRUE)
  12. list_winning_combinations<-vector("list", length = 2*k +2)
  13.  
  14. # Assign winning combinations
  15. for (i in 1:k){
  16. list_winning_combinations[[i]]<-winning_mat[i,] # Rows
  17. list_winning_combinations[[i+k]]<-winning_mat[,i] # Columns
  18. }
  19. list_winning_combinations[[2*k+1]]<-diag(winning_mat) # Diagonal
  20. list_winning_combinations[[2*k+2]]<-diag(winning_mat[nrow(winning_mat):1, ]) # Reverse-diagonal
  21. return(list_winning_combinations)
  22. }
  23.  
  24. #################################################
  25. # Display current board in a k by k matrix form #
  26. #################################################
  27.  
  28. display_board <- function(current_board, k = 3) {
  29.  
  30. # Sanity check
  31. if (k%%1 != 0 || k < 3) stop ('k is not an integer or less than 3')
  32.  
  33. # Display the current board as a k by k matrix
  34. current_board[which(is.na(current_board))]<-which(is.na(current_board))
  35. mat<-matrix(current_board, nrow = k, byrow = TRUE)
  36. rownames(mat)<-colnames(mat)<-rep("", k)
  37. print(noquote(mat))
  38. }
  39.  
  40. ############################
  41. # Function to update board #
  42. ############################
  43.  
  44. update_board <- function(current_board, player, position) {
  45. if (is.na(current_board[position])) {
  46. current_board[position] <- player
  47. } else {
  48. print("This position is already taken. Please choose another one!")
  49. }
  50. return(current_board)
  51. }
  52.  
  53. #######################################
  54. # Function to check and decide winner #
  55. #######################################
  56.  
  57. check_winner <- function(current_board, k=3) {
  58.  
  59. # Extract winning combinations
  60. winning_combinations<-get_winning_combinations(k)
  61.  
  62. # Extract Players' moves
  63. x.move <- as.numeric(which(current_board == "x"))
  64. o.move <- as.numeric(which(current_board == "o"))
  65.  
  66. # Match
  67. for (i in 1:length(winning_combinations)) {
  68. if (sum(winning_combinations[[i]] %in% x.move) == k) {
  69. print("Player 1 (x) wins!")
  70. return (FALSE)
  71. }
  72. if (sum(winning_combinations[[i]] %in% o.move) == k) {
  73. print("Player 2 (o) wins!")
  74. return (FALSE)
  75. }
  76. if (!(NA %in% current_board)){
  77. print("It's a draw!")
  78. return (FALSE)
  79. }
  80. }
  81. return(TRUE)
  82. }
  83.  
  84. #####################################
  85. # Check if a proposed move is valid #
  86. #####################################
  87.  
  88. check.move <- function(position) {
  89. if (!grepl("^[1-9]$", position)) {
  90. return(FALSE)
  91. }
  92. return(TRUE)
  93. }
  94.  
  95. #######################################
  96. # Check if the player number is valid #
  97. #######################################
  98.  
  99. check.player.number <- function() {
  100. input <- readline(prompt = "How many players (Answer 1 or 2):")
  101. if (!grepl("^[1-2]", input)) {
  102. stop("Invalid input. Try again!")
  103. } else {
  104. return (as.integer(input))
  105. }
  106. }
  107.  
  108. #############################
  109. # Main function to play TTT #
  110. #############################
  111.  
  112. play_TTT <- function(k = 3){
  113.  
  114. # Initialize game conditons: 1 or 2 players.
  115. # If AI plays, is it player 1 or 2?
  116. n <- check.player.number()
  117.  
  118. # Register names of the players
  119. if (n == 1) {
  120. if ((readline(prompt = "Do you want to play first? (Answer Y or N) ")) == "Y") {
  121. player1 <- readline(prompt = "Please enter your name: ")
  122. player2 <- "AI"
  123. } else if (readline(prompt = "Do you want to play first? (Answer Y or N) ") == "N") {
  124. player1 <- "AI"
  125. player2 <- readline(prompt = "Please enter your name: ")
  126. } else {
  127. stop("Invalid input. Please try again!")
  128. }
  129. } else if (n == 2){
  130. player1 <- readline(prompt = "Who wants to go first: ")
  131. player2 <- readline(prompt = "Who wants to go next: ")
  132. } else {
  133. stop("Invalid input. Please try again!")
  134. }
  135.  
  136. # Initialize game board
  137. current_board <- rep(NA, k^2)
  138. repeat{
  139.  
  140. ###################
  141. # Player 1's turn #
  142. ###################
  143.  
  144. display_board(current_board, k = k) # Display board
  145.  
  146. if (player1 == "AI") { # Player 1 chooses where to play. prompt user or AI_turn()
  147. move <- AI_turn(current_board)
  148. current_board <- update_board(current_board, "x", move)
  149. } else {
  150. move <- readline(prompt = cat(player1, "Which position do you want to play: ", sep = ' '))
  151. if (check.move(move)) {
  152. move <- as.integer(move)
  153. current_board <- update_board(current_board, "x", move) # update board
  154. } else {break}
  155. }
  156. if (!check_winner(current_board)) {
  157. break # if Player 1 wins - quit loop
  158. }
  159.  
  160. ###################
  161. # Player 2's turn #
  162. ###################
  163.  
  164. display_board(current_board, k = k) # Display board
  165.  
  166. # o chooses where to play. prompt user or AI_turn()
  167. if (player2 == "AI") {
  168. move <- AI_turn(current_board)
  169. current_board <- update_board(current_board, "o", move)
  170. } else {
  171. move <- readline(prompt = cat(player2, "Which position do you want to play: ", sep = " "))
  172. if (check.move(move)) {
  173. move <- as.integer(move)
  174. current_board <- update_board(current_board, "o", move) # update board
  175. } else {break}
  176. }
  177. if (!check_winner(current_board)) {
  178. break # if Player 2 wins - quit loop
  179. }
  180. }
  181.  
  182. # Final Step - Display final board state and declare winner
  183. display_board(current_board)
  184. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement