当前位置: 首页 > article >正文

【C++】控制台小游戏

移动:W向上,S上下,A向左,D向右

程序代码:

#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;bool gameOver;
const int width = 20;
const int height = 17;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir;void ClearScreen() {HANDLE hOut;COORD Position;hOut = GetStdHandle(STD_OUTPUT_HANDLE);Position.X = 0;Position.Y = 0;SetConsoleCursorPosition(hOut, Position);
}void Setup() {gameOver = false;dir = STOP;x = width / 2;y = height / 2;fruitX = rand() % width;fruitY = rand() % height;score = 0;
}void Draw() {ClearScreen();for (int i = 0; i < width + 2; i++)cout << "#";cout << endl;for (int i = 0; i < height; i++) {for (int j = 0; j < width; j++) {if (j == 0)cout << "#";if (i == y && j == x)cout << "O";else if (i == fruitY && j == fruitX)cout << "*";else {bool print = false;for (int k = 0; k < nTail; k++) {if (tailX[k] == j && tailY[k] == i) {cout << "o";print = true;}}if (!print) cout << " ";}if (j == width - 1)cout << "#";}cout << endl;}for (int i = 0; i < width + 2; i++)cout << "#";cout << endl;cout << "Score:" << score << 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() {int prevX = tailX[0];int prevY = tailY[0];int prev2X, prev2Y;tailX[0] = x;tailY[0] = y;for (int i = 1; i < nTail; i++) {prev2X = tailX[i];prev2Y = tailY[i];tailX[i] = prevX;tailY[i] = prevY;prevX = prev2X;prevY = prev2Y;}switch (dir) {case LEFT:x--;break;case RIGHT:x++;break;case UP:y--;break;case DOWN:y++;break;default:break;}if (x >= width) x = 0;else if (x < 0) x = width - 1;if (y >= height) y = 0;else if (y < 0) y = height - 1;for (int i = 0; i < nTail; i++)if (tailX[i] == x && tailY[i] == y)gameOver = true;if (x == fruitX && y == fruitY) {score += 10;fruitX = rand() % width;fruitY = rand() % height;nTail++;}
}int main() {Setup();while (!gameOver) {Draw();Input();Logic();Sleep(100);}return 0;
}

运行结果

http://www.lryc.cn/news/2384098.html

相关文章:

  • 配合本专栏前端文章对应的后端文章——从模拟到展示:一步步搭建传感器数据交互系统
  • React中常用的钩子函数:
  • springboot IOC
  • java面试每日一背 day2
  • Ajax01-基础
  • (37)服务器增加ipv6配置方法
  • 生成树协议(STP)配置详解:避免网络环路的最佳实践
  • 面向 C 语言项目的系统化重构实战指南
  • 网络层——蚂蚁和信鸽的关系VS路由原理和相关配置
  • Python Pandas库简介及常见用法
  • 第十六届蓝桥杯复盘
  • 【已解决】HBuilder X编辑器在外接显示器或者4K显示器怎么界面变的好小问题
  • 直线型绝对值位移传感器:精准测量的科技利刃
  • 解决服务器重装之后vscode Remote-SSH无法连接的问题
  • AI 招聘系统科普:如何辨别真智能与伪自动化
  • Ansible模块——管理100台Linux的最佳实践
  • 从0开始学习大模型--Day09--langchain初步使用实战
  • C++中的菱形继承问题
  • 订单越来越到导致接口列表查询数据缓慢解决思路
  • word格式相关问题
  • 网络-MOXA设备基本操作
  • 飞桨paddle import fluid报错【已解决】
  • 测试工程师要如何开展单元测试
  • IPv4 地址嵌入 IPv6 的前缀转换方式详解
  • 野火鲁班猫(arrch64架构debian)从零实现用MobileFaceNet算法进行实时人脸识别(三)用yolov5-face算法实现人脸检测
  • IS-IS 中间系统到中间系统
  • 【图像生成大模型】HunyuanVideo:大规模视频生成模型的系统性框架
  • GitHub 趋势日报 (2025年05月19日)
  • 如何使用Java生成pdf报告
  • HarmonyOS鸿蒙应用规格开发指南