所以我有一个任务,我认为我或多或少地完成了,但是有些东西在某个地方严重地弄乱了输出,甚至是计算,我看不出问题出在哪里。
任务是制作一个游戏,其中一定数量的玩家通过隧道跑向一个点,他们会停下来绕着它旋转,然后他们的头晕应该让他们随机地朝着目标前进或倒退开始。每次他们获得另一个更接近目标的位置时,他们都会获得另一个“标记”,并且这样继续下去,直到他们中的一个到达目标。
该程序包括三个文件:一个main.cpp,一个头文件和另一个cpp文件。
头文件:
#ifndef COMPETITOR_H
#define COMPETITOR_H
#include <string>
using namespace std;
class Competitor
{
public:
void setName();
string getName();
void spin();
void move();
int checkScore();
void printResult();
private:
string name;
int direction;
int markedSpots;
};
#endif // COMPETITOR_H
第二个cpp文件:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include "Competitor.h"
using namespace std;
void Competitor::setName()
{
cin>>name;
}
string Competitor::getName()
{
return name;
}
void Competitor::spin()
{
srand(time(NULL));
direction = rand()%1+0;
}
void Competitor::move()
{
if(direction == 1)
{
markedSpots++;
}
else if(direction == 0 && markedSpots != 0)
{
markedSpots--;
}
}
int Competitor::checkScore()
{
return markedSpots;
}
void Competitor::printResult()
{
if(direction == 1)
{
cout<<" is heading towards goal and has currently "<<markedSpots<<" markings.";
}
else if(direction == 0)
{
cout<<"\n"<<getName()<<" is heading towards start and has currently "<<markedSpots<<" markings.";
}
}
主cpp文件:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include "Competitor.h"
using namespace std;
void inputAndSetNames(Competitor comps[],int nrOfComps);
void makeTwist(Competitor comps[],int nrOfComps);
void makeMove(Competitor comps[],int nrOfComps);
void showAll(Competitor comps[],int nrOfComps);
int winner(Competitor comps[],int nrOfComps, int nrOfTwistPlaces);
int main()
{
int nrOfTwistPlaces;
int nrOfComps;
int noWinner = -1;
int laps = 0;
cout<<"How many spinning places should there be? ";
cin>>nrOfTwistPlaces;
cout<<"How many competitors should there be? ";
cin>>nrOfComps;
Competitor * comps = new Competitor[nrOfComps];
inputAndSetNames(comps, nrOfComps);
do
{
laps++;
cout<<"\nSpin "<<laps<<":";
makeTwist(comps, nrOfComps);
makeMove(comps, nrOfComps);
showAll(comps, nrOfComps);
}while(noWinner == -1);
delete [] comps;
return 0;
}
void inputAndSetNames(Competitor comps[],int nrOfComps)
{
cout<<"Type in the names of the "<<nrOfComps<<" competitors:\n";
for(int i=0;i<nrOfComps;i++)
{
comps[i].setName();
}
cout<<"\n";
}
void makeTwist(Competitor comps[],int nrOfComps)
{
for(int i=0;i<nrOfComps;i++)
{
comps[i].spin();
}
}
void makeMove(Competitor comps[],int nrOfComps)
{
for(int i=0;i<nrOfComps;i++)
{
comps[i].move();
}
}
void showAll(Competitor comps[],int nrOfComps)
{
for(int i=0;i<nrOfComps;i++)
{
comps[i].printResult();
}
cout<<"\n\n";
system("pause");
}
int winner(Competitor comps[],int nrOfComps, int nrOfTwistPlaces)
{
int end = 0;
int score = 0;
for(int i=0;i<nrOfComps;i++)
{
score = comps[i].checkScore();
if(score == nrOfTwistPlaces)
{
end = 1;
}
else end = -1;
}
return end;
}
如果您发现任何错误,请指出其他错误,我将不胜感激。在此先感谢。