1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
#include <iostream> #include <vector> #include <conio.h> #include <windows.h> const int WIDTH = 20; const int HEIGHT = 10; class Game { private: std::vector<std::vector<char>> screen; int playerX, playerY; bool gameOver; public: Game() : playerX(WIDTH / 2), playerY(HEIGHT - 1), gameOver(false) { screen.resize(HEIGHT, std::vector<char>(WIDTH, ' ')); screen[playerY][playerX] = '^'; } void draw() { system("cls"); // Clear screen for (const auto& row : screen) { for (const auto& cell : row) { std::cout << cell; } std::cout << std::endl; } } void input() { if (_kbhit()) { char current = _getch(); if (current == 'a' && playerX > 0) { screen[playerY][playerX] = ' '; playerX--; screen[playerY][playerX] = '^'; } else if (current == 'd' && playerX < WIDTH - 1) { screen[playerY][playerX] = ' '; playerX++; screen[playerY][playerX] = '^'; } else if (current == 'q') { gameOver = true; } } } void logic() { // Game logic would go here, such as moving enemies or detecting collisions. // For simplicity, this example doesn't include advanced logic. } void run() { while (!gameOver) { draw(); input(); logic(); Sleep(100); // Sleep for a short period to control game speed } } }; int main() { Game game; game.run(); return 0; } |
Explanation
- Class Definition:
Game
class manages the game state.screen
is a 2D vector representing the game screen.playerX
andplayerY
store the player’s position.gameOver
is a flag to indicate if the game should end.
- Constructor:
- Initializes the screen with spaces and places the player at the bottom center of the screen.
- Member Functions:
draw()
: Clears the screen and then prints the current state of the screen.input()
: Checks for user input using_kbhit()
and_getch()
fromconio.h
. Moves the player left or right based on user input or ends the game if ‘q’ is pressed.logic()
: Placeholder for game logic (e.g., enemy movement, collision detection). Currently, it’s empty for simplicity.
- Run Loop (
run()
):- Continuously updates the game by calling
draw()
,input()
, andlogic()
. - Uses
Sleep(100)
to slow down the loop, controlling the game’s frame rate.
- Continuously updates the game by calling
- Main Function:
- Creates a
Game
object and starts the game loop by callingrun()
.
- Creates a