Advertisement
MonkaGaming

Tic Tac Toe Meta

Nov 7th, 2024
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
GDScript 1.34 KB | Source Code | 0 0
  1. extends Node2D
  2.  
  3.  
  4. var buttons = []
  5. var currentPlayer = 1
  6. var gameBoard = [0, 0, 0, 0, 0, 0, 0, 0, 0]
  7.  
  8.  
  9. func _ready():
  10.     buttons = $GridContainer.get_children()
  11.     for i in range(len(buttons)):
  12.         buttons[i].connect("pressed", self, "_on_button_pressed", [i])
  13.  
  14.  
  15. func _on_button_pressed(index):
  16.     var button = buttons[index]
  17.     if gameBoard[index] == 0:
  18.         gameBoard[index] = currentPlayer
  19.         button.text = "X" if currentPlayer == 1 else "O"
  20.  
  21.         if check_win():
  22.             print("Player ", currentPlayer, " wins!")
  23.             reset_game()
  24.         else:
  25.             currentPlayer = 2 if currentPlayer == 1 else 1
  26.             ai_turn()
  27.  
  28.  
  29. func check_win():
  30.     var winningCombinations = [
  31.         [0, 1, 2],
  32.         [3, 4, 5],
  33.         [6, 7, 8],
  34.         [0, 3, 6],
  35.         [1, 4, 7],
  36.         [2, 5, 8],
  37.         [0, 4, 8],
  38.         [2, 4, 6]
  39.     ]
  40.  
  41.     for combination in winningCombinations:
  42.         if gameBoard[combination[0]] == gameBoard[combination[1]] && gameBoard[combination[0]] == gameBoard[combination[2]] && gameBoard[combination[0]] != 0:
  43.             return true
  44.     return false
  45.  
  46.  
  47. func ai_turn():
  48.     var index = randi() % 9
  49.     while gameBoard[index] != 0:
  50.         index = randi() % 9
  51.     gameBoard[index] = 2
  52.     buttons[index].text = "O"
  53.  
  54.     if check_win():
  55.         print("AI wins!")
  56.         reset_game()
  57.     else:
  58.         currentPlayer = 1
  59.  
  60.  
  61. func reset_game():
  62.     for button in buttons:
  63.         button.text = ""
  64.     gameBoard = [0, 0, 0, 0, 0, 0, 0, 0, 0]
  65.     currentPlayer = 1
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement