zoukankan      html  css  js  c++  java
  • 打地鼠游戏(3)

    需求:随机弹出1-3个老鼠

    实现:利用一个定时器,设置定时器周期到之后,置换掉1-3个图元的图片。

    1、置换图片的方法:

     1 #ifndef MYITEM_H  //--------------myitem.h
     2 #define MYITEM_H
     3 #include <QGraphicsPixmapItem>
     4 
     5 class myitem : public QGraphicsPixmapItem
     6 {
     7 public:
     8     myitem();
     9     void setPic(QString src);  //置换图片
    10 };
    11 
    12 #endif // MYITEM_H
     1 #include "myitem.h"
     2 #include <QPixmap>
     3 
     4 myitem::myitem()
     5 {   /*
     6     void setPixmap(const QPixmap &pixmap);
     7     绑定图片到图元
     8     */
     9     this->setPixmap(QPixmap(":/mouse/pic/bg1.png"));
    10 }
    11 
    12 //重新设置图片,从而实现更换图片的效果
    13 void myitem::setPic(QString src){
    14     this->setPixmap(src);
    15 }

    2、绑定信号与槽,开启定时器:

     1 MyScene::MyScene(QObject *parent) : QGraphicsScene(parent)
     2 {
     3 
     4     //添加图元到场景
     5     for(int i = 0;i<16;i++){
     6         this->item[i] = new myitem();
     7         //设置坐标
     8         /*一维数组转换为二维数组,下面宽、高的倍数组合
     9         0 0,0 1,0 2,0 3
    10         1 0,1 1,1 2,1 3
    11         2 0,2 1,2 2,2 3
    12         3 0,3 1,3 2,3 3
    13         */
    14         double x = i/4 * this->item[i]->boundingRect().width();
    15         double y = i%4 * this->item[i]->boundingRect().height();
    16         this->item[i]->setPos(x,y);
    17         this->addItem(this->item[i]);
    18     }
    19 
    20     //绑定一个定时器,等定时周期到触发一个随机数[0-15],然后让场景中的一个图元的图片更换
    21     this->p_timer = new QTimer();
    22     connect(this->p_timer, SIGNAL(timeout()), this, SLOT(update_my_item())); //绑定定时器和槽函数
    23     this->p_timer->start(1000); //1s
    24 
    25 }
     1 #include <stdlib.h>
     2 #include <time.h>
     3 
     4 void MyScene::update_my_item(){
     5     //每次出现老鼠之前,先恢复到所有图元为无老鼠的样式图片
     6     for(int i = 0;i<16;i++){
     7         this->item[i]->setPic(":/mouse/pic/bg1.png");
     8     }
     9 
    10     srand(time(NULL)); //设置随机数种子
    11 
    12     //一次性允许显式最多三个老鼠
    13     int count = rand()%3 +1;
    14     for(int k=1;k<=3;k++){
    15         int i = rand()%16;
    16         this->item[i]->setPic(":/mouse/pic/mouse.png");
    17     }
    18 }

    演示效果:

    内在的趣味,表面的繁琐
  • 相关阅读:
    Kubernetes-一文详解ServiceAccount与RBAC权限控制
    删除无用的docker镜像与容器
    How do I write one to many query in Dapper.Net?
    c# 使用反射Reflection的Emit实现动态创建元数据及可执行文件
    IE浏览器下bootStrap form-control input输入框不显示兼容性问题
    WPF控件从一个窗口移动到另一个窗口,特别适合实时刷新的
    添加/扫描显示二维码中的换行之【另类视野】
    各浏览器官方离线版下载地址
    CentOS挂载NTFS
    System.Data.SQLite.Core for .NET 5 Core manual reference
  • 原文地址:https://www.cnblogs.com/data1213/p/10851165.html
Copyright © 2011-2022 走看看