IT 프로그래밍/객체지향프로그래밍

객체지향프로그래밍 7 과제 Food Monster

기술1 2024. 6. 21. 19:03
반응형

 

 

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

class GameObject
{
protected:
	int distance;
	int x, y;
public:
	GameObject(int startX, int startY, int distance)
	{
		this->x = startX; this->y = startY;
		this->distance = distance;
	}
	virtual ~GameObject() {};

	virtual void move() = 0;
	virtual char getShape() = 0;

	int getX() { return x; }
	int getY() { return y; }
	bool collide(GameObject* p)
	{
		if (this->x == p->getX() && this->y == p->getY())
			return true;
		else
			return false;
	}
};

class Human : public GameObject
{
public:
	Human(int x, int y, int dis)
		: GameObject(x, y, dis)
	{}
	void move();
	char getShape() { return 'H'; }
};

void Human::move()
{
	string key;
	for (;;)
	{
		cin >> key;
		if (key == "a")
		{
			if (y != 0)
			{
				y -= distance;
				break;
			}
			else
				cout << "이동불가" << endl;
		}
		if (key == "s")
		{
			if (x != 9)
			{
			    x += distance;
				break;
			}
			else
				cout << "이동불가" << endl;
		}
		if (key == "d")
		{
			if (x != 0)
			{
				x -= distance;
				break;
			}
			else
				cout << "이동불가" << endl;
		}
		if (key == "f")
		{
			if (y != 19)
			{
				y += distance;
				break;
			}
			else
				cout << "이동불가" << endl;
		}
	}
}

class Monster : public GameObject
{
public:
	Monster(int x, int y, int dis)
		: GameObject(x, y, dis)
	{
		srand((unsigned)time(0));
	}
	void move();
	char getShape() { return 'M'; }
};

void Monster::move()
{
	for (;;)
	{
		int n = rand() % 4;
		if (n == 0) {
			if (y > 1) {
				y -= distance;
				break;
			}
		}
		else if (n == 1) {
			if (x < 8) {
				x += distance;
				break;
			}
		}
		else if (n == 2) {
			if (x > 1) {
				x -= distance;
				break;
			}
		}
		else {
			if (y < 18) {
				y += distance;
				break;
			}
		}
	}
}

class Food : public GameObject
{
public:
	Food(int x, int y, int dis)
		: GameObject(x, y, dis)
	{}
	void move();
	char getShape() { return '@'; }
};
void Food::move()
{
	for (;;)
	{
		int n = rand() % 4;
		if (n == 0) {
			if (y != 0) {
				y -= distance;
				break;
			}
		}
		else if (n == 1) {
			if (x != 9) {
				x += distance;
				break;
			}
		}
		else if (n == 2) {
			if (x != 0) {
				x -= distance;
				break;
			}
		}
		else {
			if (y != 19) {
				y += distance;
				break;
			}
		}
	}
}


class Game {
	string board[10][20]; 
	Human* h = new Human(0, 0, 1); 
	Monster* m = new Monster(5, 7, 2);
	Food* f = new Food(8, 10, 1); 
public:
	Game() {
		srand((unsigned)time(0));
		cout << "Game Start" << endl << endl;
		for (int i = 0; i < 10; ++i) { 
			for (int j = 0; j < 20; ++j)
				board[i][j] = "-";
		}
	}
	~Game() { delete h; delete m; delete f; }
	void game();
	void clr1() {
		board[h->getX()][h->getY()] = "-";
		board[m->getX()][m->getY()] = "-";
	}
	void clr2() { 
		board[f->getX()][f->getY()] = "-";
	}
	void setXY() {
		board[h->getX()][h->getY()] = h->getShape();
		board[m->getX()][m->getY()] = m->getShape();
		board[f->getX()][f->getY()] = f->getShape();
	}
	void show() {
		for (int i = 0; i < 10; ++i) {
			for (int j = 0; j < 20; ++j)
				cout << board[i][j];
			cout << endl;
		}
	}
};
void Game::game() {
	int count = 0, gamecount = 0;
	for (;;) {
		setXY();
		show();
		clr1();
		h->move(); m->move();
		int n = rand();
		cout << endl;
		if (n % 2 == 0 && count < 2 && gamecount <= 3) {
			clr2();
			f->move();
			++count;
		}
		if (gamecount > 3 && count < 2) { 
			clr2();
			f->move();
			++count;
		}
		if (f->collide(h)) { 
			setXY();
			board[f->getX()][f->getY()] = "H";
			show();
			cout << "Human's win" << endl;
			break;
		}
		else if (h->collide(m)) { 
			setXY();
			board[f->getX()][f->getY()] = "M";
			show();
			cout << "Monster's win" << endl;
			break;
		}
		else if (f->collide(m)) { 
			setXY();
			board[f->getX()][f->getY()] = "M";
			show();
			cout << "Monster's win" << endl;
			break;
		}
		++gamecount;
		if ((gamecount % 5) == 0) { 
			count = 0;
			gamecount = 0;
		}
	}
}
int main()
{
	Game* g = new Game;
	g->game();
	delete g;

	return 0;
}

 

GameObject 클래스:
distance: 이동할 거리.
x, y: 현재 위치.
move(): 가상 함수, 객체가 이동할 때의 동작을 정의.
getShape(): 가상 함수, 객체의 모양을 반환.
collide(GameObject* p): 객체가 다른 객체와 충돌했는지 확인.


Human 클래스 (GameObject를 상속):
move(): 사용자가 입력한 방향으로 인간을 이동시킴. 사용 가능한 방향은 'a'(왼쪽), 's'(아래), 'd'(위), 'f'(오른쪽). getShape(): 'H' 반환.

 

Monster 클래스 (GameObject를 상속):
move(): 랜덤하게 몬스터를 이동시킴. 이동 가능한 방향은 0(왼쪽), 1(아래), 2(위), 3(오른쪽). getShape(): 'M' 반환.

 

Food 클래스 (GameObject를 상속):
move(): 랜덤하게 음식을 이동시킴.
getShape(): '@' 반환.

 

게임 로직

 

Game 클래스:
board[10][20]: 게임 보드를 나타내는 문자열 배열.
Human* h, Monster* m, Food* f: 게임 객체를 생성.
생성자: 게임 보드를 초기화하고 시작 메시지를 출력.
소멸자: 동적 할당된 객체를 삭제.

 

game(): 게임의 주요 로직을 담당.
clr1(), clr2(): 각각 인간과 몬스터, 음식을 보드에서 지움.
setXY(): 보드에 객체의 위치를 설정.
show(): 현재 보드를 출력.

 

게임 루프:
객체의 위치를 설정하고 보드를 출력.
인간과 몬스터의 위치를 초기화.
인간과 몬스터를 이동시킴.
랜덤하게 음식을 이동시킴.
충돌 상황을 확인하여 게임 종료 조건을 판단.
게임 카운트를 증가시키고 주기적으로 음식 이동 카운트를 초기화.

 

게임 흐름

 

 

초기화:
보드가 -로 채워짐.
Human, Monster, Food 객체가 생성되고 초기 위치가 설정됨.

 

게임 루프:
현재 객체의 위치를 보드에 설정하고 보드를 출력.
사용자 입력을 받아 인간을 이동시킴.
몬스터를 랜덤하게 이동시킴.
음식이 일정 확률로 이동.
인간과 몬스터, 음식 간의 충돌을 확인하고 게임 종료 여부를 판단.
충돌이 발생하지 않으면 루프를 반복.

 

게임 종료:
인간이 음식을 먹거나, 인간과 몬스터가 충돌하거나, 몬스터가 음식을 먹으면 게임이 종료됨.
결과 메시지를 출력하고 게임을 종료.

 

 

+ rand() % 4 = 랜덤 수를 구합니다. 왼쪽식의 결과로는 0~3 사이의 수를 얻을 수 있습니다. 

rand()로는 0~32000정도의 수를 얻어오는데 이 수 중 어느 수라도 4로 나눈 후 나머지는 0~3이기 때문입니다.

 
+ srand((unsigned)time(0)); = 보통 위 rand()와 연계하여 사용하는 것 입니다. 이를 입력해주어야 실행 때마다 다른 결과를 얻을 수 있습니다.

 

 

 

Trap 문제 응용

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

class GameObject
{
protected:
    int distance;
    int x, y;
public:
    GameObject(int startX, int startY, int distance)
    {
        this->x = startX; this->y = startY;
        this->distance = distance;
    }
    virtual ~GameObject() {};

    virtual void move() = 0;
    virtual char getShape() = 0;

    int getX() { return x; }
    int getY() { return y; }
    bool collide(GameObject* p)
    {
        if (this->x == p->getX() && this->y == p->getY())
            return true;
        else
            return false;
    }
};

class Human : public GameObject
{
public:
    Human(int x, int y, int dis)
        : GameObject(x, y, dis)
    {}
    void move();
    char getShape() { return 'H'; }
};

void Human::move()
{
    string key;
    for (;;)
    {
        cin >> key;
        if (key == "a")
        {
            if (y != 0)
            {
                y -= distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "s")
        {
            if (x != 9)
            {
                x += distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "d")
        {
            if (x != 0)
            {
                x -= distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "f")
        {
            if (y != 19)
            {
                y += distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
    }
}

class Monster : public GameObject
{
public:
    Monster(int x, int y, int dis)
        : GameObject(x, y, dis)
    {
        srand((unsigned)time(0));
    }
    void move();
    char getShape() { return 'M'; }
};

void Monster::move()
{
    for (;;)
    {
        int n = rand() % 4;
        if (n == 0) {
            if (y > 1) {
                y -= distance;
                break;
            }
        }
        else if (n == 1) {
            if (x < 8) {
                x += distance;
                break;
            }
        }
        else if (n == 2) {
            if (x > 1) {
                x -= distance;
                break;
            }
        }
        else {
            if (y < 18) {
                y += distance;
                break;
            }
        }
    }
}

class Food : public GameObject
{
public:
    Food(int x, int y, int dis)
        : GameObject(x, y, dis)
    {}
    void move();
    char getShape() { return '@'; }
};
void Food::move()
{
    for (;;)
    {
        int n = rand() % 4;
        if (n == 0) {
            if (y != 0) {
                y -= distance;
                break;
            }
        }
        else if (n == 1) {
            if (x != 9) {
                x += distance;
                break;
            }
        }
        else if (n == 2) {
            if (x != 0) {
                x -= distance;
                break;
            }
        }
        else {
            if (y != 19) {
                y += distance;
                break;
            }
        }
    }
}

class Trap : public GameObject
{
public:
    Trap(int x, int y, int dis)
        : GameObject(x, y, dis)
    {}
    void move() {}
    char getShape() { return 'T'; }
};

class Game {
    string board[10][20]; 
    Human* h = new Human(0, 0, 1); 
    Monster* m = new Monster(5, 7, 2);
    Food* f = new Food(8, 10, 1); 
    Trap* t = new Trap(4, 4, 1); 
public:
    Game() {
        srand((unsigned)time(0));
        cout << "Game Start" << endl << endl;
        for (

Trap 클래스 정의:

  1. Game object를 상속받고 move() 메소드는 이동하지 않도록 구현
  2. getshape() 메소드는 T를 반환

Game 클래스 수정

  • Trap 객체를 추가하고 초기 위치를 설정
  • setXY() 메소드에서 Trap 객체의 위치를 설정
  • 게임루프에서 Trap 객체와의 충돌을 검사하여 인간이 Trap에 도달하면 Human is trapped 메세지를 출력하고 게임을 종료하도록 구

Super Food 응용

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

class GameObject
{
protected:
    int distance;
    int x, y;
public:
    GameObject(int startX, int startY, int distance)
    {
        this->x = startX; this->y = startY;
        this->distance = distance;
    }
    virtual ~GameObject() {};

    virtual void move() = 0;
    virtual char getShape() = 0;

    int getX() { return x; }
    int getY() { return y; }
    bool collide(GameObject* p)
    {
        if (this->x == p->getX() && this->y == p->getY())
            return true;
        else
            return false;
    }
};

class Human : public GameObject
{
public:
    Human(int x, int y, int dis)
        : GameObject(x, y, dis)
    {}
    void move();
    char getShape() { return 'H'; }
};

void Human::move()
{
    string key;
    for (;;)
    {
        cin >> key;
        if (key == "a")
        {
            if (y != 0)
            {
                y -= distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "s")
        {
            if (x != 9)
            {
                x += distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "d")
        {
            if (x != 0)
            {
                x -= distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "f")
        {
            if (y != 19)
            {
                y += distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
    }
}

class Monster : public GameObject
{
public:
    Monster(int x, int y, int dis)
        : GameObject(x, y, dis)
    {
        srand((unsigned)time(0));
    }
    void move();
    char getShape() { return 'M'; }
};

void Monster::move()
{
    for (;;)
    {
        int n = rand() % 4;
        if (n == 0) {
            if (y > 1) {
                y -= distance;
                break;
            }
        }
        else if (n == 1) {
            if (x < 8) {
                x += distance;
                break;
            }
        }
        else if (n == 2) {
            if (x > 1) {
                x -= distance;
                break;
            }
        }
        else {
            if (y < 18) {
                y += distance;
                break;
            }
        }
    }
}

class Food : public GameObject
{
public:
    Food(int x, int y, int dis)
        : GameObject(x, y, dis)
    {}
    void move();
    char getShape() { return '@'; }
};
void Food::move()
{
    for (;;)
    {
        int n = rand() % 4;
        if (n == 0) {
            if (y != 0) {
                y -= distance;
                break;
            }
        }
        else if (n == 1) {
            if (x != 9) {
                x += distance;
                break;
            }
        }
        else if (n == 2) {
            if (x != 0) {
                x -= distance;
                break;
            }
        }
        else {
            if (y != 19) {
                y += distance;
                break;
            }
        }
    }
}

class SuperFood : public Food
{
public:
    SuperFood(int x, int y, int dis)
        : Food(x, y, dis)
    {}
    char getShape() { return '#'; }
};

class Game {
    string board[10][20];
    Human* h = new Human(0, 0, 1);
    Monster* m = new Monster(5, 7, 2);
    Food* f = new Food(8, 10, 1);
    SuperFood* sf = new SuperFood(4, 15, 1);
public:
    Game() {
        srand((unsigned)time(0));
        cout << "Game Start" << endl << endl;
        for (int i = 0; i < 10; ++i) {
            for (int j = 0; j < 20; ++j)
                board[i][j] = "-";
        }
    }
    ~Game() { delete h; delete m; delete f; delete sf; }
    void game();
    void clr1() {
        board[h->getX()][h->getY()] = "-";
        board[m->getX()][m->getY()] = "-";
    }
    void clr2() {
        board[f->getX()][f->getY()] = "-";
        board[sf->getX()][sf->getY()] = "-";
    }
    void setXY() {
        board[h->getX()][h->getY()] = h->getShape();
        board[m->getX()][m->getY()] = m->getShape();
        board[f->getX()][f->getY()] = f->getShape();
        board[sf->getX()][sf->getY()] = sf->getShape();
    }
    void show() {
        for (int i = 0; i < 10; ++i) {
            for (int j = 0; j < 20; ++j)
                cout << board[i][j];
            cout << endl;
        }
    }
};
void Game::game() {
    int count = 0, gamecount = 0;
    for (;;) {
        setXY();
        show();
        clr1();
        h->move(); m->move();
        int n = rand();
        cout << endl;
        if (n % 2 == 0 && count < 2 && gamecount <= 3) {
            clr2();
            f->move();
            sf->move();
            ++count;
        }
        if (gamecount > 3 && count < 2) {
            clr2();
            f->move();
            sf->move();
            ++count;
        }
        if (f->collide(h)) {
            setXY();
            board[f->getX()][f->getY()] = "H";
            show();
            cout << "Human's win" << endl;
            break;
        }
        else if (h->collide(m)) {
            setXY();
            board[f->getX()][f->getY()] = "M";
            show();
            cout << "Monster's win" << endl;
            break;
        }
        else if (f->collide(m)) {
            setXY();
            board[f->getX()][f->getY()] = "M";
            show();
            cout << "Monster's win" << endl;
            break;
        }
        else if (sf->collide(h)) {
            setXY();
            board[sf->getX()][sf->getY()] = "H";
            show();
            cout << "Human's win with SuperFood" << endl;
            break;
        }
        else if (sf->collide(m)) {
            setXY();
            m->distance = 4; // 몬스터의 이동 속도 증가
            board[sf->getX()][sf->getY()] = "M";
            show();
            cout << "Monster ate SuperFood, speed increased!" << endl;
        }
        ++gamecount;
        if ((gamecount % 5) == 0) {
            count = 0;
            gamecount = 0;
        }
    }
}
int main()
{
    Game* g = new Game;
    g->game();
    delete g;

    return 0;
}

 

 

점수 시스템 추가

Game 클래스에 점수 시스템을 추가합니다. 인간이 음식을 먹으면 점수가 10점 증가하고, 몬스터가 음식을 먹으면 점수가 5점 감소합니다. 게임종료 시 최종점수를 출력합니다. 

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

class GameObject
{
protected:
    int distance;
    int x, y;
public:
    GameObject(int startX, int startY, int distance)
    {
        this->x = startX; this->y = startY;
        this->distance = distance;
    }
    virtual ~GameObject() {};

    virtual void move() = 0;
    virtual char getShape() = 0;

    int getX() { return x; }
    int getY() { return y; }
    bool collide(GameObject* p)
    {
        if (this->x == p->getX() && this->y == p->getY())
            return true;
        else
            return false;
    }
};

class Human : public GameObject
{
public:
    Human(int x, int y, int dis)
        : GameObject(x, y, dis)
    {}
    void move();
    char getShape() { return 'H'; }
};

void Human::move()
{
    string key;
    for (;;)
    {
        cin >> key;
        if (key == "a")
        {
            if (y != 0)
            {
                y -= distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "s")
        {
            if (x != 9)
            {
                x += distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "d")
        {
            if (x != 0)
            {
                x -= distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "f")
        {
            if (y != 19)
            {
                y += distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
    }
}

class Monster : public GameObject
{
public:
    Monster(int x, int y, int dis)
        : GameObject(x, y, dis)
    {
        srand((unsigned)time(0));
    }
    void move();
    char getShape() { return 'M'; }
};

void Monster::move()
{
    for (;;)
    {
        int n = rand() % 4;
        if (n == 0) {
            if (y > 1) {
                y -= distance;
                break;
            }
        }
        else if (n == 1) {
            if (x < 8) {
                x += distance;
                break;
            }
        }
        else if (n == 2) {
            if (x > 1) {
                x -= distance;
                break;
            }
        }
        else {
            if (y < 18) {
                y += distance;
                break;
            }
        }
    }
}

class Food : public GameObject
{
public:
    Food(int x, int y, int dis)
        : GameObject(x, y, dis)
    {}
    void move();
    char getShape() { return '@'; }
};
void Food::move()
{
    for (;;)
    {
        int n = rand() % 4;
        if (n == 0) {
            if (y != 0) {
                y -= distance;
                break;
            }
        }
        else if (n == 1) {
            if (x != 9) {
                x += distance;
                break;
            }
        }
        else if (n == 2) {
            if (x != 0) {
                x -= distance;
                break;
            }
        }
        else {
            if (y != 19) {
                y += distance;
                break;
            }
        }
    }
}

class Game {
    string board[10][20]; 
    Human* h = new Human(0, 0, 1); 
    Monster* m = new Monster(5, 7, 2);
    Food* f = new Food(8, 10, 1); 
    int score = 0; // 점수 변수 추가
public:
    Game() {
        srand((unsigned)time(0));
        cout << "Game Start" << endl << endl;
        for (int i = 0; i < 10; ++i) { 
            for (int j = 0; j < 20; ++j)
                board[i][j] = "-";
        }
    }
    ~Game() { delete h; delete m; delete f; }
    void game();
    void clr1() {
        board[h->getX()][h->getY()] = "-";
        board[m->getX()][m->getY()] = "-";
    }
    void clr2() { 
        board[f->getX()][f->getY()] = "-";
    }
    void setXY() {
        board[h->getX()][h->getY()] = h->getShape();
        board[m->getX()][m->getY()] = m->getShape();
        board[f->getX()][f->getY()] = f->getShape();
    }
    void show() {
        for (int i = 0; i < 10; ++i) {
            for (int j = 0; j < 20; ++j)
                cout << board[i][j];
            cout << endl;
        }
    }
};

void Game::game() {
    int count = 0, gamecount = 0;
    for (;;) {
        setXY();
        show();
        clr1();
        h->move(); m->move();
        int n = rand();
        cout << endl;
        if (n % 2 == 0 && count < 2 && gamecount <= 3) {
            clr2();
            f->move();
            ++count;
        }
        if (gamecount > 3 && count < 2) { 
            clr2();
            f->move();
            ++count;
        }
        if (f->collide(h)) { 
            score += 10; // 인간이 음식을 먹으면 점수 증가
            setXY();
            board[f->getX()][f->getY()] = "H";
            show();
            cout << "Human's win" << endl;
            break;
        }
        else if (h->collide(m)) { 
            setXY();
            board[f->getX()][f->getY()] = "M";
            show();
            cout << "Monster's win" << endl;
            break;
        }
        else if (f->collide(m)) { 
            score -= 5; // 몬스터가 음식을 먹으면 점수 감소
            setXY();
            board[f->getX()][f->getY()] = "M";
            show();
            cout << "Monster's win" << endl;
            break;
        }
        ++gamecount;
        if ((gamecount % 5) == 0) { 
            count = 0;
            gamecount = 0;
        }
    }
    cout << "Final Score: " << score << endl; // 최종 점수 출력
}

int main()
{
    Game* g = new Game;
    g->game();
    delete g;

    return 0;
}

 

 

게임 보드 크기 변경 및 사용자 정의 시작 위치

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

class GameObject
{
protected:
    int distance;
    int x, y;
public:
    GameObject(int startX, int startY, int distance)
    {
        this->x = startX; this->y = startY;
        this->distance = distance;
    }
    virtual ~GameObject() {};

    virtual void move() = 0;
    virtual char getShape() = 0;

    int getX() { return x; }
    int getY() { return y; }
    bool collide(GameObject* p)
    {
        if (this->x == p->getX() && this->y == p->getY())
            return true;
        else
            return false;
    }
};

class Human : public GameObject
{
public:
    Human(int x, int y, int dis)
        : GameObject(x, y, dis)
    {}
    void move();
    char getShape() { return 'H'; }
};

void Human::move()
{
    string key;
    for (;;)
    {
        cin >> key;
        if (key == "a")
        {
            if (y != 0)
            {
                y -= distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "s")
        {
            if (x != 14)
            {
                x += distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "d")
        {
            if (x != 0)
            {
                x -= distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
        if (key == "f")
        {
            if (y != 29)
            {
                y += distance;
                break;
            }
            else
                cout << "이동불가" << endl;
        }
    }
}

class Monster : public GameObject
{
public:
    Monster(int x, int y, int dis)
        : GameObject(x, y, dis)
    {
        srand((unsigned)time(0));
    }
    void move();
    char getShape() { return 'M'; }
};

void Monster::move()
{
    for (;;)
    {
        int n = rand() % 4;
        if (n == 0) {
            if (y > 1) {
                y -= distance;
                break;
            }
        }
        else if (n == 1) {
            if (x < 13) {
                x += distance;
                break;
            }
        }
        else if (n == 2) {
            if (x > 1) {
                x -= distance;
                break;
            }
        }
        else {
            if (y < 28) {
                y += distance;
                break;
            }
        }
    }
}

class Food : public GameObject
{
public:
    Food(int x, int y, int dis)
        : GameObject(x, y, dis)
    {}
    void move();
    char getShape() { return '@'; }
};
void Food::move()
{
    for (;;)
    {
        int n = rand() % 4;
        if (n == 0) {
            if (y != 0) {
                y -= distance;
                break;
            }
        }
        else if (n == 1) {
            if (x != 14) {
                x += distance;
                break;
            }
        }
        else if (n == 2) {
            if (x != 0) {
                x -= distance;
                break;
            }
        }
        else {
            if (y != 29) {
                y += distance;
                break;
            }
        }
    }
}

class Game {
    string board[15][30]; 
    Human* h;
    Monster* m;
    Food* f;
public:
    Game(int hx, int hy, int mx, int my, int fx, int fy) {
        srand((unsigned)time(0));
        h = new Human(hx, hy, 1);
        m = new Monster(mx, my, 2);
        f = new Food(fx, fy, 1);
        cout << "Game Start" << endl << endl;
        for (int i = 0; i < 15; ++i) { 
            for (int j = 0; j < 30; ++j)
                board[i][j] = "-";
        }
    }
    ~Game() { delete h; delete m; delete f; }
    void game();
    void clr1() {
        board[h->getX()][h->getY()] = "-";
        board[m->getX()][m->getY()] = "-";
    }
    void clr2() { 
        board[f->getX()][f->getY()] = "-";
    }
    void setXY() {
        board[h->getX()][h->getY()] = h->getShape();
        board[m->getX()][m->getY()] = m->getShape();
        board[f->getX()][f->getY()] = f->getShape();
    }
    void show() {
        for (int i = 0; i < 15; ++i) {
            for (int j = 0; j < 30; ++j)
                cout << board[i][j];
            cout << endl;
        }
    }
};

void Game::game() {
    int count = 0, gamecount = 0;
    for (;;) {
        setXY();
        show();
        clr1();
        h->move(); m->move();
        int n = rand();
        cout << endl;
        if (n % 2 == 0 && count < 2 && gamecount <= 3) {
            clr2();
            f->move();
            ++count;
        }
        if (gamecount > 3 && count < 2) { 
            clr2();
            f->move();
            ++count;
        }
        if (f->collide(h)) { 
            setXY();
            board[f->getX()][f->getY()] = "H";
            show();
            cout << "Human's win" << endl;
            break;
        }
        else if (h->collide(m)) { 
            setXY();
            board[f->getX()][f->getY()] = "M";
            show();
            cout << "Monster's win" << endl;
            break;
        }
        else if (f->collide(m)) { 
            setXY();
            board[f->getX()][f->getY()] = "M";
            show();
            cout << "Monster's win" << endl;
            break;
        }
        ++gamecount;
        if ((gamecount % 5) == 0) { 
            count = 0;
            gamecount = 0;
        }
    }
}

int main()
{
    int hx, hy, mx, my, fx, fy;
    cout << "Enter human start position (x y): ";
    cin >> hx >> hy;
    cout << "Enter monster start position (x y): ";
    cin >> mx >> my;
    cout << "Enter food start position (x y): ";
    cin >> fx >> fy;

    Game* g = new Game(hx, hy, mx, my, fx, fy);
    g->game();
    delete g;

    return 0;
}

문제 해설
게임 보드 크기 변경:

Game 클래스의 보드 크기를 15x30으로 변경.
사용자 정의 시작 위치:

main() 함수에서 사용자로부터 인간, 몬스터, 음식의 시작 위치를 입력받아 Game 객체 생성 시 전달.
Game 생성자에서 이 위치들을 이용해 Human, Monster, Food 객체를 초기화.

반응형