Advertisement
MonkaGaming

Tic Tac Toe Perplexity AI

Nov 7th, 2024
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
GDScript 1.42 KB | Source Code | 0 0
  1. extends Control
  2.  
  3. var board = ['', '', '', '', '', '', '', '', '']
  4. var player = 'X'
  5. var ai = 'O'
  6. var game_over = false
  7.  
  8. func _ready():
  9.     for i in range(9):
  10.         var button = $GridContainer.get_child(i)
  11.         button.connect("pressed", Callable(self, "_on_button_pressed").bind(i))
  12.  
  13. func _on_button_pressed(index):
  14.     if board[index] == '' and not game_over:
  15.         make_move(index, player)
  16.         if check_winner(player):
  17.             print("Player wins!")
  18.             game_over = true
  19.         elif is_board_full():
  20.             print("It's a tie!")
  21.             game_over = true
  22.         else:
  23.             ai_move()
  24.  
  25. func make_move(index, symbol):
  26.     board[index] = symbol
  27.     $GridContainer.get_child(index).text = symbol
  28.  
  29. func check_winner(symbol):
  30.     var winning_combinations = [
  31.         [0, 1, 2], [3, 4, 5], [6, 7, 8],  # Rows
  32.         [0, 3, 6], [1, 4, 7], [2, 5, 8],  # Columns
  33.         [0, 4, 8], [2, 4, 6]  # Diagonals
  34.     ]
  35.    
  36.     for combo in winning_combinations:
  37.         if board[combo[0]] == symbol and board[combo[1]] == symbol and board[combo[2]] == symbol:
  38.             return true
  39.     return false
  40.  
  41. func is_board_full():
  42.     return '' not in board
  43.  
  44. func ai_move():
  45.     var available_moves = []
  46.     for i in range(9):
  47.         if board[i] == '':
  48.             available_moves.append(i)
  49.    
  50.     if available_moves.size() > 0:
  51.         var move = available_moves[randi() % available_moves.size()]
  52.         make_move(move, ai)
  53.         if check_winner(ai):
  54.             print("AI wins!")
  55.             game_over = true
  56.         elif is_board_full():
  57.             print("It's a tie!")
  58.             game_over = true
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement