Hello,
I'm working on a C++ console Snake game. I have the following code:
main.cpp
#include <iostream>
#include "map.h"
#include "snake.h"
using namespace std;
int main()
{
map Map;
snake Snake;
Map.initMap();
Snake.initSnake();
Map.updateMap();
system("pause");
return 0;
}
map.h
#pragma once
const int row = 20;
const int column = 80;
class map
{
protected:
char area[row][column];
public:
void initMap();
void updateMap();
};
map.cpp
#include "map.h"
#include <iostream>
using namespace std;
void map::initMap()
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
if (i == 0 || i == row - 1 || j == 0 || j == column - 1)
{
area[i][j] = '#';
} else {
area[i][j] = ' ';
}
}
}
}
void map::updateMap()
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
cout << area[i][j];
}
}
}
snake.h
#pragma once
#include "map.h"
#include <vector>
class snake : public map
{
protected:
std::vector <char> snakeb;
public:
void initSnake();
void updateSnake();
};
snake.cpp
#include "snake.h"
#include <iostream>
using namespace std;
void snake::initSnake()
{
snakeb.push_back('@'); // head
snakeb.push_back('o');
snakeb.push_back('o');
for (int i = 0; i < snakeb.size(); i++)
{
area[row / 2][column / 2 + i] = snakeb[i]; // the snake will spawn in the middle of the map
}
}
The program compiles fine, but the actual snake body won't get printed in the console. My guess is that the issue is caused because of the inherited snake class.
I would appreciate if I get any piece of advice to better organise (best practice) my code, splitting the different parts of the game into different classes etc.
Thank you! :)