Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extends Node2D
- var board = []
- var current_player = "X"
- func _ready():
- board = ["", "", "", "", "", "", "", "", ""]
- for i in range(9):
- var button = $GridContainer.get_node("Button" + str(i))
- button.connect("pressed", Callable(self, "_on_button_pressed").bind(i))
- func _on_button_pressed(index):
- if board[index] == "":
- board[index] = current_player
- update_button_text(index)
- if check_winner():
- show_winner(current_player)
- else:
- switch_player()
- if current_player == "O":
- ai_move()
- func ai_move():
- var empty_cells = []
- for i in range(9):
- if board[i] == "":
- empty_cells.append(i)
- if empty_cells.size() > 0:
- var ai_index = empty_cells[randi() % empty_cells.size()]
- board[ai_index] = current_player
- update_button_text(ai_index)
- if check_winner():
- show_winner(current_player)
- else:
- switch_player()
- func update_button_text(index):
- var button = $GridContainer.get_node("Button" + str(index))
- button.text = board[index]
- func switch_player():
- current_player = "O" if current_player == "X" else "X"
- func check_winner():
- 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]] != "" and board[combo[0]] == board[combo[1]] and board[combo[1]] == board[combo[2]]:
- return true
- return false
- func show_winner(player):
- print(player + " wins!")
- # You can add more UI to show the winner
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement