【发布时间】:2022-01-01 15:27:18
【问题描述】:
我一直在关注一些关于制作有点蛇游戏的教程,但不是一个完整的游戏,一切正常,我认为我几乎做对了,但我有两个问题
#include <bits/stdc++.h>
#include <conio.h>
#include <unistd.h>
using namespace std;
int side,x,y;
int fruitx,fruity,score,flag;
bool isOver;
void randomize();
void frame(int);
void userinp();
void game();
int main(){
do{
cout << "Enter the side of your frame!(not less than 20)\n";
cin >> side;
}while(side < 20);
randomize();
while(!isOver){
frame(side);
userinp();
game();
}
return 0;
}
void randomize(){
x = side/2;
y = side/2;
label1: fruitx = rand()%side;
if (fruitx == 0 || fruitx == side)
goto label1;
label2:
fruity = rand()%side;
if (fruity == 0 || fruity == side)
goto label2;
score = 0;
}
void frame(int s){
system("cls");
for(int i=1;i<=s;i++){
for(int j=1;j<=s;j++){
if(i == 1 || i == s || j == 1 || j == s)
cout << "*";
else{
if(i == x && j == y){
cout << "-";
}
else if(i == fruitx && j == fruity){
cout << "x";
}
else
cout << " ";
}
}
cout << "\n";
}
cout << "Your score: " << score << endl;
}
void userinp(){
if(kbhit()){
switch (getch()){
case 'a':
flag = 1;
break;
case 's':
flag = 2;
break;
case 'd':
flag = 3;
break;
case 'w':
flag = 4;
break;
default:
isOver = true;
}
}
}
void game(){
sleep(0.899);
switch (flag){
case 1:
y--;
break;
case 2:
x++;
break;
case 3:
y++;
break;
case 4:
x--;
break;
}
if (x < 0 || x > side || y < 0 || y > side){
x = side/2;
y = side/2;
}
if (x == fruitx && y == fruity) {
label3: fruitx = rand()%(side);
if (fruitx == 0)
goto label3;
label4: fruity = rand()%(side);
if (fruity == 0)
goto label4;
score++;
}
}
第一个问题:
使用
system"(cls")
帮助屏幕多次不下降有点使用sleep()函数,它要么太慢要么太快屏幕,是否有不同的方法来处理整个事情或者函数本身不适合在这里使用?
第二个问题:
每当我用 20 输入边时,我根本找不到水果本身,但是当它超过这个数字时,它确实向我展示了随机水果就好了所以有没有办法解决为什么只是 side = 20 它不会工作吗?
PS:如果除了这两个问题之外还有什么可以改进的,我将不胜感激..提前致谢!
【问题讨论】:
-
sleep(0.899);看起来睡眠是以秒为单位并且是一个整数值:https://man7.org/linux/man-pages/man3/sleep.3.html 我想你想要:https://man7.org/linux/man-pages/man3/usleep.3.html 但是还有一个关于在 MS Windows 上使用它的问题:https://stackoverflow.com/questions/5801813/c-usleep-is-obsolete-workarounds-for-windows-mingw/17283549 -
@drescherjm 好吧,这是有道理的,因为分数似乎都与 0 具有相同的速度
-
你可能想看看现代 c++ 代码的这个答案:https://stackoverflow.com/a/32319170/487892
-
@drescherjm 确实,我正在滚动浏览新功能的所有答案/了解 sleep() 本身......谢谢