I am a student of first semester and I am making a console based game in c++.
There are two players in game, 'player-2' is CPU player and 'player-1' is controlable player. After every 20 seconds one of player becomes red and other becomes green. The red ones need to catch green one and green one needs to run away from red one.
Problem I am now facing is that, I cant make logic to run Player-2(CPU Player) away from Player-1(controlable player) when Player-1 is red.
I have following class for both players
class Player
{
int XPos, YPos, Width, Height, Init_XPos, Init_YPos, MovSpeed;
WORD Color;
const float HurtSoundVol = 0.7;
string HurtSound;
virtual void Draw(int x, int y);
virtual void Erase(int x, int y);
template <typename T> void ConfCollision(IEntity& obj, bool& scoreChanged);
void SetCursorPosition(int row, int col);
template <typename T> void MoveUp();
template <typename T> void MoveDown();
template <typename T> void MoveLeft();
template <typename T> void MoveRight();
};
following is code for player movement
template <typename T> void IEntity::MoveUp() {
if (XPos > EnvSetup::UpBoundary) {
Hunter* this_x = (T*)this;
(this_x->IsHunter) ? this_x->HErase(XPos, YPos) : Erase(XPos, YPos);
XPos -= MovSpeed;
if (XPos <= EnvSetup::UpBoundary) XPos = 0 + EnvSetup::TopMargin;
(this_x->IsHunter) ? this_x->HDraw(XPos, YPos) : Draw(XPos, YPos);
}
}
template <typename T> void IEntity::MoveDown() {
if (XPos + Height < EnvSetup::DownBoundary) {
Hunter* this_x = (T*)this;
(this_x->IsHunter) ? this_x->HErase(XPos, YPos) : Erase(XPos, YPos);
XPos += MovSpeed;
if (XPos + Height >= EnvSetup::DownBoundary) XPos = EnvSetup::Height - Height - EnvSetup::BottomMargin;
(this_x->IsHunter) ? this_x->HDraw(XPos, YPos) : Draw(XPos, YPos);
}
}
template <typename T> void IEntity::MoveLeft() {
if (YPos > EnvSetup::LeftBoundary) {
Hunter* this_x = (T*)this;
(this_x->IsHunter) ? this_x->HErase(XPos, YPos) : Erase(XPos, YPos);
YPos -= MovSpeed;
if (YPos <= EnvSetup::LeftBoundary) YPos = 0 + EnvSetup::LeftMargin;
(this_x->IsHunter) ? this_x->HDraw(XPos, YPos) : Draw(XPos, YPos);
}
}
template <typename T> void IEntity::MoveRight() {
if (YPos + Width < EnvSetup::RightBoundary) {
Hunter* this_x = (T*)this;
(this_x->IsHunter) ? this_x->HErase(XPos, YPos) : Erase(XPos, YPos);
YPos += MovSpeed;
if (YPos + Width >= EnvSetup::RightBoundary) YPos = EnvSetup::Width - Width - EnvSetup::RightMargin;
(this_x->IsHunter) ? this_x->HDraw(XPos, YPos) : Draw(XPos, YPos);
}
}
If a player has a flag IsHunter=true than HDraw(draw it red) else draw it simply
This is image showing my game
What I have tried:
I used distance formula(sqrt((x2-x1)^2 + (y2-y1)^2)) in many ways to move player-2 away from player-1 but there is always some position of Player-1 and Player-2 (i.e along corner of screen or center of screen) where Player-2 starts to vibrate along its positon(One time moves up and second time moves down)