Advertisement
MonkaGaming

Tic Tac Toe ChatGPT

Nov 7th, 2024
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
GDScript 1.82 KB | Source Code | 0 0
  1. extends GridContainer
  2.  
  3. # Define the state of the board (empty, player, or AI)
  4. var board = ["", "", "", "", "", "", "", "", ""]
  5. var player_turn = true  # True for player, false for AI
  6.  
  7. # Constants for identifying players
  8. const PLAYER_MARK = "X"
  9. const AI_MARK = "O"
  10.  
  11. func _ready():
  12.     for i in range(9):
  13.         var cell = get_node("Cell_" + str(i))  # Get each button by name
  14.         cell.text = ""
  15.         if not cell.is_connected("pressed", Callable(self, "_on_cell_pressed").bind(i)):
  16.             cell.connect("pressed", Callable(self, "_on_cell_pressed").bind(i))
  17.  
  18. func _on_cell_pressed(index = -1):
  19.     if index == -1:
  20.         # Get the button that emitted the signal
  21.         var cell = get_tree().current_scene.focus_owner
  22.         index = int(cell.name.split("_")[1])
  23.     if player_turn and board[index] == "":
  24.         board[index] = PLAYER_MARK
  25.         update_board()
  26.         if check_winner():
  27.             display_winner(PLAYER_MARK)
  28.             return
  29.         player_turn = false
  30.         ai_move()
  31.  
  32.  
  33. func ai_move():
  34.     # Simple AI: pick the first empty spot
  35.     for i in range(9):
  36.         if board[i] == "":
  37.             board[i] = AI_MARK
  38.             update_board()
  39.             if check_winner():
  40.                 display_winner(AI_MARK)
  41.             break
  42.     player_turn = true
  43.  
  44. func update_board():
  45.     # Update button text based on the board state
  46.     for i in range(9):
  47.         var cell = get_node("Cell_" + str(i))
  48.         cell.text = board[i]
  49.  
  50. func check_winner() -> bool:
  51.     var win_positions = [
  52.         [0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
  53.         [0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
  54.         [0, 4, 8], [2, 4, 6]             # Diagonals
  55.     ]
  56.     for line in win_positions:
  57.         if board[line[0]] != "" and board[line[0]] == board[line[1]] and board[line[1]] == board[line[2]]:
  58.             return true
  59.     return false
  60.  
  61. func display_winner(winner):
  62.     print(winner + " wins!")
  63.     reset_game()
  64.  
  65. func reset_game():
  66.     board = ["", "", "", "", "", "", "", "", ""]
  67.     update_board()
  68.     player_turn = true
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement