Snake Game

Hey guys, i'm wondering if anyone can help me with some code.
Below i have some code for a controllable circle (representing a snake head)

what could i modify/add to the below code so that when the snake collides with the border/boundaries, it repeats from the opposite side?

i have set the game resolution to 1024 x 768

any help is greatly appreciated :)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "snake.hpp"
#include <cstdlib>

void Snake::move()
{
    switch(direction_){
    case Direction::North:
        position_.y += 10;
        break;
    case Direction::East:
        position_.x += 10;
        break;
    case Direction::South:
        position_.y -= 10;
        break;
    case Direction::West:
        position_.x -= 10;
    }

}



void Snake::render(prg::Canvas& canvas) const
{
    canvas.drawCircle(getPosition().x, getPosition().y,20,prg::Colour::WHITE);
}

void Snake::changeDirection(Direction new_direction)
{
    direction_ = new_direction;
}
Last edited on
oh, it seems that trying to submit my code section in the correct format didn't work, how do i submit it correctly?
thanks, i've edited the original post
The basic idea is this: Suppose your snake is moving left (Direction::West) and is currently at X position 9. After your switch statement, the snake will be at -1--partially of the screen. So, once the X position is < 0, make the X position 1024 somehow. Either
1
2
3
position_.x = 1024
or
position_.x += 1024

would work.

Likewise, if your snake is headed right, and the X position is greater than 1024, reset the X position back to zero. Same goes with the Y position at the top or bottom.

That should get you started
Topic archived. No new replies allowed.