Advertisement
MonkaGaming

Tic Tac Toe Copilot AI

Nov 7th, 2024
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
GDScript 1.51 KB | Source Code | 0 0
  1. extends Node2D
  2.  
  3. var board = []
  4. var current_player = "X"
  5.  
  6. func _ready():
  7.     board = ["", "", "", "", "", "", "", "", ""]
  8.     for i in range(9):
  9.         var button = $GridContainer.get_node("Button" + str(i))
  10.         button.connect("pressed", Callable(self, "_on_button_pressed").bind(i))
  11.  
  12. func _on_button_pressed(index):
  13.     if board[index] == "":
  14.         board[index] = current_player
  15.         update_button_text(index)
  16.         if check_winner():
  17.             show_winner(current_player)
  18.         else:
  19.             switch_player()
  20.             if current_player == "O":
  21.                 ai_move()
  22.  
  23. func ai_move():
  24.     var empty_cells = []
  25.     for i in range(9):
  26.         if board[i] == "":
  27.             empty_cells.append(i)
  28.     if empty_cells.size() > 0:
  29.         var ai_index = empty_cells[randi() % empty_cells.size()]
  30.         board[ai_index] = current_player
  31.         update_button_text(ai_index)
  32.         if check_winner():
  33.             show_winner(current_player)
  34.         else:
  35.             switch_player()
  36.  
  37. func update_button_text(index):
  38.     var button = $GridContainer.get_node("Button" + str(index))
  39.     button.text = board[index]
  40.  
  41. func switch_player():
  42.     current_player = "O" if current_player == "X" else "X"
  43.  
  44. func check_winner():
  45.     var winning_combinations = [
  46.         [0, 1, 2], [3, 4, 5], [6, 7, 8], # Rows
  47.         [0, 3, 6], [1, 4, 7], [2, 5, 8], # Columns
  48.         [0, 4, 8], [2, 4, 6]  # Diagonals
  49.     ]
  50.     for combo in winning_combinations:
  51.         if board[combo[0]] != "" and board[combo[0]] == board[combo[1]] and board[combo[1]] == board[combo[2]]:
  52.             return true
  53.     return false
  54.  
  55. func show_winner(player):
  56.     print(player + " wins!")
  57.     # You can add more UI to show the winner
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement