《C++游戏编程入门 第四版》的例子GameLobby

前言

像一些小游戏只是考查基本功底而已,所以除了处理的逻辑,其他都不重要。

GameLobby

考查链表与重载左移操作符的知识。
也就只有两个类的处理而已,下一篇会有7个类 … \dots

Player.h

#pragma once

#include
#include
#include
using namespace std;


class Player
{
public:
	Player(const string& name = "");
	~Player();

	string GetName()const;
	Player* GetNext()const;
	void SetNext(Player* next);
private:
	string m_name;
	Player* m_next;
};


Player.cpp

#include "Player.h"


Player::Player(const string& name ) :m_name(name),m_next(NULL){


}
Player::~Player() {


}

string Player::GetName()const {

	return m_name;
}
Player* Player::GetNext()const {

	return m_next;
}
void Player::SetNext(Player* next) {

	m_next = next;
}

Lobby.h

#pragma once

#include"Player.h"

class Lobby
{
	friend ostream& operator<<(ostream&os, const Lobby& aLobby);
public:
	Lobby();
	~Lobby();

	void Add();
	void Remove();
	void Clear();
private:
	Player* m_head;
};


Lobby.cpp

#include "Lobby.h"



Lobby::Lobby() : m_head(NULL){

}


Lobby::~Lobby(){
	Clear();
}

void  Lobby::Add() {
	//create a new player node
	cout << "please enter the name of the new player>>";
	string name;
	cin >> name;

	Player* pNew = new Player(name);
	if (m_head == NULL)
		m_head = pNew;
	else {
		Player* it = m_head;
		while (it->GetNext()) {
			it = it->GetNext();
		}
		it->SetNext(pNew);//把新玩家添加到末尾
	}

}
void    Lobby::Remove() {

	if (m_head == NULL)
		cout << "the game lobby is empty. No one to remove....\n";
	else {
		Player* pCurrent = m_head;
		m_head = m_head->GetNext();
		delete pCurrent;
	}
}
void    Lobby::Clear() {

	while (m_head) {
		Remove();
	}
}

ostream& operator<<(ostream&os, const Lobby& aLobby) {

	Player* it = aLobby.m_head;
	os << "here's who's in the game lobby>>\n";
	if (it == NULL)
		os << "the lobby is empty...\n";
	else {
		int i = 0;
		while (it) {
			os <GetName() << endl;
			it=it->GetNext();
		}
	}

	return os;
}

main.cpp

#include"Lobby.h"

void main(void) {

	cout << "===================Hello World====================" << endl;

	Lobby myLobby;
	int choice;
	do {
		cout << myLobby;
		cout << "\tGame Lobby\n"
			<< "0 - exit the program\n"
			<< "1 - add a player to the lobby\n"
			<< "2 - remove a player from the lobby\n"
			<< "3 - clear the lobby\n"
			<< "enter choice>>";
		cin >> choice;
		switch (choice) {
		case 0:
			cout << "good bye\n";
			break;
		case 1:
			myLobby.Add();
			break;
		case 2:
			myLobby.Remove();
			break;
		case 3:
			myLobby.Clear();
			break;
		default:
			cout << "that was not a valid choice\n";
			break;
		}
	} while (choice!=0);
	cout << "end\n";
	system("pause");
	
}

参考:《C++游戏编程入门 第四版》

你可能感兴趣的:(C/C++)