0

So I want to play around with c++ and create a game in the command line. I found a tutorial online and took some bits from it. This code outputs a simple game board area(You have to change the size of your debug screen window for it to appear correctly).

I wanted to know how to create a character - lets say 'A' - move across the screen as the user inputs up, down, left, and right on the keyboard.

I didn't see much information on this topic when I looked on my own, any help is appreciated!

C++, Visual studio

#include <iostream>
using namespace std;
#include <Windows.h>
int nFieldWidth = 12;
int nFieldHeight = 18;
unsigned char *pField = nullptr;
int nScreenWidth = 80;
int nScreenHeight = 30;

int main()
{
     pField = new unsigned char[nFieldWidth*nFieldHeight]; // Create play field buffer
     for (int x = 0; x < nFieldWidth; x++) // Board Boundary
        for (int y = 0; y < nFieldHeight; y++)
            pField[y*nFieldWidth + x] = (x == 0 || x == nFieldWidth - 1 || y == nFieldHeight - 1) ? 9 : 0;

wchar_t *screen = new wchar_t[nScreenWidth*nScreenHeight];
for (int i = 0; i < nScreenWidth*nScreenHeight; i++) screen[i] = L' ';
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole);
DWORD dwBytesWritten = 0;

bool bGameOver = false;

while (!bGameOver) {
    //Draw Field
    for (int x = 0; x < nFieldWidth; x++)
        for (int y = 0; y < nFieldHeight; y++)
            screen[(y + 2)*nScreenWidth + (x + 2)] = L" ABCDEFG=#"[pField[y*nFieldWidth + x]];
    WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenHeight, { 0,0 }, &dwBytesWritten);
}


return 0;
  }

1 Answers1

0

See Setting the Cursor Position in a Win32 Console Application

But as a well-meant tip: Don't start learning C++ with something like a console game - you write less C++ than C with a little bit of class. If you already know C, you should start with classes and class methods to get started in C++ (and avoid globals). A simple calculator or similar is much more useful here. After you have done classes, I would recommend you to work with smart pointers (std::shared_ptr, std::weak_ptr, std::unique_ptr, ...).

Wolfgang
  • 320
  • 3
  • 12