QT---简单的猜数字游戏

从1~1000中随机取一个数,然后猜,同时统计次数。
效果如下:

效果

代码:
widget.h

#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();
private slots:
    void myjudge();
private:
    Ui::Widget *ui;
    int t;
    int n;
    int m;
    void comp();
};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QTime>
#include <QMessageBox>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle(tr("猜猜看!"));
    ui->lineEdit->setValidator(new QIntValidator(1,1000,this));

    t=1;
    QTime time;
    time= QTime::currentTime();
    qsrand(time.msec()+time.second()*1000);
    n = qrand()%1000+1;
    qDebug()<<tr("随机数为:")<<n;

    connect(ui->okBtn,SIGNAL(clicked()),this,SLOT(myjudge()));

    connect(ui->quitBtn,SIGNAL(clicked()),this,SLOT(close()));

}

Widget::~Widget()
{
    delete ui;
}

void Widget::myjudge()
{
    QString str=ui->lineEdit->text();
    m=str.toInt();
    if(str.isEmpty())
        QMessageBox::warning(NULL,"warning","请输入一个正整数",QMessageBox::Ok);
    else
        comp();
}

void Widget::comp()
{
        if(m>n)
        {
            ui->label_2->setText(tr("您输入的数比它大!"));
        }
        else {
            if(m<n)
            {
                ui->label_2->setText(tr("您输入的数比它小!"));
            }
            else
                ui->label_2->setText(tr("恭喜!您用了 %1 次就猜中了!").arg(t));
        }

        t++;

}

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}
  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值