C ++ ASCII游戏控制台屏幕闪烁

时间:2015-10-02 19:01:20

标签: c++ ascii tile

我正在使用C ++制作一个简单的游戏 它只是一个带有ASCII地图的平铺游戏。 游戏本身运行正常,但当我移动我的播放器时,控制台屏幕(地图)闪烁,我不知道如何解决这个问题。有任何帮助,谢谢!

代码:

#include <iostream>
#include <windows.h>
#include <conio.h>
#include <ctime>
#include <vector>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;

vector<string> map;
int playerX = 10;
int playerY = 10;
int oldPlayerX;
int oldPlayerY;
bool done = false;

void loadMap();
void printMap();
void setPosition(int y, int x);
void eventHandling();

int main()
{
    loadMap();
    map[playerY][playerX] = '@';
    printMap();
    while(!done){
        eventHandling();
        printMap();
    }
    exit(1);
    return 0;
}

void eventHandling(){
    char command;
    command = _getch();
    system("cls");
    oldPlayerX = playerX;
    oldPlayerY = playerY;

    if(command == 'w'){
        playerY--;
    }else if(command == 'a'){
        playerX--;
    }else if(command == 'd'){
        playerX++;
    }else if(command == 's'){
        playerY++;
    }

    if(map[playerY][playerX] == '#'){
        playerX = oldPlayerX;
        playerY = oldPlayerY;
    }

    setPosition(playerY,playerX);

}

void setPosition(int y, int x){
    map[oldPlayerY][oldPlayerX] = '.';
    map[y][x] = '@';
}

void  printMap(){
    for(int i = 0 ; i < map.size() ; i++){
        cout << map[i] << endl;
    }
}

void loadMap(){
    ifstream file;
    file.open("level.txt");

    string line;
    while(getline(file, line)){
        map.push_back(line);
    }
}

3 个答案:

答案 0 :(得分:3)

std::cout不打算以这种方式使用。

您应该参考目标操作系统和环境的系统特定API。例如,对于Windows,您应该使用Console API functions来达到目的。这些函数在Wincon.h包含文件中定义。

答案 1 :(得分:0)

清除适用于多种系统的屏幕的一种方法是打印换页符'h1-1'。 Linux控制台支持这一点,如果您加载了\f,MS-DOS也是如此。 Unix有ansi.sysncurses来抽象这些函数。

答案 2 :(得分:0)

如果您使用双缓冲系统,只有每帧需要覆盖的内容才会更改,这也会有所帮助。 IO操作非常昂贵,所以应该最小化。

Cameron Gives a Very Thorough Description of How to Do this Here

但实质上,你要使用两个数组,一个包含地图的当前状态,一个包含先前的状态,只写入已更改的特定位置。

相关问题