Please help me find out what went wrong in my movement code for the nokia classic snake game remake

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Yinisiki

Please help me. As we know in the snake game, if we are currently moving to the right: we cannot move to the left, we have to move either up or down or persist with moving right. And so on respectively for the other directions. So I came up with the following code:

extends Area2D

export var SPEED=100
var input_vector= Vector2.ZERO
var canMove = {'left':false, 'right':false, 'up':false, 'down':false}
var moving = {'left':false, 'right':false, 'up':false, 'down':false}

func _physics_process(delta):

position += input_vector*SPEED*delta

if Input.is_action_just_pressed("ui_right"):
	input_vector.x=1
	input_vector.y=0
if Input.is_action_just_pressed("ui_left"):
	input_vector.x=-1
	input_vector.y=0
if Input.is_action_just_pressed("ui_up"):
	input_vector.x=0
	input_vector.y=-1
if Input.is_action_just_pressed("ui_down"):
	input_vector.x=0
	input_vector.y=1


if input_vector.x<0:
	moving['left']=true
if input_vector.x>0:
	moving['right']=true

if input_vector.y<0:
	moving['up']=true
if input_vector.y>0:
	moving['down']=true


if moving['left']==true:
	canMove['right']=false
	canMove['up']=true
	canMove['down']=true
if moving['right']==true:
	canMove['left']=false
	canMove['up']=true
	canMove['down']=true
if moving['up']==true:
	canMove['right']=true
	canMove['left']=true
	canMove['down']=false
if moving['down']==true:
	canMove['right']=true
	canMove['left']=true
	canMove['up']=false


if canMove['left']==false:
	input_vector.x= abs(input_vector.x)
if canMove['right']==false:
	input_vector.x= -abs(input_vector.x)

if canMove['up']==false:
	input_vector.y= abs(input_vector.y)
if canMove['down']==false:
	input_vector.y= -abs(input_vector.y)
:bust_in_silhouette: Reply From: Legorel

I don’t think this is a good way to achieve snake like mouvement, I remember some part of how I coded this some time ago:

var direction = Vector2.ZERO

func _physics_process(delta):
  if Input.is_action_just_pressed("ui_left") and direction != Vector2.RIGHT:
    direction = Vector2.LEFT
  if Input.is_action_just_pressed("ui_right") and direction != Vector2.LEFT:
    direction = Vector2.RIGHT
  if Input.is_action_just_pressed("ui_up") and direction != Vector2.DOWN:
    direction = Vector2.UP
  if Input.is_action_just_pressed("ui_down") and direction != Vector2.UP:
    direction = Vector2.DOWN

You can then add the code to move the snake according to the variable direction