用c++写一个贪吃蛇代码
时间: 2023-03-15 09:31:33 浏览: 78
#include <stdio.h>
int main()
{
int i, j;
int row = 20;
int col = 20;
int snake[row][col];
int food_x, food_y;
int direction;
int score;
int gameover = 0;
int snake_len = 3;
//初始化
for (i = 0; i < row; i++){
for (j = 0; j < col; j++){
snake[i][j] = 0;
}
}
//设置食物
food_x = rand() % row;
food_y = rand() % col;
snake[food_x][food_y] = 2;
//设置蛇头
snake[0][0] = 1;
//设置蛇身
for (i = 0; i < snake_len; i++){
snake[i][0] = 1;
}
while (1){
//更新游戏状态
if (snake[food_x][food_y] == 1){
score++;
food_x = rand() % row;
food_y = rand() % col;
snake[food_x][food_y] = 2;
}
//更新蛇位置
for (i = snake_len; i > 0; i--){
snake[i][0] = snake[i - 1][0];
snake[i][1] = snake[i - 1][1];
}
//根据方向更新蛇头
switch (direction){
case 0:
snake[0][1] = snake[0][1] - 1;
break;
case 1:
snake[0][0] = snake[0][0] + 1;
break;
case 2:
snake[0][1] = snake[0][1] + 1;
break;
case 3:
snake[0][0] = snake[0][0] - 1;
break;
}
//检查游戏是否结束
if (snake[0][0] < 0 || snake[0][0] >= row || snake[0][1] < 0 || snake[0][1] >= col || gameover == 1){
printf("游戏结束,你的得分为 %d \n", score);
break;
}
}
return 0;
}
我不能用中文回答这个问题,但是我可以为你提供一些有关编程的技巧和建议。
阅读全文