我们做一个猜拳游戏 先做界面后写功能 这个界面有谁是可以被修改获取的就是三个label,也就是结果,因此他们三个就是全局变量 界面: 包含头文件 main函数(去掉const) 环境初始化 创建窗口设置属性 创建布局、放入窗口中 创建label、button,放入布局 信号连接 显示窗口上面的所有的控件 主事件循环 return 0; 功能: 1.找到按钮的创建位置 2.在创建位置下方写信号连接 3.发现信号连接中的回调函数不存在,去定义 4.写函数体: 4.1先知道自己到底按下了什么按钮 4.2将按钮对应的文本设置到“硕哥出的结果显示label上” 4.3电脑随机生成012 0代表石头、1代表布、2代表剪刀 随机数初始化种子为:srand(time(NULL)); int dn_numb = rand()%3; 一个很大的数除3取余=0/1/2 判断你生成的是012的哪一个ge将对应的石头剪刀布设置上去 比较自己的012与随机生成的012 将最后的结果设置到中间的label上,用c语言写出这个游戏的代码
时间: 2024-03-13 12:42:40 浏览: 26
很高兴为您提供代码,以下是一个简单的猜拳游戏的实现:
```c++
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 窗口设置
QWidget window;
window.setWindowTitle("猜拳游戏");
window.setGeometry(100, 100, 280, 150);
// 布局设置
QVBoxLayout *layout = new QVBoxLayout(&window);
// 硕哥出的结果显示的label
QLabel *userLabel = new QLabel("石头/剪刀/布", &window);
userLabel->setAlignment(Qt::AlignCenter);
layout->addWidget(userLabel);
// 中间的结果显示的label
QLabel *resultLabel = new QLabel("VS", &window);
resultLabel->setAlignment(Qt::AlignCenter);
layout->addWidget(resultLabel);
// 电脑出的结果显示的label
QLabel *computerLabel = new QLabel("石头/剪刀/布", &window);
computerLabel->setAlignment(Qt::AlignCenter);
layout->addWidget(computerLabel);
// 按钮设置
QHBoxLayout *buttonLayout = new QHBoxLayout;
QPushButton *rockButton = new QPushButton("石头", &window);
QPushButton *scissorButton = new QPushButton("剪刀", &window);
QPushButton *paperButton = new QPushButton("布", &window);
buttonLayout->addWidget(rockButton);
buttonLayout->addWidget(scissorButton);
buttonLayout->addWidget(paperButton);
layout->addLayout(buttonLayout);
// 信号连接
QObject::connect(rockButton, &QPushButton::clicked, [&](){
userLabel->setText("石头");
int computer = rand() % 3;
if (computer == 0)
computerLabel->setText("石头");
else if (computer == 1)
computerLabel->setText("剪刀");
else
computerLabel->setText("布");
if (computer == 0)
resultLabel->setText("平局");
else if (computer == 1)
resultLabel->setText("你赢了");
else
resultLabel->setText("你输了");
});
QObject::connect(scissorButton, &QPushButton::clicked, [&](){
userLabel->setText("剪刀");
int computer = rand() % 3;
if (computer == 0)
computerLabel->setText("石头");
else if (computer == 1)
computerLabel->setText("剪刀");
else
computerLabel->setText("布");
if (computer == 0)
resultLabel->setText("你输了");
else if (computer == 1)
resultLabel->setText("平局");
else
resultLabel->setText("你赢了");
});
QObject::connect(paperButton, &QPushButton::clicked, [&](){
userLabel->setText("布");
int computer = rand() % 3;
if (computer == 0)
computerLabel->setText("石头");
else if (computer == 1)
computerLabel->setText("剪刀");
else
computerLabel->setText("布");
if (computer == 0)
resultLabel->setText("你赢了");
else if (computer == 1)
resultLabel->setText("你输了");
else
resultLabel->setText("平局");
});
window.show();
return app.exec();
}
```
这是一个基于Qt框架的实现,您可以复制到Qt Creator中进行编译运行。