banner



Design Snake Game In C++

How to Design a Snake Game?

How to Design a Snake Game?

Design a Snake game that is played on a device with screen size = width x height. Play the game online if you are not familiar with the game.

The snake is initially positioned at the top left corner (0,0) with length = 1 unit.

You are given a list of food's positions in row-column order. When a snake eats the food, its length and the game's score both increase by 1.

Each food appears one by one on the screen. For example, the second food will not appear until the first food was eaten by the snake.

When a food does appear on the screen, it is guaranteed that it will not appear on a block occupied by the snake.

Example:
Given width = 3, height = 2, and food = [[1,2],[0,1]].

1                                
Snake snake                                  =                                  new                                  Snake(width, height, food)                                  ;                                
Snake snake = new Snake(width, height, food);

Initially the snake appears at position (0,0) and the food at (1,2).

|S| | | | | |F|

snake.move("R"); – Returns 0

| |S| | | | |F|

snake.move("D"); – Returns 0

| | | | | |S|F|

snake.move("R"); – Returns 1 (Snake eats the first food and right after that, the second food appears at (0,1) )

| |F| | | |S|S|

snake.move("U"); – Returns 1

| |F|S| | | |S|

snake.move("L"); – Returns 2 (Snake eats the second food)

| |S|S| | | |S|

snake.move("U"); – Returns -1 (Game over because snake collides with border)

snake_grows How to Design a Snake Game? c / c++ data structure design questions games

The Snake Game in Magik

Snake Body: Double Ended Queue

The Snake Body can be stored using the double-ended queue, which we can push to the front and pop from the back.

1                            
deque<vector<int>>                              body;                            

Snake Food: Vector

We can use a std::vector to store the list of food for the snake to eat.

1                              
vector<vector<int>>                                food;                              
vector<vector<int>> food;

Design a Snake Game

We follow the logics as we play the Snake Game:

  1. Move the head of the snake as directed, and return -1 if the head is out of the boundary.
  2. If the head position is now at the food, push the food to the front of the body, erase the food, increment the score, and the snake body will grow one.
  3. Otherwise, the snake needs to move one step forward, then we can pop one from the snake's tail. And check if the updated heads position is in the snake body, if yes, return -1, otherwise, push the new head to the front of the snake body.

The snake can chase its tail without dying. That is why we need to pop one from tail first before we move the snake head forward. The following C++ code illustrates the design of the snake game.

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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                              
class SnakeGame                                {                                private:                                deque<vector<int>>                                body;                                int                                W,                                H;                                vector<vector<int>>                                food;                                int                                score                                =                                0                                ;                                public:                                /** Initialize your data structure here.                                        @param width - screen width                                        @param height - screen height                                                                        @param food - A list of food positions                                        E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */                                SnakeGame(                                int                                width,                                int                                height,                                vector<vector<int>>&                                food)                                {                                this->W                                =                                width;                                this->H                                =                                height;                                this->food                                =                                food;                                body.push_back                                (                                {                                0                                ,                                0                                }                                )                                ;                                }                                /** Moves the snake.                                        @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down                                                                        @return The game's score after the move. Return -1 if game over.                                                                        Game over when snake crosses the screen boundary or bites its body. */                                int                                move(string direction)                                {                                auto                                head                                =                                body.front                                (                                )                                ;                                int                                r                                =                                head[                                0                                ]                                ;                                int                                c                                =                                head[                                1                                ]                                ;                                for                                (                                const                                auto                                &ch:                                direction)                                {                                switch                                (ch)                                {                                case                                'U'                                :                                r                                --;                                break                                ;                                case                                'L'                                :                                c                                --;                                break                                ;                                case                                'R'                                :                                c                                ++;                                break                                ;                                case                                'D'                                :                                r                                ++;                                break                                ;                                default                                :                                return                                -                                1                                ;                                }                                if                                (r                                <                                0                                ||                                c                                <                                0                                ||                                c                                >=                                W                                ||                                r                                >=                                H)                                {                                return                                -                                1                                ;                                }                                if                                (food.size                                (                                )                                >                                0                                )                                {                                vector<int>                                f                                =                                food[                                0                                ]                                ;                                if                                (f[                                0                                ]                                ==                                r                                &&                                f[                                1                                ]                                ==                                c)                                {                                food.erase                                (begin(food)                                )                                ;                                body.push_front                                (                                {r,                                c}                                )                                ;                                score                                ++;                                continue                                ;}                                }                                body.pop_back                                (                                )                                ;                                if                                (std::                                find                                (begin(body)                                ,                                end(body)                                ,                                vector<int>                                {r,                                c}                                )                                !=                                body.end                                (                                )                                )                                {                                return                                -                                1                                ;                                }                                body.push_front                                (                                {r,                                c}                                )                                ;                                }                                return                                score;                                }                                }                                ;                              
class SnakeGame { private:     deque<vector<int>> body;     int W, H;     vector<vector<int>> food;     int score = 0;  public:     /** Initialize your data structure here.         @param width - screen width         @param height - screen height          @param food - A list of food positions         E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */     SnakeGame(int width, int height, vector<vector<int>>& food) {         this->W = width;         this->H = height;         this->food = food;         body.push_back({0, 0});     }          /** Moves the snake.         @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down          @return The game's score after the move. Return -1 if game over.          Game over when snake crosses the screen boundary or bites its body. */     int move(string direction) {         auto head = body.front();         int r = head[0];         int c = head[1];         for (const auto &ch: direction) {             switch (ch) {                 case 'U':                     r --;                     break;                 case 'L':                     c --;                     break;                 case 'R':                     c ++;                     break;                 case 'D':                     r ++;                     break;                 default:                     return -1;             }             if (r < 0 || c < 0 || c >= W || r >= H) {                 return -1;             }             if (food.size() > 0) {                 vector<int> f = food[0];                 if (f[0] == r && f[1] == c) {                     food.erase(begin(food));                     body.push_front({r, c});                     score ++;                     continue;                }             }             body.pop_back();             if (std::find(begin(body), end(body), vector<int>{r, c}) != body.end()) {                 return -1;             }             body.push_front({r, c});         }         return score;     } };

With the above Snake Class, the game can be initialised and played:

1 2 3 4 5                              
                                /**                                 * Your SnakeGame object will be instantiated and called as such:                                */                                SnakeGame*                                obj                                =                                new SnakeGame(width,                                height,                                food)                                ;                                int                                param_1                                =                                obj->move(direction)                                ;                              
/**  * Your SnakeGame object will be instantiated and called as such: */ SnakeGame* obj = new SnakeGame(width, height, food); int param_1 = obj->move(direction);

game_over How to Design a Snake Game? c / c++ data structure design questions games

The Snake Game in Magik

Play Snake Game

Want to play the snake game? Here are two good options:

  • Simple Snake Game in Javascript
  • Chrome Extension: Snake Game

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...

974 words
Last Post: How to Design a Two-Sum Data Structure?
Next Post: The Maximum Average Subtree of a Binary Tree

The Permanent URL is: How to Design a Snake Game? (AMP Version)

Design Snake Game In C++

Source: https://helloacm.com/how-to-design-a-snake-game/

Posted by: bakersalogned.blogspot.com

0 Response to "Design Snake Game In C++"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel