taqin/game/src/Taquin.gd

85 lines
2.1 KiB
GDScript3
Raw Normal View History

2019-11-21 00:25:53 +01:00
extends Node2D
2019-11-22 13:38:50 +01:00
class_name Taquin
tool
2019-11-21 00:25:53 +01:00
2019-11-25 01:16:06 +01:00
var Piece = preload("res://src/Piece.tscn")
2019-11-21 00:25:53 +01:00
export var rows: int = 4
export var columns: int = 4
2019-11-22 13:38:50 +01:00
export var width: int = 512
export var height: int = 512
2019-11-21 00:25:53 +01:00
2019-11-22 13:38:50 +01:00
var pieces: Array = []
2019-11-22 13:50:37 +01:00
var missing_piece: Vector2
2019-11-21 00:25:53 +01:00
2019-11-22 13:38:50 +01:00
func _draw() -> void:
draw_rect(Rect2(0, 0, width, height), Color.blue)
func _ready() -> void:
2019-11-22 13:50:37 +01:00
for c in range(columns):
var pieces_row: Array = []
for r in range(rows):
2019-11-25 01:16:06 +01:00
var piece = Piece.instance()
2019-11-22 13:38:50 +01:00
var padding_w = (width - (piece.size * columns)) / (columns + 1)
var padding_h = (height - (piece.size * rows)) / (rows + 1)
var initial_position = Vector2(padding_w + c * (piece.size + padding_w), padding_h + r * (piece.size + padding_h))
2019-11-25 01:16:06 +01:00
piece.set_number(1 + c + r * columns)
2019-11-22 13:38:50 +01:00
piece.translate(initial_position)
2019-11-22 13:50:37 +01:00
if r == rows - 1 && c == columns - 1:
piece.visible = false
missing_piece.x = c
missing_piece.y = r
2019-11-25 01:16:06 +01:00
2019-11-22 13:38:50 +01:00
add_child(piece)
2019-11-22 13:50:37 +01:00
pieces_row.append(piece)
2019-11-25 01:16:06 +01:00
2019-11-25 01:24:38 +01:00
pieces.append(pieces_row)
func _input(event):
if event.is_action_pressed("ui_up"):
2019-11-25 21:40:55 +01:00
move_piece(Direction.UP)
2019-11-25 01:24:38 +01:00
if event.is_action_pressed("ui_down"):
2019-11-25 21:40:55 +01:00
move_piece(Direction.DOWN)
2019-11-25 01:24:38 +01:00
if event.is_action_pressed("ui_left"):
2019-11-25 21:40:55 +01:00
move_piece(Direction.LEFT)
2019-11-25 01:24:38 +01:00
if event.is_action_pressed("ui_right"):
2019-11-25 21:40:55 +01:00
move_piece(Direction.RIGHT)
enum Direction { UP, DOWN, LEFT, RIGHT }
func move_piece(direction) -> bool:
var destination: Vector2 = missing_piece
match direction:
Direction.UP:
print("up")
destination.y -= 1
Direction.DOWN:
destination.y += 1
print("down")
Direction.LEFT:
destination.x -= 1
print("left")
Direction.RIGHT:
destination.x += 1
print("right")
print(destination)
if (destination.x < 0 || destination.x >= columns
|| destination.y < 0 || destination.y >= rows):
print("impossible move")
return false
swap(missing_piece, destination)
missing_piece = destination
update()
return true
func swap(src: Vector2, dst: Vector2) -> void:
var tmp: Piece = pieces[src.x][src.y]
pieces[src.x][src.y] = pieces[dst.x][dst.y]
pieces[dst.x][dst.y] = tmp
pieces[src.x][src.y].position = position_for_index(src, tmp.size)
pieces[dst.x][dst.y].position = position_for_index(dst, tmp.size)