gpt4 book ai didi

c++ - C++ 中的贪吃蛇游戏 : the snake head does not move as expected

转载 作者:太空宇宙 更新时间:2023-11-04 13:16:00 24 4
gpt4 key购买 nike

<分区>

tutorial 之后,我用vs2015社区写了一个简单的C++程序:

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
bool gameOver;
const int width=20;
const int height=20;
int x,y,fruitx,fruity,score; //coordinates for head and fruit
enum eDirection {STOP=0, LEFT, RIGHT, UP,DOWN};
eDir direction;

void setup(){
gameOver=false;
dir=STOP;
//initial position of head
x=width/2;
y=height/2;
fruitx=rand()%width;
fruity=rand()%height;
score=0;
}

void draw(){
system("cls");
int i,j;
//print the top wall
for(i=0;i<width;i++)
cout << "#";
cout << endl;
for(i=0;i<height;i++){
for(j=0;j<width;j++){
if (j==0)
cout << "#"; //print the left wall
if (i==y && j==x)
cout << "O"; //print the head
else if (i==fruity && j==fruitx)
cout << "F"; //print the fruit
else cout << " "; //print a space character
if (j==(width-1)) cout << "#"; //print the right wall
}
cout << endl;
}
//print the bottom wall
for(i=0;i<width;i++)
cout << "#";
cout << endl;
}

void input(){
if(_kbhit()){
switch(_getch()){
case 'a':
dir=LEFT;
break;
case 'd':
dir=RIGHT;
break;
case 'w':
dir=UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameOver=true;
break;
}
}
}

void logic(){
switch (dir){
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
}

int main(){
setup();
while(!gameOver){
draw();
input();
logic();
}
return 0;
}

该程序的预期行为如下:当我按“a”一次时,头部(“O”)向左移动一个字符长度。但是,它会快速向左移动直到消失,然后对我的键盘输入没有反应。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com