Not a member of Pastebin yet?
                        Sign Up,
                        it unlocks many cool features!                    
                - extends GridContainer
 - # Define the state of the board (empty, player, or AI)
 - var board = ["", "", "", "", "", "", "", "", ""]
 - var player_turn = true # True for player, false for AI
 - # Constants for identifying players
 - const PLAYER_MARK = "X"
 - const AI_MARK = "O"
 - func _ready():
 - for i in range(9):
 - var cell = get_node("Cell_" + str(i)) # Get each button by name
 - cell.text = ""
 - if not cell.is_connected("pressed", Callable(self, "_on_cell_pressed").bind(i)):
 - cell.connect("pressed", Callable(self, "_on_cell_pressed").bind(i))
 - func _on_cell_pressed(index = -1):
 - if index == -1:
 - # Get the button that emitted the signal
 - var cell = get_tree().current_scene.focus_owner
 - index = int(cell.name.split("_")[1])
 - if player_turn and board[index] == "":
 - board[index] = PLAYER_MARK
 - update_board()
 - if check_winner():
 - display_winner(PLAYER_MARK)
 - return
 - player_turn = false
 - ai_move()
 - func ai_move():
 - # Simple AI: pick the first empty spot
 - for i in range(9):
 - if board[i] == "":
 - board[i] = AI_MARK
 - update_board()
 - if check_winner():
 - display_winner(AI_MARK)
 - break
 - player_turn = true
 - func update_board():
 - # Update button text based on the board state
 - for i in range(9):
 - var cell = get_node("Cell_" + str(i))
 - cell.text = board[i]
 - func check_winner() -> bool:
 - var win_positions = [
 - [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 line in win_positions:
 - if board[line[0]] != "" and board[line[0]] == board[line[1]] and board[line[1]] == board[line[2]]:
 - return true
 - return false
 - func display_winner(winner):
 - print(winner + " wins!")
 - reset_game()
 - func reset_game():
 - board = ["", "", "", "", "", "", "", "", ""]
 - update_board()
 - player_turn = true
 
Advertisement
 
                    Add Comment                
                
                        Please, Sign In to add comment