How to code a snake game AI which eats apple against player.

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

Currently I am making a game exactly like the snake game(play snake - Google Suche) or you can simply search snake game on google and it will be the first window. I am making this game without grid-based movement. I want to make an AI which eats apples against the player. Please help me to build this system.

:bust_in_silhouette: Reply From: aXu_AP

For simple AI you need to have 2 behaviours:

  1. Understand in which direction the apple is and rotate towards it.
  2. See obstacles and steer away from them. If you are using colliders, you can cast a ray from head of AI player forward and change direction if it’s a hit.

Of course one could make more intricate system with pathfinding and trapping behaviours, but it’s better to start small.

I preferred using a pathfinding system but, it moves the snake in 8 directions instead of 4.
Here is the code.

extends KinematicBody2D

export var ai_speed = 200
onready var nav = get_parent().get_node(“Navigation2D”)
onready var ai_apple = get_parent().get_node(“Apple”)
var path

func _physics_process(delta):
path = nav.get_simple_path(self.global_position, ai_apple.global_position, false)
var distance = path[1] - self.global_position
var direction = distance.normalized()

if path.size() > 1:
if distance != self.global_position:
self.position += direction

adgan | 2021-11-09 11:55