1. 定义snake类,
#ifndef _CSNAKE_ #define _CSNAKE_ #include "stdafx.h" //蛇最大长度 #define MAXSIZE 5000 //蛇初始长度 #define INITSIZE 5 enum DIRECTION{ RIGHT = 0, UP, LEFT, DOWN }; class CSnake{ public: CSnake(int width, int height); ~CSnake(); //随机生成食物 void GenerateFood(); //出界,回绕检测 bool CollisionDetect(); //吃到食物 bool EatFood(); //移动蛇 void Move(); public: //snake的长度 int snakelength; //snake的组成 CPoint snake[MAXSIZE]; //食物 CPoint food; //尾巴 CPoint snaketail; //方向 DIRECTION direction; //边届宽 int width; //边界高 int height; }; #endif
详细:
1. 初始化。
CSnake::CSnake(int width, int height) { snakelength = INITSIZE; for (int i = 0; i < snakelength; i++) { snake[i].x = 150 + i*10; snake[i].y = 150; } snaketail = snake[snakelength-1]; direction = LEFT; this->width = width; this->height = height; }
2. 食物生成
void CSnake::GenerateFood() { for (;;) { food.x = rand() % width; food.y = rand() % height; food.x /= 10; food.y /= 10; food.x *= 10; food.y *= 10; for (int i = 0; i < snakelength; i++) { if (food.x == snake[i].x && food.y == snake[i].y) continue; } break; } }
3. 碰撞检测
bool CSnake::CollisionDetect() { //出界 if (snake[0].x < 0 || snake[0].x >= width || snake[0].y < 0 || snake[0].y >= height) { return true; } //回绕 for (int i = 1; i < snakelength; i++) { if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) { return true; } } return false; }
4. 吃到食物
bool CSnake::EatFood() { if (snake[0] == food) { snakelength++; snake[snakelength-1] = snaketail; return true; } return false; }
5. 蛇的移动
void CSnake::Move() { //移动身体 for (int i = snakelength-1 ; i > 0; i--) { snake[i].x = snake[i-1].x; snake[i].y = snake[i-1].y; } snaketail = snake[snakelength-1]; //移动头 switch (direction) { case RIGHT: snake[0].x += 10; break; case LEFT: snake[0].x -= 10; break; case UP: snake[0].y -= 10; break; case DOWN: snake[0].y += 10; break; default: break; } }
(待续)
原文:http://www.cnblogs.com/fwst/p/3715608.html