Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extends Node2D
- var buttons = []
- var currentPlayer = 1
- var gameBoard = [0, 0, 0, 0, 0, 0, 0, 0, 0]
- func _ready():
- buttons = $GridContainer.get_children()
- for i in range(len(buttons)):
- buttons[i].connect("pressed", self, "_on_button_pressed", [i])
- func _on_button_pressed(index):
- var button = buttons[index]
- if gameBoard[index] == 0:
- gameBoard[index] = currentPlayer
- button.text = "X" if currentPlayer == 1 else "O"
- if check_win():
- print("Player ", currentPlayer, " wins!")
- reset_game()
- else:
- currentPlayer = 2 if currentPlayer == 1 else 1
- ai_turn()
- func check_win():
- var winningCombinations = [
- [0, 1, 2],
- [3, 4, 5],
- [6, 7, 8],
- [0, 3, 6],
- [1, 4, 7],
- [2, 5, 8],
- [0, 4, 8],
- [2, 4, 6]
- ]
- for combination in winningCombinations:
- if gameBoard[combination[0]] == gameBoard[combination[1]] && gameBoard[combination[0]] == gameBoard[combination[2]] && gameBoard[combination[0]] != 0:
- return true
- return false
- func ai_turn():
- var index = randi() % 9
- while gameBoard[index] != 0:
- index = randi() % 9
- gameBoard[index] = 2
- buttons[index].text = "O"
- if check_win():
- print("AI wins!")
- reset_game()
- else:
- currentPlayer = 1
- func reset_game():
- for button in buttons:
- button.text = ""
- gameBoard = [0, 0, 0, 0, 0, 0, 0, 0, 0]
- currentPlayer = 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement