Snake/Scripts/GameManager.gd

122 lines
3 KiB
GDScript3
Raw Normal View History

extends GridContainer
@export var map_size := 15
@export var texture : Texture2D
@export var speed := 0.25
@export var tile_color := TileColors.new()
var tiles = []
var snake_move_vector : Vector2
var last_snake_move_vector : Vector2
var snake_length : int
var rng = RandomNumberGenerator.new()
var timer := 0.0
var game_is_running := true
func generate_tiles():
self.columns = map_size
for x in range(map_size):
tiles.append([])
tiles[x] = []
for y in range(map_size):
var tile = Tile.new(x ,y, tile_color)
self.add_child(tile)
tiles[x].append([])
tiles[x][y] = tile
pass
func generate_apple():
var foundViablePosition := false
var tile : Tile
while !foundViablePosition:
tile = tiles[rng.randi_range(0, map_size -1)][rng.randi_range(0, map_size -1)] as Tile
if(tile.state == Tile.States.EMPTY):
foundViablePosition = true
tile.state = Tile.States.APPLE
pass
func set_snake_to_start_position():
#No need for float protection, godot automaticly converts floats to ints in this case
var tile = (tiles[map_size / 2][map_size / 2] as Tile)
tile.state = Tile.States.SNAKE
tile.snake_pos = 1
pass
func read_input() -> Vector2:#
# cant use Input.get_vector because it normalizes the vector
return Vector2(Input.get_axis("up", "down"), Input.get_axis("left", "right"))
func process_tiles():
var new_snake_head : Tile
for x in range(map_size):
for y in range(map_size):
var tile = tiles[x][y] as Tile
if tile.state == Tile.States.SNAKE:
if tile.snake_pos == 1:
if x + snake_move_vector.x >= map_size || x + snake_move_vector.x < 0 || y + snake_move_vector.y >= map_size || y + snake_move_vector.y < 0:
game_stop()
return
new_snake_head = tiles[x + snake_move_vector.x][y + snake_move_vector.y] as Tile
tile.snake_pos += 1
if(tile.snake_pos > snake_length):
tile.snake_pos = 0
tile.state = Tile.States.EMPTY
var was_apple = new_snake_head.state == Tile.States.APPLE
if new_snake_head.state == Tile.States.SNAKE:
game_stop()
return
new_snake_head.snake_pos = 1
new_snake_head.state = Tile.States.SNAKE
last_snake_move_vector = snake_move_vector
if was_apple:
snake_length += 1
generate_apple()
pass
func process_snake_rotation():
var input = read_input()
# Return if no Input or Input into multiple directions
if input.length() == 0 || input.length() > 1:
return
#return if input is the inverse of the moving direction
if input * -1 == last_snake_move_vector:
return
# set move direction into inpu direction
snake_move_vector = input.normalized()
func _ready():
game_start()
pass
func game_start():
snake_move_vector = Vector2.RIGHT
last_snake_move_vector = snake_move_vector
snake_length = 3
tiles.clear()
generate_tiles()
set_snake_to_start_position()
generate_apple()
pass
func game_stop():
game_is_running = false
get_tree().change_scene_to_file("res://Scene/Main Menu.tscn")
pass
func _process(delta):
if !game_is_running:
return
process_snake_rotation()
if(timer >= speed):
timer = 0
process_tiles()
timer += delta
pass