vendredi 21 avril 2023

How to quickly choose a number in a wide range and avoiding prohibited numbers

I am making a snake game and I need to place an apple in the x*y map in each loop, this apple cannot be placed on the body of the snake

My code probably looks like this

// snake_body is a array include all body's coordinate
snake_body := []

// Find coordinates in a loop that are not in the snake_body
function setApple()
    loop
        apple_x := random(map_x)
        apple_x := random(map_y)
        if not apple_x, apple_x in snake_body
            return apple_x, apple_x

This is a poor design that gives quick results when the snake is relatively short, but once you get into the late game and the snake's body takes up most of the coordinates, the loop needs to be executed very many times to find valid coordinates

My current solution is to also create and maintain a coordinate array that is not used by the snake

empty_ground := []

function refresh()
    // Use this method in each loop to update the elements in the empty ground

function setApple()
    return random(empty_ground)

This would require me to maintain a very large coordinate table, and updating it would also require some arithmetic power, and I would like to know if there is any better algorithm that can solve this problem quickly?




Aucun commentaire:

Enregistrer un commentaire