Simple ASCII Game written in C++.

Source Code:

/*
  Copyright (c) 2016 TheFlyingKeyboard
  
  For more games and programs visit http://theflyingkeyboard.net/

  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
  to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
  and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>

#ifdef _WIN32 //Windows
  #include <conio.h>
  #include <windows.h>
#endif

using namespace std;

void processPlayerInput(char input);
void setFileData(int currentPlayerX, int currentPlayerY);
int checkCollision(int currentPlayerX, int currentPlayerY, char key);
void printFile();
void loadFile(string filename);
void findPlayer(int &playerX, int &playerY);
void clearConsole();
char getChar();

const unsigned short X_CONSOLE_SIZE = 39; //Number must be uneven
const unsigned short Y_CONSOLE_SIZE = 21; //Number must be uneven
bool isGameOver = false;
bool wasPlayerFound = false;
vector<string> fileData; //Entire file data
vector<string> fileDataToDisplay; //File data to display in console

const char playerChar = 1; //1 is smiling face in ASCII Table
const char emptyTileChar = ' ';

int main() {
  loadFile("level1.txt");
  processPlayerInput(' ');

  clearConsole();
  cout << "W - up  S - down  A - left  D - right" << endl;
  cout << "Escape - exit" << endl;
  cout << "Press any key to continue...";
  getChar();
  clearConsole();

  while (!isGameOver) //Game loop
  {
    printFile();
    processPlayerInput(getChar());
    clearConsole();	
  }

  return 0;
}

void processPlayerInput(char input) { //Processes player input
  static int playerX;
  static int playerY;
  
  if (!wasPlayerFound) { //Makes sure the function will run only once		
    findPlayer(playerX, playerY);
    setFileData(playerX, playerY);
    wasPlayerFound = true;
  }
  
  switch (input)
  {
  case 'W': //Up
  case 'w':
    if (checkCollision(playerX, playerY, 'W') == 0) {			
      playerY--;

      fileData[playerY][playerX] = playerChar; //Changes next empty tile to player tile
      fileData[playerY + 1][playerX] = emptyTileChar; //Changes previous player tile to empty tile
    }
    break;
  case 'S': //Down
  case 's':
    if (checkCollision(playerX, playerY, 'S') == 0) {
      playerY++;

      fileData[playerY][playerX] = playerChar; //Changes next empty tile to player tile
      fileData[playerY - 1][playerX] = emptyTileChar; //Changes previous player tile to empty tile
    }
    break;
  case 'A': //Left
  case 'a':
    if (checkCollision(playerX, playerY, 'A') == 0) {
      playerX--;

      fileData[playerY][playerX] = playerChar; //Changes next empty tile to player tile
      fileData[playerY][playerX + 1] = emptyTileChar; //Changes previous player tile to empty tile
    }
    break;
  case 'D': //Right
  case 'd':
    if (checkCollision(playerX, playerY, 'D') == 0) {
      playerX++;

      fileData[playerY][playerX] = playerChar; //Changes next empty tile to player tile
      fileData[playerY][playerX - 1] = emptyTileChar; //Changes previous player tile to empty tile
    }
    break;
  case 27: //Escape
    isGameOver = true; //Ends game loop

    clearConsole();
    cout << "Thank you for playing!" << endl;
    cout << "Press any key to end the program...";
    getChar();

    break;
  }
  
  setFileData(playerX, playerY);
}

void setFileData(int currentPlayerX, int currentPlayerY) { //Sets data to display
  string line;

  fileDataToDisplay.clear();
  
  for (unsigned int i = 0; i < Y_CONSOLE_SIZE; i++) {
    line.clear();
    for (unsigned int j = 0; j < X_CONSOLE_SIZE; j++) {
      line += fileData[currentPlayerY - (Y_CONSOLE_SIZE / 2 - 1) + i][currentPlayerX - (X_CONSOLE_SIZE / 2 - 1) + j];
    }
    fileDataToDisplay.push_back(line);
  }
}

int checkCollision(int currentPlayerX, int currentPlayerY, char key) { //Checks collision between player and game objects
  int playerNextX;
  int playerNextY;
  char tile;
  int canEnter;

  switch (key) {
  case 'W': //Up
    playerNextX = currentPlayerX;
    playerNextY = (currentPlayerY - 1);
    break;
  case 'S': //Down
    playerNextX = currentPlayerX;
    playerNextY = (currentPlayerY + 1);
    break;
  case 'A': //Left
    playerNextX = (currentPlayerX - 1);
    playerNextY = currentPlayerY;
    break;
  case 'D': //Right
    playerNextX = (currentPlayerX + 1);
    playerNextY = currentPlayerY;
    break;
  }

  tile = fileData[playerNextY][playerNextX]; //Tile which player wants to enter

  switch (tile) { //Checks what is next tile
  case '#': //Wall
    canEnter = 1;
    break;
  case ' ': //Empty tile
    canEnter = 0;
    break;
  default: //Unexpected tile/error
    canEnter = -1;
    break;
  }

  return canEnter;
}

void printFile() { //Prints file
  for (unsigned int i = 0; i < fileDataToDisplay.size(); i++) {
    printf("%s \n", fileDataToDisplay[i].c_str());
  }
}

void loadFile(string filename) { //Loads level from text file
  ifstream file;
  file.open(filename);
  if (!(file.fail())) {
    string line;
    while (getline(file, line)) {
      fileData.push_back(line);
    }
  }
  else {
    printf("loadFile function failed!\n");
    getChar();
  }
}

void findPlayer(int &playerX, int &playerY) { //Finds player in fileData vectors
  char tile;

  //Loop through the file data
  for (unsigned int i = 0; i < fileData.size(); i++) { //Loop through each line of fileData vector
    for (unsigned int j = 0; j < fileData[i].size(); j++) { //Loop through each letter in row i
      tile = fileData[i][j]; //This is the current tile we are looking at

      if (tile == '@') { //Checks if player was found
        // j - x coordinate in file, i - y coordinate in file
        //First char in file coordinates are: x = 0, y = 0
        playerX = j;
        playerY = i;

        fileData[i][j] = playerChar;

        break;
      }
    }
  }
}

void clearConsole() { //Clears console
  #ifdef _WIN32 //Windows
    system("CLS");
  #else //Others
    system("clear");
  #endif
}

char getChar() { //Gets input from keyboard
  char input;

  #ifdef _WIN32 //Windows
    input = _getch();
    if (input == 0 || input == 0xE0) input = _getch(); //In case of input error
  #else //Others
    cin >> input;
  #endif

  return input;
}

Level file:

Remember to copy everything, including spaces!

level1.txt

C++ ASCII Game
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504