board.h

#ifndef BOARD_H
#define BOARD_H #define MAX_X 40
#define MAX_Y 30
#define NORMAL_LABEL 0//普通label
#define BORDER_LABEL 1//边界label
#define SNAKE_LABEL 2//蛇身label
#define FOOD_LABEL 3//食物label #include <QWidget>
#include <QLabel>
#include <QList>
#include <QTimer>
#include <QKeyEvent> struct Node{
    QLabel *label;
    int type;//边界:1   蛇身:2  普通:0 食物:3
    int x;
    int y;
}; class Board : public QWidget
{
    Q_OBJECT
public:
    explicit Board(QWidget *parent = 0);
    void init();
    void drawBorder();//画边界
    void initSnake();
    void moveStep();
    void getHeadTail();//得到头和尾
    bool left();//判断是否能上下左右移动
    bool right();
    bool up();
    bool down();
    void keyPressEvent(QKeyEvent *e);//键盘事件
//    void gameover();
//    void showAllType();
    void generateFood();//生成食物 signals: public slots:
    void slotMoveStep();//槽函数,可以当做普通函数使用 private:
    Node *matrix[MAX_X][MAX_Y];
    QList<Node*> snake;//蛇身     int dx, dy;
    Node *head;//蛇头指针
    Node *tail;//蛇尾指针     QTimer timer; }; #endif // BOARD_H

boarder.cpp

#include "board.h"
#include <QDebug>
#include <QString>
#include <QTimer>
#include <QMessageBox>
#include <QKeyEvent>
#include <ctime> Board::Board(QWidget *parent) :
    QWidget(parent)
{
    this->setWindowTitle("贪吃蛇");
    init();//初始化
    drawBorder();//画边界
    initSnake();//初始化蛇身
    moveStep();     generateFood();//初始化完就产生一个食物     connect(&timer, SIGNAL(timeout()), this, SLOT(slotMoveStep()));
    timer.start(100); } void Board::init(){
    int gridSize = 25;     for(int x = 0; x < MAX_X; x++){
        for(int y = 0; y < MAX_Y; y++){
            QLabel *label = new QLabel(this);
            label->setStyleSheet("background:red");
            label->setGeometry(x * gridSize, y * gridSize, gridSize - 1, gridSize - 1);
            label->hide();
            matrix[x][y]= new Node;
            matrix[x][y]->label =label;
            matrix[x][y]->type = NORMAL_LABEL;//将所有的都初始化成普通label
            matrix[x][y]->x = x;
            matrix[x][y]->y = y;
        }
    }
} void Board::drawBorder(){//画边界
    for(int x = 0; x < MAX_X; x++){
        for(int y = 0; y < MAX_Y; y++){
            if(x == 0 || x == MAX_X - 1 || y == 0 || y == MAX_Y - 1){
                matrix[x][y]->label->show();
                matrix[x][y]->type = BORDER_LABEL;//边界label
            }
        }
    }
} void Board::initSnake(){//画蛇身
    int x0 = 5, y0 = 5;
    int snakeLen = 5;//初始蛇身长5     dx = 1;
    dy = 0;
    snake.clear();
    for(int x = x0; x < x0 + snakeLen; x++){         snake.append(matrix[x][y0]);
        snake.at(snake.length() - 1)->x = x;
        snake.at(snake.length() - 1)->y = y0;
        matrix[x][y0]->type = SNAKE_LABEL;//蛇身label
        matrix[x][y0]->label->show();
    } } void Board::moveStep(){
    getHeadTail();//获取蛇头和蛇尾指针
    Node *n = matrix[head->x + dx][head->y + dy];
    n->label->show();
    //n是即将变成蛇头的那个label
    if(n->type == BORDER_LABEL || n->type == SNAKE_LABEL){
        qDebug() << "Game over@!!!";
        timer.stop();
        QMessageBox::information(this, "提示", "*** Game Over ***", QMessageBox::Ok);
    }else{
        if(n->type == FOOD_LABEL){//吃到食物了
            n->type = SNAKE_LABEL;
            snake.append(n);
            //不移除尾巴
            generateFood();//生成下一个食物
        }else{
            n->type = SNAKE_LABEL;
            snake.append(n);
            tail->label->hide();
            tail->type = NORMAL_LABEL;
            snake.removeFirst();
        }
    }
} void Board::getHeadTail(){
    head = snake.at(snake.length() - 1);//蛇头其实是list的尾巴
    tail = snake.at(0);//蛇尾其实是list的第一个元素
    //    gameover();
} void Board::slotMoveStep(){
    //    qDebug() << "movestep";
    moveStep();
} void Board::keyPressEvent(QKeyEvent *e){
    //qDebug() << Qt::Key_up;
    qDebug() << e->key();
    switch (e->key()) {
    case 16777235://上
        if(up()){
            dy = -1;
            dx = 0;
        }
        break;
    case 16777237://下
        if(down()){
            dy = 1;
            dx = 0;
        }
        break;
    case 16777234://左
        if(left()){
            dx = -1;
            dy = 0;
        }
        break;
    case 16777236://右
        if(right()){
            dx = 1;
            dy = 0;
        }
        break;
    default:
        break;;
    }
} void Board::generateFood(){//生成食物
    int food_x,food_y;
    srand((unsigned)time(0));
    do{
        food_x = rand()%MAX_X;
        food_y = rand()%MAX_Y;
    }while(matrix[food_x][food_y]->type != NORMAL_LABEL);
//    matrix[food_x][food_y]->label->setText("food");
    matrix[food_x][food_y]->type = FOOD_LABEL;
    matrix[food_x][food_y]->label->show(); } bool Board::left(){
    if(dy == 0){//向左或向右走
        return false;
    }
    return true;
} bool Board::right(){
    if(dy == 0){//向左或向右走
        return false;
    }
    return true;
} bool Board::up(){
    if(dx == 0){//向上或向下走
        return false;
    }
    return true;
} bool Board::down(){
    if(dx == 0){//向上或向下走
        return false;
    }
    return true;
}

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M02/2F/2E/wKiom1Oeqa-ymO_qAAG6R9KtXxQ333.jpg" title="QQ截图20140616161726.png" alt="wKiom1Oeqa-ymO_qAAG6R9KtXxQ333.jpg" />

本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1426968

QT实现贪吃蛇的更多相关文章

  1. QT下的贪吃蛇

    QT写的贪吃蛇,学习于https://www.devbean.net/2012/12/qt-study-road-2-snake-1/ 建议就学习一下开发思想,开发游戏还是用专门的编译器. 多加了墙, ...

  2. Qt 学习之路 2(34):贪吃蛇游戏(4)

    Qt 学习之路 2(34):贪吃蛇游戏(4) 豆子 2012年12月30日 Qt 学习之路 2 73条评论 这将是我们这个稍大一些的示例程序的最后一部分.在本章中,我们将完成GameControlle ...

  3. Qt 学习之路 2(33):贪吃蛇游戏(3)

    Qt 学习之路 2(33):贪吃蛇游戏(3) 豆子 2012年12月29日 Qt 学习之路 2 16条评论 继续前面一章的内容.上次我们讲完了有关蛇的静态部分,也就是绘制部分.现在,我们开始添加游戏控 ...

  4. Qt 学习之路 2(32):贪吃蛇游戏(2)

    Qt 学习之路 2(32):贪吃蛇游戏(2) 豆子 2012年12月27日 Qt 学习之路 2 55条评论 下面我们继续上一章的内容.在上一章中,我们已经完成了地图的设计,当然是相当简单的.在我们的游 ...

  5. Qt 学习之路 2(31):贪吃蛇游戏(1)

    Qt 学习之路 2(31):贪吃蛇游戏(1) 豆子 2012年12月18日 Qt 学习之路 2 41条评论 经过前面一段时间的学习,我们已经了解到有关 Qt 相当多的知识.现在,我们将把前面所讲过的知 ...

  6. easyx图形库做贪吃蛇游戏

    编程总是对着一个黑窗口,可以说是非常乏味了,于是喵喵就翻出来了以前用easyx图形库做图形界面的贪吃蛇游戏. 不过大家只是当做提高编程的乐趣来学习吧,想进一步做的话可以学习QT,还有其他的框架. 这是 ...

  7. Android快乐贪吃蛇游戏实战项目开发教程-01项目概述与目录

    一.项目简介 贪吃蛇是一个很经典的游戏,也很适合用来学习.本教程将和大家一起做一个Android版的贪吃蛇游戏. 我已经将做好的案例上传到了应用宝,无病毒.无广告,大家可以放心下载下来把玩一下.应用宝 ...

  8. 用C++实现的贪吃蛇游戏

    我是一个C++初学者,控制台实现了一个贪吃蛇游戏. 代码如下: //"贪吃蛇游戏"V1.0 //李国良于2016年12月29日编写完成 #include <iostream& ...

  9. [LeetCode] Design Snake Game 设计贪吃蛇游戏

    Design a Snake game that is played on a device with screen size = width x height. Play the game onli ...

随机推荐

  1. wordpress模板各文件函数解析

    修改主题时发现好多WordPress主题函数都不了解,因此网上摘抄了一份放在自己博客上,便于以后好找. 在WordPress中如何按你的意愿显示页面,关键看你是否了解WordPress主题模板页面.这 ...

  2. asp.net mvc 设置启动页面在区域中

    在开发过程中,我们有时候需要启动区域中的页面为起始页面,那我们就需要子啊路由中添加一段代码 如何完整案例:         public static void RegisterRoutes(Rout ...

  3. String,Date,XMLGregorianCalendar的转换

    常见标准的写法"yyyy-MM-dd HH:mm:ss",区分大小写,时间是24小时制,24小时制转换成12小时制只需将HH改成hh. String to Date: String ...

  4. KM算法及其优化的学习笔记&&bzoj2539: [Ctsc2000]丘比特的烦恼

    感谢  http://www.cnblogs.com/vongang/archive/2012/04/28/2475731.html 这篇blog里提供了3个链接……基本上很明白地把KM算法是啥讲清楚 ...

  5. 微软注册dll在dotnet开发时起到缓存的作用

    经过试验,我发觉只要是注册了dll之后,会在全局的环境中得到很好的体现,比如无需指定具体物理路径的dll引用,搜索即可引用等,同时也得到一点: 1.会缓存起这个dll先,在不重启电脑的情况,本地物理路 ...

  6. [Android] HttpURLConnection & HttpClient & Socket

    Android的三种网络联接方式 1.标准Java接口:java.net.*提供相关的类//定义地址URL url = new URL("http://www.google.com" ...

  7. JSP实现数据传递与保存

    业务逻辑: 1.登陆login.jsp 2.判断登陆是否成功check.jsp 3.登陆成功页面newsDetail.jsp 4.登陆失败转发到login.jsp 代码如下: <%@ page ...

  8. ARPSpoofing教程(二) - 获取网络设备中的详细地址信息

    WinPcap中文API  http://www.ferrisxu.com/WinPcap/html/index.html 1: #include"pcap.h" 2: #incl ...

  9. matlab连接sql数据库

    最近项目还涉及到matlab连接数据库,下面我就记录如何进行配置使得matlab能够连接sql数据库.由于最近工程做的多一些,所以分享的都在工程配置上,当初为了这些配置可是反复卸载与重装,算法其实也有 ...

  10. _mkdir

    [内容摘要]: C语言 在VS2013环境下使用_mkdir返回值是-,而且文件夹不存在,#include stdio.h#include direct.hmain(){)printf("无 ...