TicTacToeExtreme/game.gd

66 lines
1.6 KiB
GDScript

extends Node2D
var current_player: int = 0
var player_states := ["Circle", "Cross"]
var won := ""
@onready var board := $Board as Board
@onready var nextPlayer := $GUI/NextPlayer as Sprite2D
@onready var wonPlayer := $GUI/WonPlayer as Sprite2D
# Called when the node enters the scene tree for the first time.
func _ready():
current_player = 0
board.reset()
won = ""
wonPlayer.hide()
nextPlayer.region_rect.position.x = current_player * 300
nextPlayer.show()
board.active = true
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta):
if won == "":
if Input.is_action_just_pressed("Click"):
var grid_pos = board.gridpos_at_mouse()
if board.get_state(grid_pos) == board.empty_state:
if board.set_state(grid_pos, player_states[current_player]):
won = _check_win()
if won=="":
current_player = 1 - current_player
nextPlayer.region_rect.position.x = current_player * 300
else:
print("Winner: ", won)
wonPlayer.region_rect.position.x = player_states.find(won) * 300
wonPlayer.show()
nextPlayer.hide()
board.active = false
func _on_restart_button_pressed():
_ready()
var _checks = [
[Vector2i(-1,0), Vector2i(1,0)],
[Vector2i(0,-1), Vector2i(0,1)],
[Vector2i(-1,-1), Vector2i(1,1)],
[Vector2i(-1,1), Vector2i(1,-1)],
]
func _check_win() -> String:
for cell in board.get_used_cells(board.layer_by_name[board.state_layer]):
var state = board.get_state(cell)
for check in _checks:
var same = true
for neighbour in check:
if board.get_state(cell + neighbour) != state:
same = false
continue
if same:
return state
return ""