Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extends Control
- var board = ['', '', '', '', '', '', '', '', '']
- var player = 'X'
- var ai = 'O'
- var game_over = false
- func _ready():
- for i in range(9):
- var button = $GridContainer.get_child(i)
- button.connect("pressed", Callable(self, "_on_button_pressed").bind(i))
- func _on_button_pressed(index):
- if board[index] == '' and not game_over:
- make_move(index, player)
- if check_winner(player):
- print("Player wins!")
- game_over = true
- elif is_board_full():
- print("It's a tie!")
- game_over = true
- else:
- ai_move()
- func make_move(index, symbol):
- board[index] = symbol
- $GridContainer.get_child(index).text = symbol
- func check_winner(symbol):
- var winning_combinations = [
- [0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
- [0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
- [0, 4, 8], [2, 4, 6] # Diagonals
- ]
- for combo in winning_combinations:
- if board[combo[0]] == symbol and board[combo[1]] == symbol and board[combo[2]] == symbol:
- return true
- return false
- func is_board_full():
- return '' not in board
- func ai_move():
- var available_moves = []
- for i in range(9):
- if board[i] == '':
- available_moves.append(i)
- if available_moves.size() > 0:
- var move = available_moves[randi() % available_moves.size()]
- make_move(move, ai)
- if check_winner(ai):
- print("AI wins!")
- game_over = true
- elif is_board_full():
- print("It's a tie!")
- game_over = true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement