Untitled

 avatar
Kandif
plain_text
2 years ago
2.3 kB
8
Indexable
Never
extends Node2D

var point_pos:Vector2
var snake_body = [Vector2(5,10),Vector2(4,10),Vector2(3,10)]
var snake_direction = Vector2(1,0)

var changed_direction = false
var buffered_direction = Vector2.ZERO

func _ready():
	
	point_pos = place_point()
	draw_point()
	draw_snake()
	
func draw_snake():
	for block in snake_body:
		$Board.set_cell(block.x,block.y,0,false,false,false,Vector2(7,0))

func draw_point():
	$Board.set_cell(point_pos.x,point_pos.y,1)
	
func place_point():
	randomize()
	var x = randi() % 20
	var y = randi() % 20
	while(Vector2(x,y) in snake_body):
		x = randi() % 20
		y = randi() % 20
	return Vector2(x,y)

func delete_tiles(id):
	var cells = $Board.get_used_cells_by_id(id)
	for cell in cells:
		$Board.set_cell(cell.x,cell.y,-1)		
		
func move_snake():
	delete_tiles(0)
	var body_copy = snake_body.slice(0,snake_body.size() - 2)
	var new_head = body_copy[0] + snake_direction
	body_copy.insert(0,new_head)
	snake_body = body_copy
	if buffered_direction!=Vector2.ZERO:
		snake_direction = buffered_direction
		buffered_direction = Vector2.ZERO
		changed_direction = true
	
func _on_Timer_timeout():
	changed_direction = false
	move_snake()
	draw_point()
	draw_snake()
	
func _process(delta):
	if not changed_direction:
		if Input.is_key_pressed(KEY_W) and snake_direction != Vector2(0,1):
			snake_direction = Vector2(0,-1)
			changed_direction = true
		elif Input.is_key_pressed(KEY_S) and snake_direction != Vector2(0,-1):
			snake_direction = Vector2(0,1)
			changed_direction = true
		elif Input.is_key_pressed(KEY_A) and snake_direction != Vector2(1,0):
			snake_direction = Vector2(-1,0)
			changed_direction = true
		elif Input.is_key_pressed(KEY_D) and snake_direction != Vector2(-1,0):
			snake_direction = Vector2(1,0)	
			changed_direction = true
	else:
		if Input.is_key_pressed(KEY_W) and snake_direction != Vector2(0,1):
			buffered_direction = Vector2(0,-1)
		elif Input.is_key_pressed(KEY_S) and snake_direction != Vector2(0,-1):
			buffered_direction = Vector2(0,1)
		elif Input.is_key_pressed(KEY_A) and snake_direction != Vector2(1,0):
			buffered_direction = Vector2(-1,0)
		elif Input.is_key_pressed(KEY_D) and snake_direction != Vector2(-1,0):
			buffered_direction = Vector2(1,0)