QT simple to write greedy snake __qt

Source: Internet
Author: User

The general idea is to circle the grid by drawing a rectangle. A small red square indicates that the snake's head is black, and that the snake's green indicates that the food is represented by a two-dimensional array of snake-headed snakes. The corresponding XY coordinates the movement of the snake is mainly after feeding the mobile part of the code to show the main game related files to select File code corresponding to the effect map PC version Android phone Version

General Ideas loops the grid by drawing a rectangle.

    Draw game disk
    Qpainter painter (this);
    for (int x = 0; x < COL; ++x) {
      for (int y = 0; y < ROW; ++y) {
          painter.drawrect qrect (x*rectwidth, Y*rectheig HT, Rectheight, rectheight));
      }
    
The snake head is represented by a small red square, and the black indicates the snake body, and the green means food
    Draw Food
    Painter.fillrect (Qrect (Foodposition[0]*rectwidth, Foodposition[1]*rectheight, Rectheight, RectHeight), Qt::green);

    Draw Snake head
    painter.fillrect (Qrect (Snake[0][0]*rectwidth, Snake[0][1]*rectheight, Rectheight, rectheight), Qt::red);

    Draw Snake Body for
    (int snakeboy = 1; snakeboy <= m_foodcount; ++snakeboy) {
        Painter.fillrect (qrect ]*rectwidth, Snake[snakeboy][1]*rectheight, Rectheight, rectheight), qt::black);
    
The corresponding x,y coordinates are represented by a two-dimensional array, which corresponds to the snake head.

int snake[100][2]; Save the snakes, each node coordinates.

The length of the snake is defined here to be no more than 100, and of course it can be increased, 2 represents x and Y, Snake[0][0] represents the x-coordinate of the snake head, and snake[0][1] represents the y-coordinate of the snake head. The corresponding snake body uses snake[k][0] to denote X, snake[k][1] is Y and K is between 1 and 99. The movement of snakes is mainly the movement after feeding.

That is, the head of the snake moved forward, the coordinates of the snake head changed, the original snake head coordinates for the first section of the body's coordinates, the original first body coordinates for now the second section of the coordinates, that is, all coordinates move forward a section of code to show the main game related files

It was handled by the place where Mark wrote the words "#".
. h Files

"Ifndef widget_h" define Widget_h "include <QWidget> namespace Ui {class WIDGET;}
    Class Widget:public Qwidget {q_object public:explicit Widget (qwidget *parent = 0);

~widget ();
    protected:virtual void PaintEvent (qpaintevent* event);


virtual void Resizeevent (qresizeevent* event);
    Private:bool Checkeatfood ();
    void Creatfood ();
    BOOL Dealguojie ();
    void Drawsnakehead ();
    void Flashscore ();
    void Gameover ();
    void Init ();
    void InitData ();
    void Initandirostyle ();
    void Initbackground ();
    void Initconnect ();
    void Initwindows ();
    void Snakeheadrun ();
    void Snakerun ();

void upgrade ();

    Private Slots:void slottimeout ();

    void on_upbutton_clicked ();

    void on_leftbutton_clicked ();

    void on_downbutton_clicked ();

    void on_rightbutton_clicked ();

void on_returnbutton_clicked ();
    Private:ui::widget *ui;
    Qtimer *m_timer; int snake[100][2]; Save snake each node coordinates int *snakebody[100][2];
    int m_direction;
    int foodposition[2];
    int m_foodcount;
    int M_currentgrade;
    int M_upgradescore;
int m_currentspeed;

}; #endif//Widget_h

. cpp files

Include "Widget.h" include "Ui_widget.h" include "qkeyevent> include" qpainter> include "qtimer> include" Qdebug > include "qmessagebox> include" qevent> include qmenu> include "qcontextmenuevent> include" Qapplication> include "qscreen> include" qdesktopwidget> ifndef COL define COL endif ifndef row define row 2  2 endif ifndef rectwidth define rectwidth endif ifndef rectheight define rectheight endif up 0 define down 1 Define left 2 define right 3 Widget::widget (Qwidget *parent): Qwidget (parent), UI (new Ui::widget), M_time R (New Qtimer (This)), M_direction (0), M_foodcount (0), M_currentgrade (1), M_upgradescore (MB), m_current
    Speed {ui->setupui (this);
Init ();

} widget::~widget () {Delete UI;}
    void Widget::p aintevent (qpaintevent* event) {//Draw game disk Qpainter painter (this); for (int x = 0; x < COL; ++x) {for (int y = 0; y < ROW; ++y) {Painter.drawrect (Qrect (X*rectwidth, Y*rectheight, Rectheight, rectheight)); ///Draw food Painter.fillrect (Qrect foodposition[0]*rectwidth, Foodposition[1]*rectheight, Rectheight, RectHeigh

    T), Qt::green);

    Draw Snake head Painter.fillrect (qrect (Snake[0][0]*rectwidth, Snake[0][1]*rectheight, Rectheight, rectheight), Qt::red); Draw snake body for (int snakeboy = 1; snakeboy <= m_foodcount; ++snakeboy) {Painter.fillrect (qrect
    ]*rectwidth, Snake[snakeboy][1]*rectheight, Rectheight, rectheight), qt::black);
    } void Widget::resizeevent (Qresizeevent* event) {initbackground ();
    Qsize size = Qapp->desktop ()->screengeometry (). Size ();
Resize (size);
    BOOL Widget::checkeatfood () {//If the x-coordinate of the head is equal to the x-coordinate of the food, and the y-coordinate of the snake's head equals the y-coordinate of the food, it means that food is not eaten.
        if (snake[0][0] = = Foodposition[0] && snake[0][1] = = Foodposition[1]) {+ + M_foodcount;
        Upgrade ();
        Flashscore (); Creatfood (); Produce a new food}//Snake body add for (int snId = M_foodcount; Snid > 0;
       --snid) {snake[snid][0] = snake[snid-1][0];
    SNAKE[SNID][1] = snake[snid-1][1];
} snakeheadrun ();
    } void Widget::creatfood () {foodposition[0] = Qrand ()% COL;

    FOODPOSITION[1] = Qrand ()% ROW; Prevent food from being produced on snakes for (int bodyid = 0; Bodyid <= m_foodcount; + + Bodyid) {if (foodposition[0) = = snake[bodyid][
            0] && foodposition[1] = = Snake[bodyid][1]) {foodposition[0] = Qrand ()% COL-1;
        FOODPOSITION[1] = Qrand ()% ROW-1; BOOL Widget::d Ealguojie () {if (snake[0][0] > (COL-1) | | snake[0][0] < 0 | | snake[0][1] > (ROW- 1) | |
        Snake[0][1] < 0) {Gameover ();
    return true; for (int i = 1; I <= m_foodcount ++i) {if (snake[0][0] = = Snake[i][0] && snake[0][1] = = Snake[i]
            [1]) {Gameover ();
        return true;
return false;
   void Widget::d rawsnakehead ()//Picture snake Head Snake[0][0] = Qrand ()% COL;

    SNAKE[0][1] = Qrand ()% ROW;
Direction m_direction = Qrand ()% 4;
    } void Widget::flashscore () {Ui->leveledit->settext (Qstring::number (M_currentgrade));
Ui->scoreedit->settext (Qstring::number (m_foodcount*10));
    } void Widget::gameover () {m_timer->stop ();
    Qmessagebox::information (This, Qstring::fromutf8 ("Waring"), Qstring::fromutf8 ("Game over"));
    Ui->leveledit->settext (Qlatin1string ("1"));
Ui->scoreedit->settext (Qlatin1string ("0"));
    } void Widget::init () {Initandirostyle ();
    Drawsnakehead ();
    Creatfood ();
    Initbackground ();
    Initconnect ();
Initwindows ();
    } void Widget::initandirostyle () {QScreen *screen = Qapp->primaryscreen ();
    Qfont f = qapp->font ();

    int pixelsize = (f.pointsize () * Screen->logicaldotsperinch ())/(72*1.5);
    Qfont Andirofont;

    Andirofont.setpixelsize (pixelsize);
    Ui->upbutton->setfont (Andirofont); Ui->leftbutton->setfont (Andirofont);
    Ui->downbutton->setfont (Andirofont);

    Ui->rightbutton->setfont (Andirofont);
    Ui->label->setfont (Andirofont);

    Ui->label_2->setfont (Andirofont);
    Ui->scoreedit->setfont (Andirofont);
Ui->leveledit->setfont (Andirofont);
    } void Widget::initbackground () {Setautofillbackground (true);
    Qpalette Palette;
    Palette.setbrush (Qpalette::background, Qbrush (Qpixmap (":/images/background.png"). Scaled (This->size ()));

    SetPalette (palette);
    Ui->returnbutton->seticon (Qicon (":/images/return_normal.png"));
    Ui->returnbutton->seticonsize (qsize (100, 60));
Ui->returnbutton->setflat (TRUE);
    } void Widget::initconnect () {Connect (M_timer, SIGNAL (timeout ()), this, SLOT (Slottimeout ()));
M_timer->start (M_currentspeed);
    } void Widget::initdata () {Ui->leveledit->settext (qlatin1string ("1"));

    Ui->scoreedit->settext (Qlatin1string ("0")); m_direction = 0;
    M_foodcount = 0;
    M_currentgrade = 1;
    M_upgradescore = 100;
M_currentspeed = 500;
    } void Widget::initwindows () {setwindowtitle ("greedy snake");
Setwindowicon (Qicon (":/images/ico.png"));
        } void Widget::snakeheadrun () {//Snake moves the switch according to direction (M_direction) {case up:--snake[0][1];

    Break
        Case down: + + snake[0][1];

    Break
        Case left:--snake[0][0];

    Break
        Case right: + + snake[0][0];

    Break
    Default:break;
    } void Widget::snakerun () {//Snake moves according to direction if (Dealguojie ()) return;
    Checkeatfood ();
Update (); } void Widget::upgrade () {qdebug () << "The Ui->scoreedit->text (). ToInt () is:" << ui->scoreedit- >text () ToInt () << "M_upgradescore * m_currentgrade" << M_upgradescore * m_currentgrade
    ;< M_upgradescore << M_currentgrade; if (Ui->scoreedit->text (). ToInt () >= M_upgradescore * m_currentgrade) {M_upgradescore *= 2;
        + + M_currentgrade;
        if (M_currentspeed >) {m_currentspeed = 10;
        } m_timer->stop ();
        Qmessagebox::information (This, Qstring::fromutf8 ("Waring"), Qstring::fromutf8 ("Upgrade success"));
    M_timer->start (M_currentspeed);

} void Widget::slottimeout () {Snakerun ();}

void widget::on_upbutton_clicked () {m_direction = up;}

void widget::on_leftbutton_clicked () {m_direction = left;}

void widget::on_downbutton_clicked () {m_direction = down;}

void widget::on_rightbutton_clicked () {m_direction = right;}
    void widget::on_returnbutton_clicked () {initdata ();
Close ();
 }
make a selection file code

. h

"Ifndef menuewidget_h
" define Menuewidget_h

"include <QWidget>

namespace Ui {
class Menuewidget;
}

Class Menuewidget:public Qwidget
{
    q_object public

:
    explicit Menuewidget (Qwidget *parent = 0);
    ~menuewidget ();

Protected:
    virtual void PaintEvent (qpaintevent* event);

Private slots:
    void on_startbutton_clicked ();

    void on_leavebutton_clicked ();

Private:
    void init ();
    void Initbackground ();
    void Initwindows ();

Private:
    ui::menuewidget *ui;

#endif//Menuewidget_h

. cpp

#include "menuewidget.h" #include "ui_menuewidget.h" #include "widget.h" Menuewidget::menuewidget (Qwidget *parent):
    Qwidget (parent), UI (new Ui::menuewidget) {ui->setupui (this);
Init ();

} menuewidget::~menuewidget () {Delete UI;}

void Menuewidget::p aintevent (qpaintevent* event) {Initbackground ();}
   void menuewidget::on_startbutton_clicked () {widget *mywidget = new Widget (this);
   Mywidget->setwindowflags (Qt::windowminmaxbuttonshint&qt::windowclosebuttonhint);
    Mywidget->showfullscreen ();
Mywidget->show ();

} void Menuewidget::on_leavebutton_clicked () {exit (0);}
    void Menuewidget::init () {initbackground ();
Initwindows ();
    } void Menuewidget::initbackground () {Setautofillbackground (true);
    Qpalette Palette; Palette.setbrush (Qpalette::background, Qbrush (Qpixmap (":/images/main_home_background.png"). Scaled (this->size
    ())));

    SetPalette (palette); Ui->startbutton->seticon (Qicon (":/imageS/start_normal.png "));
    Ui->startbutton->seticonsize (Qsize (240, 240));

    Ui->startbutton->setflat (TRUE);
    Ui->leavebutton->seticon (Qicon (":/images/quit_normal.png"));
    Ui->leavebutton->seticonsize (Qsize (270, 270));

Ui->leavebutton->setflat (TRUE);
    } void Menuewidget::initwindows () {setwindowtitle ("greedy snake");
Setwindowicon (Qicon (":/images/ico.png"));
 }
corresponding Effect Chart PC version

1. Operation Interface Effect Chart

2. Run-time Effect Diagram

3. Hit the boundary effect chart
Android Mobile Version

1. Mobile version of the operating interface

2. Mobile version of the game interface


3. Mobile Version Boundary treatment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.