首页 > 其他 > 详细

简单贪吃蛇

时间:2014-05-08 18:21:26      阅读:614      评论:0      收藏:0      [点我收藏+]

 

 

bubuko.com,布布扣

 

bubuko.com,布布扣

 

1. 定义snake类,

bubuko.com,布布扣
#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
bubuko.com,布布扣

详细:

  1. 初始化。

  

bubuko.com,布布扣
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;
}
bubuko.com,布布扣

   2. 食物生成

  

bubuko.com,布布扣
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;
    }
}
bubuko.com,布布扣

 

3. 碰撞检测

  

bubuko.com,布布扣
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;
}
bubuko.com,布布扣

 

4. 吃到食物

bubuko.com,布布扣
bool CSnake::EatFood()
{
    if (snake[0] == food)
    {
        snakelength++;
        snake[snakelength-1] = snaketail;
        return true;
    }
    return false;
}
bubuko.com,布布扣

 

5. 蛇的移动

bubuko.com,布布扣
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;
    }
}
bubuko.com,布布扣

 

(待续)

 

简单贪吃蛇,布布扣,bubuko.com

简单贪吃蛇

原文:http://www.cnblogs.com/fwst/p/3715608.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!