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. ps还能用脚本切片?

    最近在慕课网上看有关于ps切图的视频,发现ps 切片的水还挺深的.这相当于我的一篇学习笔记吧.对于ps的基本切图我觉得对于前端人员来说就是a piece of cake.但是对于ps的精准切图,我不知 ...

  2. 【POJ 3525】Most Distant Point from the Sea(直线平移、半平面交)

    按逆时针顺序给出n个点,求它们组成的多边形的最大内切圆半径. 二分这个半径,将所有直线向多边形中心平移r距离,如果半平面交不存在那么r大了,否则r小了. 平移直线就是对于向量ab,因为是逆时针的,向中 ...

  3. an important difference between while and foreach on Perl

    while (<STDIN>) { } # will read from standard input one line at a time foreach (<STDIN>) ...

  4. linux 下更改 blast+ version

    to 2.2.30 cd /usr/bin sudo su mv blastdb_aliastool blastdb_aliastool_2.25 mv blastdbcheck blastdbche ...

  5. c# 获取iis地址

    using System;using System.Collections.Generic;using System.DirectoryServices;using System.Linq;using ...

  6. 【BZOJ-4455】小星星 容斥 + 树形DP

    4455: [Zjoi2016]小星星 Time Limit: 10 Sec  Memory Limit: 512 MBSubmit: 204  Solved: 137[Submit][Status] ...

  7. CruiseControl.NET/CCNET配置(SVN+MSBuild+BAT+FTP)

    CCNET目前最新版本为1.8.5,官方很久没更新过了,如果投入生成环境使用,建议全部转到Jenkins上. 可以直接在这里下载:http://www.cnblogs.com/EasonJim/p/5 ...

  8. VS调试时同时启动多个项目解决方法

    选中要设置的项目,不要右击里面的属性,而是按f4时显示属性,下面总是在调试时启动设为false.

  9. linux ipv6临时地址

    在Ubuntu系统上想要通过ipv6来上网,结果发现通过DHCP获取到了ipv6地址却无法连接外网. ping6 ipv6.google.com 数据包有去无回,100% loss . 奇怪的是通过D ...

  10. ofo走出校园观察:市场定位导致产品错位?

    Ofo和摩拜单车虽然同样都是做单车共享,但实际上两者在最初的市场定位是有明显的差异的,因此提供的产品方案也存在巨大的差异. 市场定位不同,导致产品方案的巨大差异 摩拜单车一开始就定位于开放市场,充分的 ...