-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtic-tac-toe.R
65 lines (49 loc) · 1.36 KB
/
tic-tac-toe.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Import functions from other files
source("print_functions.R")
source("input_functions.R")
source("state_functions.R")
source("computer_turn.R")
# Set up the board
size <- 3
board = array(rep(" ", size * size), dim = c(size, size))
# Ask player which symbol they want
player <- initial_input()
computer <- if (player == "X") "O" else "X"
# Greeting!
cat("\nWelcome,", player, "!\n\n")
# Begin!
round <- 1
valid_moves <- get_valid_moves(board)
# If player chose O, computer makes the first move
if (player == "O") {
move <- get_computer_move(size, valid_moves)
board[move[1], move[2]] <- computer
valid_moves <- get_valid_moves(board)
}
# Run game
while (length(valid_moves) > 0) {
# Print board
print_header(round)
print_board()
# Get player move
move <- player_turn_input(size, valid_moves)
row <- move[1]
col <- move[2]
board[row, col] <- player
cat("\nMove placed!\n")
# Check if game is over
winner <- game_won(board)
valid_moves <- get_valid_moves(board)
game_over(player, winner, valid_moves)
Sys.sleep(1)
# Perform computer move
move <- get_computer_move(size, valid_moves)
board[move[1], move[2]] <- computer
cat("Computer move registered.\n\n")
# Check if game is over
winner <- game_won(board)
valid_moves <- get_valid_moves(board)
game_over(player, winner, valid_moves)
# Proceed to next round
round <- round + 1
}