Untitled
unknown
plain_text
3 years ago
2.1 kB
6
Indexable
#include <iostream> #include <vector> using namespace std; const int WIDTH = 5; // the width of the game board const int HEIGHT = 5; // the height of the game board // the game board, represented as a 2D vector of characters vector<vector<char>> board = { {'#', '#', '#', '#', '#'}, {'#', '.', '.', '.', '#'}, {'#', '.', '@', '.', '#'}, {'#', '.', '.', '.', '#'}, {'#', '#', '#', '#', '#'} }; // the current position of the player int playerX = 2; int playerY = 2; // moves the player in the specified direction void movePlayer(int dx, int dy) { // calculate the new position of the player int newX = playerX + dx; int newY = playerY + dy; // check if the new position is valid if (newX < 0 || newX >= WIDTH || newY < 0 || newY >= HEIGHT || board[newY][newX] == '#') { // if the new position is invalid, do nothing return; } // move the player to the new position playerX = newX; playerY = newY; // redraw the game board for (int y = 0; y < HEIGHT; y++) { for (int x = 0; x < WIDTH; x++) { if (x == playerX && y == playerY) { cout << "@"; } else { cout << board[y][x]; } } cout << endl; } } int main() { // print the initial game board for (int y = 0; y < HEIGHT; y++) { for (int x = 0; x < WIDTH; x++) { if (x == playerX && y == playerY) { cout << "@"; } else { cout << board[y][x]; } } cout << endl; } // repeatedly get input from the user and move the player while (true) { char input; cin >> input; switch (input) { case 'w': movePlayer(0, -1); break; case 'a': movePlayer(-1, 0); break; case 's': movePlayer(0, 1); break; case 'd': movePlayer(1, 0); break; } } return 0; }
Editor is loading...