Reputation: 828
I have this program I've been working on for a while, which is basically a checkers game where somebody can either decide to play against a player or watch a computer simulation. Now both of these are basically the same code, except for the fact that the computer simulation takes randomized values. Both of these code blocks are located in my driver and I want to break up the code into two different cpp files. This way I have user input decide what is going to happen.
so for example:
if(x == 1)
call the player cpp file
else if (x == 2)
call the simulation cpp
My program is object-oriented, but I was wondering if there is a way to just run code from a different file without creating a class and defining functions?
Upvotes: 1
Views: 127
Reputation: 19583
A game should have two players. There are 2 types of player. A CpuPlayer and a HumanPlayer.
class Player {
public:
virtual Move getNextMove() = 0;
};
class HumanPlayer : public Player {
public:
HumanPlayer() {}
Move getNextMove() {
// get move from user interface
return move;
}
};
class CpuPlayer : public Player {
public:
CpuPlayer() {}
Move getNextMove() {
// get move from some sort of logic...
return move;
}
};
class MyGame {
public:
void setPlayer1(Player &player1instance) {
player1 = &player1instance;
}
void setPlayer2(Player &player2instance) {
player2 = &player2instance
}
private:
Player* player1;
Player* player2;
}
You code against a player. If player 1 is a human and player 2 is a human, then the "moves" are determined by some sort of human interface. If player 1 is a human and player 2 is a CPU, then player 1 is a UI and player 2 is a CPU. The reverse should be true if player 1 is a CPU and player 2 is a human. If both players are CPU's, then you have a simulation effect.
So, if you have some sort of starting menu to bootstrap your game, this should be pretty easy. Just make sure you code your game logic against a Player
contract, and not against a specific type of player implementation.
Upvotes: 2
Reputation: 32530
You could do something like
if (x == 1)
{
#include "player.cpp"
}
else if (x == 2)
{
#include "simulation.cpp"
}
And have the individual .cpp files contain the logic for each major section. This is a bit clunkier though that just wrapping the functionality in some functions and call those from your if-if-else statements. At least with functions if something goes wrong, it will be easier to debug or do stack-traces, etc. rather than chase around multiple .cpp files.
Upvotes: 0