Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Handling Collisions | Snake Game
Building a Classic Snake Game

bookHandling Collisions

Calling game over

We did all the hard work before when created is_body_collision() method, so now we just have to use it. First of all let's ensure that there is a game_over() when the snake head collides with its body.

if is_collision(game.snake):
    game_over(game)

Collision with fruit

Let's consider what should occur when the snake's head collides with a fruit. Naturally, when this happens, the fruit needs to appear in a different location, and the snake's length should increase. This concept is straightforward to understand and also implement:

if is_collision(game.snake, game.fruit.position):
    spawn(game.fruit, game.snake.positions)
    add_length(game.snake)

The code snippet above detects if the snake collides with a fruit. Upon collision, the fruit moves to a new position, the snake grows longer.

Compito

Swipe to start coding

  • Add and implement handle_collision method.
    • Add collision detection for Game Over.
    • Add collision detection with Fruit.

Soluzione

Mark tasks as Completed
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 10

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Awesome!

Completion rate improved to 9.09

bookHandling Collisions

Calling game over

We did all the hard work before when created is_body_collision() method, so now we just have to use it. First of all let's ensure that there is a game_over() when the snake head collides with its body.

if is_collision(game.snake):
    game_over(game)

Collision with fruit

Let's consider what should occur when the snake's head collides with a fruit. Naturally, when this happens, the fruit needs to appear in a different location, and the snake's length should increase. This concept is straightforward to understand and also implement:

if is_collision(game.snake, game.fruit.position):
    spawn(game.fruit, game.snake.positions)
    add_length(game.snake)

The code snippet above detects if the snake collides with a fruit. Upon collision, the fruit moves to a new position, the snake grows longer.

Compito

Swipe to start coding

  • Add and implement handle_collision method.
    • Add collision detection for Game Over.
    • Add collision detection with Fruit.

Soluzione

Mark tasks as Completed
Switch to desktopCambia al desktop per esercitarti nel mondo realeContinua da dove ti trovi utilizzando una delle opzioni seguenti
Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 10
some-alt