官术网_书友最值得收藏!

Implementing the snake structure

Let's now create the two files we'll be working with: Snake.h and Snake.cpp. Prior to actually developing the snake class, a definition of some data types and structures is in order. We can begin by actually defining the structure that our apple eating serpent will be made out of, right in the snake header file:

struct SnakeSegment{
    SnakeSegment(int x, int y) : position(x,y){}
    sf::Vector2i position;
};

As you can tell, it's a very simple structure that contains a single member, which is an integer vector representing the position of the segment on the grid. The constructor here is utilized to set the position of the segment through an initializer list.

Tip

Before moving past this point, make sure you're competent with the Standard Template Library and the data containers it provides. We will specifically be using std::vector for our needs.

We now have the segment type defined, so let's get started on actually storing the snake somewhere. For beginner purposes, std::vector will do nicely! Before going too far with that, here's a neat little trick for curing our code of "long-line-itus":

using SnakeContainer = std::vector<SnakeSegment>;

As you should already know from your C/C++ background, using is a neat little keyword that allows the user to define aliases for the known data types. By using our clean new definitions together with the auto keyword, we're preventing a scenario like the following from ever happening:

std::vector<SnakeSegment>::iterator someIterator = ...

It's a simple matter of convenience and is completely optional to use, however, we will be equipping this useful tool all the way through this book.

One last type we need to define before beginning to really work on the snake class, is the direction enumeration:

enum class Direction{ None, Up, Down, Left, Right };

Once again, it's nothing too fancy. The snake has four directions it can move in. We also have a possibility of it standing still, in which case we can just set the direction to NONE.

主站蜘蛛池模板: 华安县| 绩溪县| 勐海县| 北海市| 漳平市| 南通市| 蚌埠市| 金秀| 静海县| 收藏| 措勤县| 瑞安市| 玛沁县| 黎川县| 莎车县| 张家界市| 宜黄县| 江安县| 富川| 蒙山县| 色达县| 景洪市| 原平市| 辽宁省| 辰溪县| 湟源县| 阳东县| 嘉禾县| 慈利县| 澄城县| 贡嘎县| 龙里县| 中阳县| 伊金霍洛旗| 宜章县| 彩票| 中卫市| 会东县| 陈巴尔虎旗| 皮山县| 大姚县|