21xrx.com
2025-04-14 00:43:14 Monday
文章检索 我的文章 写文章
50条c++贪吃蛇简易版代码
2023-07-05 11:05:49 深夜i     137     0
C++ 贪吃蛇 代码 简易版 50条

贪吃蛇是一种经典的计算机游戏,很多人都为它着迷。如果你对编程也有兴趣,那么可以考虑用C++语言来实现简易版贪吃蛇,下面是50条代码供参考。

1. 首先,我们需要包含头文件:

#include <iostream>
 #include <queue>
 #include <conio.h>
 #include <windows.h>
 using namespace std;

2. 接下来,定义一些变量,如画布大小、贪吃蛇长度、蛇头、蛇尾等:

const int weight = 20; // 屏幕宽度
 const int height = 20; // 屏幕高度
 int len = 3// 蛇的长度
 int speed = 150; // 贪吃蛇移动速度
 int snake[height * weight][2], head, tail; // 蛇的坐标
 int food[2]; // 食物坐标
 int direction; // 方向

3. 定义一个输出函数,用来在屏幕上输出贪吃蛇和食物:

void screen(int x, int y, char c) {
  COORD pos;
  pos.X = x;
  pos.Y = y;
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
  cout << c;
 }

4. 定义一个初始化函数,用来初始化贪吃蛇和食物:

void init() {
  head = tail = 1; // 蛇初始化成一条长度为1的蛇
  snake[1][0] = 5; // 蛇头位置
  snake[1][1] = 5;
  food[0] = 10; // 食物位置
  food[1] = 10;
  screen(food[0], food[1], '@'); // 在屏幕上输出食物
 }

5. 定义一个函数,用来检测贪吃蛇是否碰到自己或者墙壁:

bool check() {
  if (snake[head][0] <= 0 || snake[head][0] >= weight - 1 || snake[head][1] <= 0 || snake[head][1] >= height - 1) //判断是否碰到墙壁
   return true;
  
  for (int i = tail; i <= head - 1; i++) { // 判断是否碰到自己
   if (snake[head][0] == snake[i][0] && snake[head][1] == snake[i][1])
    return true;
   
  }
  return false;
 }

6. 定义一个函数,用来生成一个随机的食物坐标:

void generate_food() {
  bool flag = false;
  while (!flag) {
   food[0] = rand() % (weight - 2) + 1; // 产生随机食物位置
   food[1] = rand() % (height - 2) + 1;
   flag = true;
   for (int i = tail; i <= head; i++) { // 判断食物是否在蛇身上
    if (snake[i][0] == food[0] && snake[i][1] == food[1])
     flag = false;
     break;
    
   }
  }
  screen(food[0], food[1], '@'); // 在屏幕上输出食物
 }

7. 定义一个函数,用来移动贪吃蛇:

void move() {
  int x = snake[head][0];
  int y = snake[head][1];
  screen(x, y, ' '); // 在屏幕上删除蛇头
  switch (direction) { // 根据移动方向更新蛇头坐标
   case 1: y--; break; //上
   case 2: x++; break; //右
   case 3: y++; break; //下
   case 4: x--; break; //左
  }
  snake[++head][0] = x; // 更新蛇头
  snake[head][1] = y;
  screen(x, y, '*'); // 在屏幕上输出蛇头
  if (x == food[0] && y == food[1]) { // 如果吃到了食物
   generate_food(); // 重新生成食物
   len++; // 蛇的长度加1
  } else { // 没有吃到食物
   screen(snake[tail][0], snake[tail][1], ' '); // 在屏幕上删除蛇尾
   tail++; // 蛇尾向前移动
  }
  if (check()) { // 检测是否碰到了自己或者墙壁
   cout << "Game over!" << endl;
   exit(0); // 结束程序
  }
  Sleep(speed); // 休眠0.1秒
 }

8. 接下来,我们初始化贪吃蛇和食物,并开始游戏循环:

int main() {
  srand((unsigned)time(NULL)); // 初始化随机数种子
  init(); // 初始化贪吃蛇和食物
  while (true) { // 游戏循环
   if (kbhit()) { // 判断是否有键盘输入
    char c = getch();
    if (c == 'w' && direction != 3) direction = 1;
    else if (c == 'd' && direction != 4) direction = 2;
    else if (c == 's' && direction != 1) direction = 3;
    else if (c == 'a' && direction != 2) direction = 4;
   }
   move(); // 移动贪吃蛇
  }
  return 0;
 }

9. 这样我们就完成了一个简易版的贪吃蛇游戏,可以通过改变变量来调整游戏难度,让玩家享受到不同的游戏体验。

  
  

评论区