所以我的问题有点棘手,至少对我来说是这样。我正在尝试用 C++ 制作一款游戏来获得乐趣,基本上我觉得它就像飞扬的小鸟,小鸟永远不会移动,但小鸟背后的 map 总是从右向左移动。到目前为止,我所做的基本上是创建一个向下 5 个空格、横向 80 个空格的小网格。我基本上在 map 底部距顶部 5 个空格处绘制了下划线字符 _,而玩家是距左侧三个空格的“O”。问题是让高度第 5 个空间上方的 4 个空间移动但同时不移动玩家“O”。这是我的代码和到目前为止发生的事情的草图。对不起,这对我来说真的很难解释。我真的尽力了。问题是我不太了解它。
#include <iostream>
#include <cstdlib>
#include <string>
#include <conio.h>
using namespace std;
bool gameOver;
// Global variables
const int WIDTH = 80;
const int HEIGHT = 5;
int x, y;
int speedX;
int percentX;
int someArray[100];
string anotherArray[100];
enum eKeys { STOP = 0, SPACE};
int gameSpeed;
eKeys key;
// Function declarations
void input() {
if (_kbhit()) {
switch (_getch()){
case ' ':
key = SPACE;
break;
}
}
}
void draw() {
for (int j = 0; j < HEIGHT; j++) {
for (int i = 0; i < WIDTH; i++) {
if (j < 4) {
std::cout << " ";
if (WIDTH == 20) {
_sleep(10);
}
}
if(j == 4){
anotherArray[i] = "_";
std::cout << anotherArray[i];
}
if (j== 3 && i == 3) {
std::cout << "O";
}
if (j == 3 && i == 140) {
}
}
}
}
void setup() {
gameOver = false;
key = STOP;
x = 3;
y = 2;
}
void logic() {
switch (key) {
case SPACE:
break;
}
}
int main()
{
// Your code goes here
setup();
//while(gameOver == false){
draw();
input();
logic();
//}
// Make sure we place the end message on a new line
std::cout << endl;
// The following is system dependent. It will only work on Windows
std::system("PAUSE");
/*
// A non-system dependent method is below
cout << "Press any key to continue";
cin.get();
*/
return 0;
}
此代码在控制台中产生此输出.... “这是控制台的顶部”
哦
按任意键继续...
我想要的是“_____”上方的所有内容在玩家不移动的情况下从右向左移动。除非你按空格键跳跃然后“O”的y坐标会改变。我也知道这在类里面可能会做得更好,但我的书还没有深入到我的 c++ 类(class)才刚刚开始使用函数,所以现在最好远离它。
最佳答案
如果我没理解错的话,您想使用 C++ 级别的 io 和 conio.h 函数在 Windows 控制台上制作 ASCII 艺术游戏。对不起,你在路的尽头:
- C++ 级别(iostreams 和 C stdio 或 posix 函数)旨在以顺序方式输出文本数据,因此在屏幕上没有绝对定位可用
- conio.h 只包含一些在 MS/DOS 时代用于在键盘或屏幕上进行简单的 i/o 操作的函数 -> 也没有绝对定位
在过去的 MS/DOS 时代,屏幕内存通常可以在众所周知的地址直接访问,游戏(或应用程序)开发人员在需要特殊效果时利用它来绕过正常的 IO 功能。不确定控制台仿真是否支持它,我劝你不要使用它。
现在正确的方法是使用 Console functions的 WINAPI。它们由 conio 仿真和普通 io 函数在后台使用,但提供游戏所需的一切、绝对定位,甚至可以通过 ReadConsoleOutput
读写屏幕的任意区域和 WriteConsoleOutput
同时,您可以使用 ReadConsoleInput
从键盘获取输入事件。
当然,您不再与非 Windows 平台兼容,但由于您已经使用了 conio,因此我认为可移植性在这里不是问题。
关于C++ 在 win32 控制台中制作游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42435294/