/* Add in a number of specified stairs in a given direction
* 1 - positive x
* 2 - negative x
* 3 - positive z
* 4 - negative z
*/
GameEntitiesContainer EntityFactory::AddStairs(int number, int direction, D3DXVECTOR3 position, GameEntitiesContainer gc, int width, bool xStair)
{
	int x;
	for( x = 0 ; x < number ; x++)
	{
		switch( direction )
		{
		case 1:
			gc = AddWall(2, width + 1, D3DXVECTOR3(position.x + x  , position.y + x , position.z), gc, xStair);
			gc = AddFloor(width + 1, 2 , D3DXVECTOR3(position.x + x  , position.y + (x + 1) , position.z), gc);
			break;
		case 2:
			gc = AddWall( 2, width + 1, D3DXVECTOR3(position.x - x  , position.y + x  , position.z), gc, xStair);
			gc = AddFloor(width + 1, 2, D3DXVECTOR3(position.x - x , position.y + (x + 1) , position.z), gc);
			break;
		case 3:
			gc = AddWall( 2, width + 1, D3DXVECTOR3(position.x , position.y + x  , position.z + x ), gc, xStair);
			gc = AddFloor(2, width + 1, D3DXVECTOR3(position.x, position.y + (x + 1) , position.z + x ), gc);
			break;
		default:
			gc = AddWall( 2, width + 1, D3DXVECTOR3(position.x , position.y  + x , position.z - x ), gc, xStair);
			gc = AddFloor(2, width + 1, D3DXVECTOR3(position.x , position.y + (x + 1) , position.z - (x + 1) ), gc);
			break;

		}
	
	}
	return gc;
}
//==========================================================================
//
//
//
//==========================================================================
void GLDrawList::SortWallIntoPlane(SortNode * head,SortNode * sort)
{
	GLFlat * fh=&flats[drawitems[head->itemindex].index];
	GLWall * ws=&walls[drawitems[sort->itemindex].index];

	bool ceiling = fh->z > ViewPos.Z;

	if ((ws->ztop[0] > fh->z || ws->ztop[1] > fh->z) && (ws->zbottom[0] < fh->z || ws->zbottom[1] < fh->z))
	{
		// We have to split this wall!

		// WARNING: NEVER EVER push a member of an array onto the array itself.
		// Bad things will happen if the memory must be reallocated!
		GLWall w = *ws;
		AddWall(&w);
	
		// Splitting is done in the shader with clip planes, if available
		if (gl.flags & RFL_NO_CLIP_PLANES)
		{
			GLWall * ws1;
			ws->vertcount = 0;	// invalidate current vertices.
			ws1=&walls[walls.Size()-1];
			ws=&walls[drawitems[sort->itemindex].index];	// may have been reallocated!
			float newtexv = ws->tcs[GLWall::UPLFT].v + ((ws->tcs[GLWall::LOLFT].v - ws->tcs[GLWall::UPLFT].v) / (ws->zbottom[0] - ws->ztop[0])) * (fh->z - ws->ztop[0]);

			// I make the very big assumption here that translucent walls in sloped sectors
			// and 3D-floors never coexist in the same level. If that were the case this
			// code would become extremely more complicated.
			if (!ceiling)
			{
				ws->ztop[1] = ws1->zbottom[1] = ws->ztop[0] = ws1->zbottom[0] = fh->z;
				ws->tcs[GLWall::UPRGT].v = ws1->tcs[GLWall::LORGT].v = ws->tcs[GLWall::UPLFT].v = ws1->tcs[GLWall::LOLFT].v = newtexv;
			}
			else
			{
				ws1->ztop[1] = ws->zbottom[1] = ws1->ztop[0] = ws->zbottom[0] = fh->z;
				ws1->tcs[GLWall::UPLFT].v = ws->tcs[GLWall::LOLFT].v = ws1->tcs[GLWall::UPRGT].v = ws->tcs[GLWall::LORGT].v=newtexv;
			}
		}

		SortNode * sort2 = SortNodes.GetNew();
		memset(sort2, 0, sizeof(SortNode));
		sort2->itemindex = drawitems.Size() - 1;

		head->AddToLeft(sort);
		head->AddToRight(sort2);
	}
	else if ((ws->zbottom[0]<fh->z && !ceiling) || (ws->ztop[0]>fh->z && ceiling))	// completely on the left side
	{
		head->AddToLeft(sort);
	}
	else
	{
		head->AddToRight(sort);
	}

}
Exemple #3
0
//==========================================================================
//
//
//
//==========================================================================
void GLDrawList::SortWallIntoPlane(SortNode * head,SortNode * sort)
{
	GLFlat * fh=&flats[drawitems[head->itemindex].index];
	GLWall * ws=&walls[drawitems[sort->itemindex].index];
	GLWall * ws1;

	bool ceiling = fh->z > FIXED2FLOAT(viewz);


	if (ws->ztop[0]>fh->z && ws->zbottom[0]<fh->z)
	{
		// We have to split this wall!

		// WARNING: NEVER EVER push a member of an array onto the array itself.
		// Bad things will happen if the memory must be reallocated!
		GLWall w=*ws;
		AddWall(&w);

		ws1=&walls[walls.Size()-1];
		ws=&walls[drawitems[sort->itemindex].index];	// may have been reallocated!
		float newtexv = ws->uplft.v + ((ws->lolft.v - ws->uplft.v) / (ws->zbottom[0] - ws->ztop[0])) * (fh->z - ws->ztop[0]);

		// I make the very big assumption here that translucent walls in sloped sectors
		// and 3D-floors never coexist in the same level. If that were the case this
		// code would become extremely more complicated.
		if (!ceiling)
		{
			ws->ztop[1] = ws1->zbottom[1] = ws->ztop[0] = ws1->zbottom[0] = fh->z;
			ws->uprgt.v = ws1->lorgt.v = ws->uplft.v = ws1->lolft.v = newtexv;
		}
		else
		{
			ws1->ztop[1] = ws->zbottom[1] = ws1->ztop[0] = ws->zbottom[0] = fh->z;
			ws1->uplft.v = ws->lolft.v = ws1->uprgt.v = ws->lorgt.v=newtexv;
		}

		SortNode * sort2=SortNodes.GetNew();
		memset(sort2,0,sizeof(SortNode));
		sort2->itemindex=drawitems.Size()-1;

		head->AddToLeft(sort);
		head->AddToRight(sort2);
	}
	else if ((ws->zbottom[0]<fh->z && !ceiling) || (ws->ztop[0]>fh->z && ceiling))	// completely on the left side
	{
		head->AddToLeft(sort);
	}
	else
	{
		head->AddToRight(sort);
	}

}
// placement of SGE's
void WorldGenerator::PopulateStatics()
{
	// divide the levelInfo.size
	// set x o y to negative, centering the
	// map around origo by going from -bound to +bound
	float bounds = mLI.size / 2;
	float x = -bounds;
	float y = -bounds;
	float cellSize = 200.0f;

	/*
		0-63	: reserved
		64-95	: wall
		96+		: floor
		129-160	: PacSpawn
		161-192	: GhostSpawn
		193-224	: Pill
		224+	: Boost
	*/
	for ( int i = 0; i < mapGrid.size(); i++ )
	{
		if ( mapGrid[i] <= 64 )
		{
			mGFS->quadtree->getNode( x * cellSize, y * cellSize  )->setWeight( INT_MAX );
		}
		if ( mapGrid[i] >= 64 && mapGrid[i] < 96)
		{
			AddWall( x * cellSize, y * cellSize );

			mGFS->quadtree->getNode( x * cellSize, y * cellSize  )->setWeight( INT_MAX );
		}
		if ( mapGrid[i] >= 96 )
		{
			AddFloor( x * cellSize, y * cellSize );
		}
		if ( mapGrid[i] > 192 && mapGrid[i] <= 224 )
		{
			AddPill( x * cellSize, y * cellSize );
		}

		x++;
		if ( x >= bounds )
		{
			x = -bounds;
			y++;
		}
		if ( y >= bounds )
			y = -bounds;
	}
}
Exemple #5
0
void Maze::Generate(unsigned size){
	m_size = size;
	srand((unsigned)time(0));
	m_wall_list.clear();
	data.clear();
	//black out whole maze.
	for (unsigned i = 0; i < (m_size*m_size); ++i)
		data.push_back(BLACK_SPACE);

	

	//add first wall and space
	data[at_(1, (m_size - 1))] = SPACE;
	AddWall(at_(1, (m_size - 2)));

	while (m_wall_list.size() != 0){
		unsigned wall_index = (m_wall_list.size() == 1)? 0:rand() % (m_wall_list.size()-1);
		position wall_pos = m_wall_list[wall_index];
		position opp_side = get_opp_side(wall_pos);
		if (opp_side == 0){
			m_wall_list.erase(m_wall_list.begin() + wall_index);
			continue;
		}
		if (data[opp_side] == BLACK_SPACE && !In_wall_list(opp_side)){
			data[wall_pos] = SPACE;
			m_wall_list.erase(m_wall_list.begin() + wall_index);
			AddSpace(opp_side);
			if (data[opp_side] == SPACE){
				AddWall(opp_side + 1); AddWall(opp_side - 1);
				AddWall(opp_side + m_size); AddWall(opp_side - m_size);
			}
		}
		else m_wall_list.erase(m_wall_list.begin() + wall_index);
	}
	AddExit();
}
Exemple #6
0
void GLDrawList::SortWallIntoWall(SortNode * head,SortNode * sort)
{
	GLWall * wh=&walls[drawitems[head->itemindex].index];
	GLWall * ws=&walls[drawitems[sort->itemindex].index];
	GLWall * ws1;
	float v1=wh->PointOnSide(ws->glseg.x1,ws->glseg.y1);
	float v2=wh->PointOnSide(ws->glseg.x2,ws->glseg.y2);

	if (fabs(v1)<MIN_EQ && fabs(v2)<MIN_EQ) 
	{
		if (ws->type==RENDERWALL_FOGBOUNDARY && wh->type!=RENDERWALL_FOGBOUNDARY) 
		{
			head->AddToRight(sort);
		}
		else if (ws->type!=RENDERWALL_FOGBOUNDARY && wh->type==RENDERWALL_FOGBOUNDARY) 
		{
			head->AddToLeft(sort);
		}
		else 
		{
			head->AddToEqual(sort);
		}
	}
	else if (v1<MIN_EQ && v2<MIN_EQ) 
	{
		head->AddToLeft(sort);
	}
	else if (v1>-MIN_EQ && v2>-MIN_EQ) 
	{
		head->AddToRight(sort);
	}
	else
	{
		double r=ws->CalcIntersectionVertex(wh);

		float ix=(float)(ws->glseg.x1+r*(ws->glseg.x2-ws->glseg.x1));
		float iy=(float)(ws->glseg.y1+r*(ws->glseg.y2-ws->glseg.y1));
		float iu=(float)(ws->uplft.u + r * (ws->uprgt.u - ws->uplft.u));
		float izt=(float)(ws->ztop[0]+r*(ws->ztop[1]-ws->ztop[0]));
		float izb=(float)(ws->zbottom[0]+r*(ws->zbottom[1]-ws->zbottom[0]));

		GLWall w=*ws;
		AddWall(&w);
		ws1=&walls[walls.Size()-1];
		ws=&walls[drawitems[sort->itemindex].index];	// may have been reallocated!

		ws1->glseg.x1=ws->glseg.x2=ix;
		ws1->glseg.y1=ws->glseg.y2=iy;
		ws1->ztop[0]=ws->ztop[1]=izt;
		ws1->zbottom[0]=ws->zbottom[1]=izb;
		ws1->lolft.u = ws1->uplft.u = ws->lorgt.u = ws->uprgt.u = iu;

		SortNode * sort2=SortNodes.GetNew();
		memset(sort2,0,sizeof(SortNode));
		sort2->itemindex=drawitems.Size()-1;

		if (v1>0)
		{
			head->AddToLeft(sort2);
			head->AddToRight(sort);
		}
		else
		{
			head->AddToLeft(sort);
			head->AddToRight(sort2);
		}
	}
}
GameEntitiesContainer EntityFactory::CreateLevel1(GameEntitiesContainer container, PlayerComponent *player, AIEntitiesInteractionContainer aiEntitiesContainer)
{
	int height = 25;
	int width = 50;
	int length = 50;
	// Create the bounding walls and floor
	// F1
	container = AddFloor( width , length, D3DXVECTOR3(0,0,0) , container);
	// W1
	container = AddWall( height, width, D3DXVECTOR3(0,0,0), container, true);
	// W2
	container = AddWall( height,length, D3DXVECTOR3(0,0,0) , container, false);
	// W3
	container = AddWall( height,width, D3DXVECTOR3( 49, 0,0), container, true);
	// W4
	container = AddWall(height,length, D3DXVECTOR3(0,0, 49 ), container, false);
	// F2
	container = AddFloor( width,length , D3DXVECTOR3(0,24 , 0), container);
	
	// Containing walls
	// W5
	container = AddWall( height, 26, D3DXVECTOR3(3 , 0, 0) , container, true);
	// W6
	container = AddWall( (int)(height/2), 18 , D3DXVECTOR3( 3 , 0 , 25 ), container, false);
	// W7
	container = AddWall( height, 7, D3DXVECTOR3( 24  , 0 , 25 ), container, false);
	// W8
	container = AddWall( (int)(height / 2), 8 , D3DXVECTOR3( 30 , 0, 25 ), container, false);
	// W9
	container = AddWall( height, 10 , D3DXVECTOR3( 37 , 0, 25 ) , container, false);
	// W10
	container = AddWall( height, 22, D3DXVECTOR3( 46 , 0, 4 ), container, true);
	// W11
	container = AddWall( height, 26, D3DXVECTOR3( 21 , 0, 4 ),  container, false);
	// W12
	container = AddWall( height, 5, D3DXVECTOR3( 21 , 0, 0), container, true, "Textures/door.png");
	// S1
	container = AddStairs( 6, 4, D3DXVECTOR3( 20 , 0 , 25 ), container, 4, false);
	// Plateau for staircase
	container = AddFloor( 5 , 5 , D3DXVECTOR3( 20  , 6 ,  16 ), container );
	// Second half of staircase
	container = AddStairs( 6, 1, D3DXVECTOR3( 24 , 6 , 16 ), container , 4, true);
	// Right  for 2nd floor
	container = AddWall( height, 10 , D3DXVECTOR3( 20 , 0 , 16 ), container, true);
	// Left stair wall
	container = AddWall( height, 6, D3DXVECTOR3( 24 , 0, 20 ), container, true);
	// W27
	container = AddWall( height, 6, D3DXVECTOR3( 30 , 0, 20 ), container, true);
	//
	container = AddWall( height, 7, D3DXVECTOR3( 24 , 0, 20 ), container, false);
	// 2nd floor at top of stairs
	container = AddFloor( 22 , 8, D3DXVECTOR3( 30  , (int)(height / 2) , 4 ), container);
	//
	container = AddWall( height, 11, D3DXVECTOR3(20 , 0, 16 ), container, false);
	// W21
	container = AddWall( (int)(height / 2) , 21 , D3DXVECTOR3( 37  , (int)(height / 2)  , 5 ), container, true);
	// W22
	container = AddWall( (int)(height / 2) , 8, D3DXVECTOR3(30  , (int)(height / 2) , 4 ), container, true);
	// W23
	container = AddWall( (int)(height / 2) , 18, D3DXVECTOR3(13  , (int)(height / 2) , 11 ), container, false);
	// W24
	container = AddWall( (int)(height / 2) , 30, D3DXVECTOR3( 13  , (int)(height / 2) , 11 ), container, true);
	// W25
	container = AddWall(( int)(height / 2), 16, D3DXVECTOR3( 20 , (int)(height / 2) , 25 ), container, true);

	// Floor for previous walls
	container = AddFloor( 6, 18 , D3DXVECTOR3( 13 , (int)(height/2)  , 11 ), container);
	container = AddFloor( 14, 8, D3DXVECTOR3( 13  , (int)(height/2)  , 16 ), container);

	// Add floor extending into main room
	container = AddFloor(8 , 2, D3DXVECTOR3( 19 , (int)(height/2) , 29 ), container);
	container = AddFloor(8 , 2, D3DXVECTOR3( 13 , (int)(height / 2) , 29 ), container);
	container = AddFloor(5 , 8, D3DXVECTOR3(13  , (int)(height / 2) , 36 ), container);

	// W26
	container = AddWall(height, 47 , D3DXVECTOR3( 0, 0, 40 ), container, false);
	// W27
	container = AddWall(height, 2, D3DXVECTOR3( 46 , 0 , 40 ), container, true);
	// W28
	container = AddWall( height, 47, D3DXVECTOR3( 0, 0, 41 ), container, false);


	vector<D3DRECT> collisions;
	D3DRECT c1;
	c1.x1 = 3*20;
	c1.y1 = 0;
	c1.x2 = 16*20;
	c1.y2 = 26*20;
	//collisions.push_back(c1);

	AStarPathfindingGraph* graph = PathfindingUtil::CreateAStarGraphFromFloors(50, 50, 20, 20, D3DXVECTOR3(0, 0, 0), collisions);
	//create AI controller character
	
	GameEntity* aiEntity1 = this->CreateAIEntity(
		&container, 
		D3DXVECTOR3(400, 60, 700), 
		D3DXVECTOR3(10, 40, 10), 
		5,
		D3DCOLOR_RGBA(255, 0, 0, 255),
		0, 
		BasicEnemy, 
		aiEntitiesContainer, 
		graph, 
		player);
	GameEntity* aiEntity2 = this->CreateAIEntity(
		&container, 
		D3DXVECTOR3(700, 60, 700),
		D3DXVECTOR3(10, 40, 10),
		5,
		D3DCOLOR_RGBA(0, 255, 0, 255), 
		1, 
		RangedEnemy, 
		aiEntitiesContainer,
		graph, 
		player);
	GameEntity* aiEntity3 = this->CreateAIEntity(
		&container, 
		D3DXVECTOR3(350, 60, 700), 
		D3DXVECTOR3(10, 40, 10),
		5,
		D3DCOLOR_RGBA(255, 0, 0, 255), 
		2, 
		BasicEnemy, 
		aiEntitiesContainer,
		graph, 
		player);
	GameEntity* aiEntity4 = this->CreateAIEntity(
		&container, 
		D3DXVECTOR3(650, 60, 650), 
		D3DXVECTOR3(10, 40, 10),
		5,
		D3DCOLOR_RGBA(0, 255, 0, 255), 
		3, 
		RangedEnemy, 
		aiEntitiesContainer, 
		graph, 
		player);
	GameEntity* aiEntity5 = this->CreateAIEntity(
		&container, 
		D3DXVECTOR3(550, 60, 550), 
		D3DXVECTOR3(10, 40, 10),
		5,
		D3DCOLOR_RGBA(255, 0, 0, 255), 
		4, 
		BasicEnemy, 
		aiEntitiesContainer, 
		graph,
		player);
	GameEntity* aiEntity6 = this->CreateAIEntity(
		&container, 
		D3DXVECTOR3(600, 60, 650), 
		D3DXVECTOR3(10, 40, 10),
		5,
		D3DCOLOR_RGBA(0, 0, 255, 255), 
		4, 
		HealerEnemy, 
		aiEntitiesContainer, 
		graph,
		player);
	//GameEntity* aiEntity6 = this->CreateAIEntity(&container, D3DXVECTOR3(650, 60, 700), D3DXVECTOR3(10, 40, 10), D3DCOLOR_RGBA(0, 255, 0, 255), 5, RangedEnemy, aiEntitiesContainer, graph);
	
	return container;

}
void GLDrawList::SortWallIntoWall(SortNode * head,SortNode * sort)
{
	GLWall * wh=&walls[drawitems[head->itemindex].index];
	GLWall * ws=&walls[drawitems[sort->itemindex].index];
	GLWall * ws1;
	float v1=wh->PointOnSide(ws->glseg.x1,ws->glseg.y1);
	float v2=wh->PointOnSide(ws->glseg.x2,ws->glseg.y2);

	if (fabs(v1)<MIN_EQ && fabs(v2)<MIN_EQ) 
	{
		if (ws->type==RENDERWALL_FOGBOUNDARY && wh->type!=RENDERWALL_FOGBOUNDARY) 
		{
			head->AddToRight(sort);
		}
		else if (ws->type!=RENDERWALL_FOGBOUNDARY && wh->type==RENDERWALL_FOGBOUNDARY) 
		{
			head->AddToLeft(sort);
		}
		else 
		{
			head->AddToEqual(sort);
		}
	}
	else if (v1<MIN_EQ && v2<MIN_EQ) 
	{
		head->AddToLeft(sort);
	}
	else if (v1>-MIN_EQ && v2>-MIN_EQ) 
	{
		head->AddToRight(sort);
	}
	else
	{
		double r=ws->CalcIntersectionVertex(wh);

		float ix=(float)(ws->glseg.x1+r*(ws->glseg.x2-ws->glseg.x1));
		float iy=(float)(ws->glseg.y1+r*(ws->glseg.y2-ws->glseg.y1));
		float iu=(float)(ws->tcs[GLWall::UPLFT].u + r * (ws->tcs[GLWall::UPRGT].u - ws->tcs[GLWall::UPLFT].u));
		float izt=(float)(ws->ztop[0]+r*(ws->ztop[1]-ws->ztop[0]));
		float izb=(float)(ws->zbottom[0]+r*(ws->zbottom[1]-ws->zbottom[0]));

		ws->vertcount = 0;	// invalidate current vertices.
		GLWall w=*ws;
		AddWall(&w);
		ws1=&walls[walls.Size()-1];
		ws=&walls[drawitems[sort->itemindex].index];	// may have been reallocated!

		ws1->glseg.x1=ws->glseg.x2=ix;
		ws1->glseg.y1=ws->glseg.y2=iy;
		ws1->glseg.fracleft = ws->glseg.fracright = ws->glseg.fracleft + r*(ws->glseg.fracright - ws->glseg.fracleft);
		ws1->ztop[0]=ws->ztop[1]=izt;
		ws1->zbottom[0]=ws->zbottom[1]=izb;
		ws1->tcs[GLWall::LOLFT].u = ws1->tcs[GLWall::UPLFT].u = ws->tcs[GLWall::LORGT].u = ws->tcs[GLWall::UPRGT].u = iu;
		if (gl.buffermethod == BM_DEFERRED)
		{
			ws->MakeVertices(false);
			ws1->MakeVertices(false);
		}

		SortNode * sort2=SortNodes.GetNew();
		memset(sort2,0,sizeof(SortNode));
		sort2->itemindex=drawitems.Size()-1;

		if (v1>0)
		{
			head->AddToLeft(sort2);
			head->AddToRight(sort);
		}
		else
		{
			head->AddToLeft(sort);
			head->AddToRight(sort2);
		}
	}
}
// function to test threads
// This function will run concurrently.
void* avatar(void* ptr) {

    // Initial variables
    int sockfd = 0;
    struct sockaddr_in servaddr;
    avatarInfo a = *((avatarInfo *) ptr);
    fprintf(a.pLog, "\n\nTHREAD FOR %i", a.avID);

    ///////////////////////// create socket

    //Create a socket for the client
    //If sockfd<0 there was an error in the creation of the socket
    if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) <0) {
        perror("Problem in creating the socket");
        exit(2);
    }

    //Creation of the socket
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr= inet_addr(a.ip);
    servaddr.sin_port =  htons(a.MazePort); //convert to big-endian order

    //Connection of the client to the socket
    int connected = connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
    if (connected <0) {
        perror("Problem in connecting to the server");
        exit(3);
    }
    fprintf(a.pLog, "Avatar %d connected to socket: %i\n", a.avID, connected);


    //////////////////////////// send initial message

    AM_Message *ready = calloc(1, sizeof(AM_Message));
    if (!ready) {
        perror("No memory\n");
        exit(4);
    }

    ready->type = htonl(AM_AVATAR_READY);
    ready->avatar_ready.AvatarId = htonl(a.avID);

    //send ready message to server
    int sent = send(sockfd, ready, sizeof(AM_Message), 0);
    fprintf(a.pLog, "Avatar ready message sent: %i, for av %i\n", sent, a.avID);
    free(ready);
    sleep(1);

    ////////////////////////// initialize a move message and a rec message

    AM_Message *rec_message = calloc(1, sizeof(AM_Message));
    if(!rec_message) {
        perror("\nNo memory");
        exit(4);
    }

    ////////////////////////////////// listen to server

    while (1) {
        memset(rec_message, 0, sizeof(AM_Message));
        //printf("\n thread %i, socket %i", a.avID, sockfd);
        int x = recv(sockfd, rec_message, sizeof(AM_Message), 0);
        if ( x== 0) {
            //error: server terminated prematurely
            //printf("\n server error");
            return NULL;
        }

        ///////////////////////////////////////// if turnID matches avID, make a move
        if(ntohl(rec_message->type) == AM_AVATAR_TURN) {
            pthread_mutex_lock(&turn_lock);
            // if turn id is my id
            int move = -1;
            if(ntohl(rec_message->avatar_turn.TurnId) == a.avID) {
                // write board to the log
                fprintf(a.pLog, "\n\nits my turn: %i", a.avID);
                fprintf(a.pLog, "\nCurrent board:");
                XYPos pos;
                //look through the positions received from the server and add them to the Avatars, if they aren't there, or use them to update the maze based on the last move
                for(int b = 0; b < a.nAvatars; b++) {
                    pos.x = ntohl(rec_message->avatar_turn.Pos[b].x);
                    pos.y = ntohl(rec_message->avatar_turn.Pos[b].y);
                    fprintf(a.pLog, "\nPosition of avatar %i - x: %i y: %i", b,pos.x, pos.y);
                    //printf("\nCurrent position of avatar %i - x: %i y: %i", b,pos.x, pos.y);
                    //printf("\nAvatar %d: pos.x: %i, pos.y: %i, direction: %d, last_move: %d \n", b, Avatars[b].pos.x, Avatars[b].pos.y, Avatars[b].direction, Avatars[b].last_move);
                    if (Avatars[b].last_move == -1) { //if the avatar doesn't have a position yet
                        Avatars[b].pos = pos;
                        Avatars[b].last_move = M_NULL_MOVE;
                    }
                    else if (Avatars[b].last_move != M_NULL_MOVE) {
                        if ((pos.x == Avatars[b].pos.x) && (pos.y == Avatars[b].pos.y)) {
                            fprintf(a.pLog, "Avatar %d encountered a wall and did not move.", b);
                            AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 1);
                            Avatars[b].last_move = M_NULL_MOVE;
                        }
                        else {
                            fprintf(a.pLog, "Avatar %d moved successfully.", b);
                            switch(Avatars[b].last_move) {
                            case M_NORTH:
                                if (maze->maze[Avatars[b].pos.y][Avatars[b].pos.x].north_wall != 2) {
                                    AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                }
                                break;
                            case M_SOUTH:
                                if (maze->maze[Avatars[b].pos.y][Avatars[b].pos.x].south_wall != 2) {
                                    AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                }
                                break;
                            case M_EAST:
                                if (maze->maze[Avatars[b].pos.y][Avatars[b].pos.x].east_wall != 2) {
                                    AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                }
                                break;
                            case M_WEST:
                                if (maze->maze[Avatars[b].pos.y][Avatars[b].pos.x].west_wall != 2) {
                                    AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                }
                                break;
                            default:
                                AddWall(Avatars[b].pos.y, Avatars[b].pos.x, Avatars[b].last_move, 0);
                                break;
                            }
                            Avatars[b].pos = pos;
                            Avatars[b].direction = Avatars[b].last_move;
                            Avatars[b].last_move = M_NULL_MOVE;
                        }
                    }

                }

                ////////////////graphics////////////////
                //initscr();
                clear();
                raw();
                //start_color();
                create_border(maze->num_col, maze->num_row);
                draw_inside(maze);
                //draw_fakes(maze);
                int f;
                for (f = 0; f<a.nAvatars; f++) {
                    draw_avatar(2*Avatars[f].pos.y+1, 2*Avatars[f].pos.x+1);
                }
                //unsigned int microseconds;
                //microseconds = 200;
                //usleep(microseconds);
                refresh();

                /* Determine the direction of the move for the current Avatar */

                /* Avatar 0 has a fixed location - it never moves */
                if (a.avID == 0) {
                    if(!final_destination) {
                        final_destination = (XYPos *) calloc(1, sizeof(XYPos));
                        final_destination->x = Avatars[a.avID].pos.x;
                        final_destination->y = Avatars[a.avID].pos.y;
                    }
                    move = M_NULL_MOVE;
                }
                // if(!final_destination){
                //   for(int i = 0; i < a.nAvatars; i++){
                //     if (i == a.avID) continue;
                //     //if the Avatar is in the same place as another Avatar, save position as final_destination
                //     if((Avatars[i].pos.x == Avatars[a.avID].pos.x) && (Avatars[i].pos.y == Avatars[a.avID].pos.y)){
                //       final_destination = (XYPos *) calloc(1, sizeof(XYPos));
                //       final_destination->x = Avatars[a.avID].pos.x;
                //       final_destination->y = Avatars[a.avID].pos.y;
                //       move = M_NULL_MOVE;
                //       break;
                //     }
                //   }
                // }
                /* Determine the direction of the move for Avatars that aren't Avatar 0 */
                //if Avatar is at final_destination, it should not move
                if((final_destination) && (Avatars[a.avID].pos.x == final_destination->x) && (Avatars[a.avID].pos.y == final_destination ->y)) {
                    move = M_NULL_MOVE;
                }
                else { //if the Avatar is alone, use the rightHandRule to determine the next move
                    move = rightHandRule(Avatars[a.avID]);
                }

                //temporary fix to diagnose the initial -1 rightHandRule return
                if(move == -1) {
                    ClearFakeWalls(Avatars[a.avID].pos.y, Avatars[a.avID].pos.x);
                    move = rightHandRule(Avatars[a.avID]);
                    move = (move == -1) ? M_NULL_MOVE : move;
                }
                Avatars[a.avID].last_move = move;
                //int move = rand() % 4;
                // write move to the log
                fprintf(a.pLog, "\nMove: %i", move);
                //printf("\nMove: %i", move);

                //send a move message for the current avatar
                AM_Message *ready = calloc(1, sizeof(AM_Message));
                if (!ready) {
                    perror("No memory\n");
                    exit(4);
                }
                ready->type = htonl(AM_AVATAR_MOVE);
                ready->avatar_move.AvatarId = htonl(a.avID);
                ready->avatar_move.Direction =htonl(move);

                //send ready message to server
                int sent = send(sockfd, ready, sizeof(AM_Message), 0);
                fprintf(a.pLog, "\nAvatar move message sent: %i, for av %i", sent, a.avID);
                free(ready);
                //sleep(1);
            }
            pthread_mutex_unlock(&turn_lock);
        }

        // else if the message is success, break
        else if(ntohl(rec_message->type) == AM_MAZE_SOLVED) {
            pthread_mutex_lock(&solved_lock);
            if(!thread_return) {
                time_t myTime;
                char buff[100];
                thread_return = (char *) calloc(100, sizeof(char));
                myTime = time(NULL);
                strftime(buff, 100, "%a %d %Y, %H:%M", localtime(&myTime));
                //printf("%s\n", buff);
                sprintf(thread_return, "\nMaze Solved on %s!\n", buff);
                //printf("\nSolved!\n");
                //free(rec_message);
                //free(ptr);
            }

            //stop at solution, wait for an input to end graphics
            //refresh();
            //sleep(1);
            //clear();
            //printw("Maze solved!");
            //getch();
            //clear();
            //endwin();
            //delwin(stdscr);

            if(a.avID == 0) {
                //stop at solution, wait for an input to end graphics
                refresh();
                sleep(1);
                clear();
                printw("Maze solved!");
                getch();
                clear();
                //endwin();
            }
            pthread_mutex_unlock(&solved_lock);
            break;
        }

        else if(ntohl(rec_message->type) == AM_TOO_MANY_MOVES) {
            pthread_mutex_lock(&too_many_moves_lock);
            printf("\nToo many moves! You lose.\n");
            //fprintf(a.pLog,"\nToo many moves! You lose.\n");
            thread_return = "\nToo many moves! You lose.\n";
            //free(rec_message);
            //free(ptr);
            pthread_mutex_unlock(&too_many_moves_lock);
            break;
        }

        else if(IS_AM_ERROR(ntohl(rec_message->type))) {
            pthread_mutex_lock(&error_lock);
            thread_return = (char *) calloc(100, sizeof(char));
            printf("\nReceived Error code\n");
            sprintf(thread_return, "\nReceived Error code: %u\n", ntohl(rec_message->type));
            //free(rec_message);
            //free(ptr);
            pthread_mutex_unlock(&error_lock);
            break;
        }
    }
    //CleanupMaze();
    free(rec_message);
    free(ptr);
    pthread_exit(thread_return);
}
Exemple #10
0
CDTrigger *CMine::AddTrigger (UINT16 wallnum, INT16 type, BOOL bAutoAddWall) 
{
	INT16 flags;
	INT16 segnum, sidenum, trignum;
	static INT16 defWallTypes [NUM_TRIGGER_TYPES] = {
		WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_ILLUSION, 
		WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_OPEN, 
		WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_ILLUSION,
		WALL_OPEN, WALL_OPEN
		};
	static INT16 defWallTextures [NUM_TRIGGER_TYPES] = {
		0, 0, 0, 0, 426, 
		0, 0, 0, 0, 0, 
		0, 0, 0, 0, 426,
		0, 0
		};

// check if there's already a trigger on the current side
wallnum = FindTriggerWall (&trignum);
if (trignum != NO_TRIGGER) {
	ErrorMsg ("There is already a trigger on this side");
	return NULL;
	}
if (GameInfo ().triggers.count >= MAX_TRIGGERS) {
	ErrorMsg ("The maximum number of triggers has been reached.");
	return NULL;
	}
// if no wall at current side, try to add a wall of proper type
bool bUndo = theApp.SetModified (TRUE);
theApp.LockUndo ();
if (CurrSide ()->nWall >= GameInfo ().walls.count) {
	if (bAutoAddWall) {
		if (GameInfo ().walls.count >= MAX_WALLS) {
			ErrorMsg ("Cannot add a wall to this side,\nsince the maximum number of walls is already reached.");
			return NULL;
			}
		segnum = sidenum = -1;
		GetCurrent (segnum, sidenum);
		if (!AddWall (-1, -1, (Segments (segnum)->children [sidenum] < 0) ? WALL_OVERLAY : defWallTypes [type], 0, 0, -1, defWallTextures [type])) {
			ErrorMsg ("Cannot add a wall for this trigger.");
			theApp.ResetModified (bUndo);
			return NULL;
			}
		}
	else {
		ErrorMsg ("You must add a wall to this side before you can add a trigger.");
		return NULL;
		}
	}
// if D1, then convert type to flag value
if (file_type == RDL_FILE) {
	switch(type) {
		case TT_OPEN_DOOR:
			flags = TRIGGER_CONTROL_DOORS;
			break;
		case TT_MATCEN:
			flags = TRIGGER_MATCEN;
			break;
		case TT_EXIT:
			flags = TRIGGER_EXIT;
			break;
		case TT_SECRET_EXIT:
			flags = TRIGGER_SECRET_EXIT;
			break;
		case TT_ILLUSION_OFF:
			flags = TRIGGER_ILLUSION_OFF;
			break;
		case TT_ILLUSION_ON:
			flags = TRIGGER_ILLUSION_ON;
			break;
		case TT_ENERGY_DRAIN:
			flags = TRIGGER_ENERGY_DRAIN;
			break;
		case TT_SHIELD_DAMAGE:
			flags = TRIGGER_SHIELD_DAMAGE;
			break;
		default:
			flags = 0;
		}
	type = 0;
	}
else
	flags = 0;

trignum = (UINT16) GameInfo ().triggers.count;
// set new trigger data
InitTrigger (Triggers (trignum), type, flags);
// link trigger to the wall
Walls (wallnum)->trigger = (UINT8) trignum;
// update number of Triggers ()
GameInfo ().triggers.count++;
AutoLinkExitToReactor();
theApp.UnlockUndo ();
theApp.MineView ()->Refresh ();
return Triggers (trignum);
}
Exemple #11
0
void Map::LoadMap(char* fileName, ResourceManager& resMan) {
	////////////////////////////////////////////////////////////////FILE I/O STUFF
	std::stringstream ss;
	std::ifstream file;
	char lineType;
	Terrain tempTerrain;
	D3DVECTOR pos, corner1, corner2, size;
	float rot;
	int zone;
	PrimStruct *tempPrim;
	PrimObj tempObj;
	sPoint tempSpawn;
	tempObj.mat = &mat;
	tempObj.Tex = resMan.loadTexture("uvtest.png",0,0,0,0,D3DFMT_UNKNOWN,D3DPOOL_MANAGED,D3DX_DEFAULT,D3DX_DEFAULT,D3DCOLOR_XRGB(255,0,255),0);
	file.open(fileName);
	if(file.is_open()) {
		while(!file.eof()) {
			lineType = ' ';
			file>>lineType;
			if(lineType == '#') {
				//comment line
				file.ignore(256,'\n');
			} else if(lineType == 'f'||lineType == 'F') {
				//floor
				//get top left
				file>>size.x;
				file>>size.z;
				file>>size.y;
				//get bottom right
				file>>pos.x;
				file>>pos.y;
				file>>pos.z;
				//zone
				file>>zone;
				ss<<"Floor"<<size.x<<"x"<<size.y<<"x"<<size.z;

				tempPrim = resMan.loadPrim(ss.str().c_str(),size.y,size.x,size.z);
				D3DXMatrixIdentity(&tempObj.matrix);
				D3DXMatrixTranslation(&tempObj.matrix,pos.x,pos.y,pos.z);
				tempObj.primInfo = tempPrim;
				renderInfo.push_back(tempObj);

				tempTerrain.Init(pos,tempPrim,FLOOR);

				AddFloor(tempTerrain);

				floorZone.push_back(zone);
				file.ignore();
			} else if(lineType == 'w' || lineType == 'W') {
				//walls
				//get top left
				file>>size.x;
				file>>size.z;
				file>>size.y;
				//get bottom right
				file>>pos.x;
				file>>pos.y;
				file>>pos.z;
				//zone
				file>>zone;

				ss<<"Wall"<<size.x<<"x"<<size.y<<"x"<<size.z;

				tempPrim = resMan.loadPrim(ss.str().c_str(),size.y,size.x,size.z);
				D3DXMatrixIdentity(&tempObj.matrix);
				D3DXMatrixTranslation(&tempObj.matrix,pos.x,pos.y,pos.z);
				tempObj.primInfo = tempPrim;
				renderInfo.push_back(tempObj);

				tempTerrain.Init(pos,tempPrim,WALL);

				AddWall(tempTerrain);
				wallZone.push_back(zone);
				file.ignore();
			} else if(lineType == 's' || lineType == 'S'){
//------------------------- LoadMap ------------------------------------
//
//  sets up the game environment from map file
//-----------------------------------------------------------------------------
bool Raven_Map::LoadMap(const std::string& filename)
{  
  std::ifstream in(filename.c_str());
  if (!in)
  {
    ErrorBox("Bad Map Filename");
    return false;
  }

  Clear();

  BaseGameEntity::ResetNextValidID();

  //first of all read and create the navgraph. This must be done before
  //the entities are read from the map file because many of the entities
  //will be linked to a graph node (the graph node will own a pointer
  //to an instance of the entity)
  m_pNavGraph = new NavGraph(false);
  
  m_pNavGraph->Load(in);

#ifdef LOG_CREATIONAL_STUFF
    debug_con << "NavGraph for " << filename << " loaded okay" << "";
#endif

  //determine the average distance between graph nodes so that we can
  //partition them efficiently
  m_dCellSpaceNeighborhoodRange = CalculateAverageGraphEdgeLength(*m_pNavGraph) + 1;

#ifdef LOG_CREATIONAL_STUFF
    debug_con << "Average edge length is " << CalculateAverageGraphEdgeLength(*m_pNavGraph) << "";
#endif

#ifdef LOG_CREATIONAL_STUFF
    debug_con << "Neighborhood range set to " << m_dCellSpaceNeighborhoodRange << "";
#endif


  //load in the map size and adjust the client window accordingly
  in >> m_iSizeX >> m_iSizeY;

#ifdef LOG_CREATIONAL_STUFF
    debug_con << "Partitioning navgraph nodes..." << "";
#endif

  //partition the graph nodes
  PartitionNavGraph();


  //get the handle to the game window and resize the client area to accommodate
  //the map
  extern char* g_szApplicationName;
  extern char* g_szWindowClassName;
  HWND hwnd = FindWindow(g_szWindowClassName, g_szApplicationName);
  const int ExtraHeightRqdToDisplayInfo = 50;
  ResizeWindow(hwnd, m_iSizeX, m_iSizeY+ExtraHeightRqdToDisplayInfo);

#ifdef LOG_CREATIONAL_STUFF
    debug_con << "Loading map..." << "";
#endif

 
  //now create the environment entities
  while (!in.eof())
  {   
    //get type of next map object
    int EntityType;
    
    in >> EntityType;

#ifdef LOG_CREATIONAL_STUFF
    debug_con << "Creating a " << GetNameOfType(EntityType) << "";
#endif

    //create the object
    switch(EntityType)
    {
    case type_wall:
 
        AddWall(in); break;

    case type_sliding_door:
 
        AddDoor(in); break;

    case type_door_trigger:
 
        AddDoorTrigger(in); break;

   case type_spawn_point:
     
       AddSpawnPoint(in); break;

   case type_health:
     
       AddHealth_Giver(in); break;

   case type_shotgun:
     
       AddWeapon_Giver(type_shotgun, in); break;

   case type_rail_gun:
     
       AddWeapon_Giver(type_rail_gun, in); break;

   case type_rocket_launcher:
     
       AddWeapon_Giver(type_rocket_launcher, in); break;

    default:
      
      throw std::runtime_error("<Map::Load>: Attempting to load undefined object");

      return false;
      
    }//end switch
  }

#ifdef LOG_CREATIONAL_STUFF
    debug_con << filename << " loaded okay" << "";
#endif

   //calculate the cost lookup table
  m_PathCosts = CreateAllPairsCostsTable(*m_pNavGraph);

  return true;
}
Exemple #13
0
void TestFunction1(scene& scene1)
{

	AddSphere(scene1, vector3(1.5, -1.5, 0), 0.5, rgbf(0, 0, 1), false);
	//AddSphere(scene1, vector3(1, 1, 0), 0.5, rgbf(0, 1, 1), true);
		
	sphere_object* s1 = new sphere_object(0.5, vector3(1.5, -1, 0));
	s1->natrual_colour = rgbf(0, 0, 0);
	s1->reflective = true;
	s1->I_refl = 1;
	s1->k_spec = 1;	
	s1->ambient_colour = rgbf(0, 0, 0);
	s1->shininess = 100;
	//scene1.add_object(s1);

	sphere_object* s2 = new sphere_object(0.5, vector3(1.5, 1, 0));
	s2->transparent = true;
	s2->transparency = 0.9;
	s2->refindex = 0.9;
	scene1.add_object(s2);

	rgbf red(1, 0, 0);
	rgbf green(0, 1, 0);
	rgbf blue(0, 0, 1);
	rgbf yellow = red + green;
	rgbf magenta = red + blue;
	rgbf cyan = green + blue;


	AddWall(scene1, vector3(3, 0, -0.5), vector3(0, 1, 0), green * 0.7);
	AddWall(scene1, vector3(0, 3, -0.5), vector3(-1, 0, 0), red* 0.7);
	AddWall(scene1, vector3(-3, 0, -0.5), vector3(0, -1, 0), blue* 0.7);
	AddWall(scene1, vector3(0, -3, -0.5), vector3(1, 0, 0), yellow* 0.7);
	

	AddCeiling(scene1, vector3(0, 0, +3.5), magenta * 0.7);
	AddFloor(scene1, vector3(0, 0, -0.5), cyan * 0.7);

	//AddBox(scene1, vector3(1, -0.5, -0.3), 0.2, rgbf(1, 0, 1), true);

	box* box1 = new box(vector3(1, -0.5, 0), vector3(-0.2, -0.2, -0.2), vector3(0.2, 0.2, 0.2));
	box1->natrual_colour = rgbf(0, 0, 0);
	box1->reflective = false;
	box1->transparent = true;
	box1->transparency = 1;
	box1->I_refr = 1;
	box1->refindex = 2;
	scene1.add_object(box1);

	//AddLightBall(scene1, vector3(-0.8, 0, 3), 3, 0.1);

	AddLight(scene1, vector3(-1.5, 1.5, 3));
	//AddLight(scene1, vector3(2, 0, 4));
	//AddLight(scene1, vector3(-5, 3, 2));

	//IcoSphere(scene1, vector3(4, 0, 2));

	torus_object* tor1 = new torus_object(0.1,0.5,vector3(1,0,-0.5));
	tor1->natrual_colour = rgbf(1, 0, 0);	
	//tor1->ambient_colour = rgbf(0, 0, 0.5);
	//scene1.add_object(tor1);

	mesh* m1 = ReadMesh("teapot.obj", vector3(1, -0.25, -0.5));
	m1->natrual_colour = rgbf(0, 0, 0);
	m1->reflective = false;
	m1->transparent = true;
	m1->transparency = 1;
	m1->I_refr = 1;

	//scene1.add_object(m1);
	
	
}
int main(int argc, char *argv[]) {

    VERBOSE = 0;
    GRAPHICS = 0;
    validate(argc, argv);
    
    int avatarID = atoi(argv[1]);
    FILE *logFile;
    logFile = fopen(argv[6], "a+");
    char *IP = (char*)calloc(strlen(argv[4]) + 1, sizeof(char));
    MALLOC_CHECK(stderr, IP);
    strncpy(IP, argv[4], strlen(argv[4]));
    
    
    myAvatar *avatar;
    int slobAvatar = 0;     // the one who doesn't move in maze solver

    int mazePort = atoi(argv[5]);
    
    int width = atoi(argv[7]);
    int height = atoi(argv[8]);
    int shmID = atoi(argv[9]);
    char *maze = (char*) shmat(shmID, 0, 0);
    if (maze == (void *)-1 && errno == EACCES) {

        fprintf(stderr, "shmat failed EACCES\n");
        exit(1);
    }
    if (maze == (void *)-1 && errno == EINVAL) {

        fprintf(stderr, "shmat failed EINVAL\n");
        exit(1);
    }
    if (maze == (void *)-1 && errno == ENOMEM) {

        fprintf(stderr, "shmat failed ENOMEM\n");
        exit(1);
    }

    // Server connection stuff
    int sockfd;
    struct sockaddr_in servaddr;
    
    // Create and check status of server
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        free(IP);
        fprintf(stderr, "Could not create socket.\n");
        return 0;   // false
    }
    
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = inet_addr(IP);
    servaddr.sin_port = htons(mazePort);
    
    // Connect to server
    if (connect(sockfd, (struct sockaddr*) &servaddr, \
                sizeof(servaddr)) < 0) {
        fprintf(stderr, "Unable to connect to server. Exiting.\n");
        free(IP);
        return 0;   // false
    }
    
    // Fire off initial AM_AVATAR_READY
    AM_Message *sendmsg = (AM_Message*)calloc(1, sizeof(AM_Message));
    MALLOC_CHECK(stderr, sendmsg);
    
    sendmsg->type = htonl(AM_AVATAR_READY);
    sendmsg->avatar_ready.AvatarId = htonl(avatarID);  // pack information
    
    // Send ready message to server containing avatar ID
    send(sockfd, sendmsg, sizeof(AM_Message), 0);
    
    // Make a message to get back from server
    AM_Message *receivemsg = (AM_Message*)calloc(1, sizeof(AM_Message));
    MALLOC_CHECK(stderr, receivemsg);

    int firstMove = 1;
    int turn = -1;
    // Start while loop that checks all server messages and updates
    // the avatar's position until either error message or AM_SOLVED received
    for ( ;; ) {
        
        // Zero out the message pointers so they can be re-used
        memset(receivemsg, 0, sizeof(AM_Message));
        memset(sendmsg, 0, sizeof(AM_Message));
        
        // Receive the message and make sure it's not empty
        if (recv(sockfd, receivemsg, sizeof(AM_Message), 0) == 0) {
            fprintf(stderr, "Server terminated early.\n");
            OUTPUT(logFile, "Empty message type. Exiting...\n");
            break;
        }
        
        // Check for server error
        if (IS_AM_ERROR(receivemsg->type)) {
            fprintf(stderr, "Error mask detected error.\n");
        }
        
        // Following if statements will check for all possible server errors
        // In all cases, print to stderr, log the error to output file
        // and break to free resources and return
        
        if (ntohl(receivemsg->type) == AM_UNKNOWN_MSG_TYPE) {
            fprintf(stderr, "AM_UNKNOWN_MSG_TYPE\n");
            OUTPUT(logFile, "Unknown message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_NO_SUCH_AVATAR) {
            fprintf(stderr, "AM_NO_SUCH_AVATAR\n");
            OUTPUT(logFile, "No such avatar error. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_UNEXPECTED_MSG_TYPE) {
            fprintf(stderr, "AM_UNEXPECTED_MSG_TYPE\n");
            OUTPUT(logFile, "Unexpected message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_AVATAR_OUT_OF_TURN) {
            fprintf(stderr, "AM_AVATAR_OUT_OF_TURN\n");
            OUTPUT(logFile, "Avatar out of turns message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_TOO_MANY_MOVES) {
            fprintf(stderr, "AM_AVATAR_TOO_MANY_MOVES\n");
            OUTPUT(logFile, "Avatar too many moves message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_SERVER_TIMEOUT) {
            fprintf(stderr, "AM_SERVER_TIMEOUT\n");
            OUTPUT(logFile, "Server timeout message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_SERVER_DISK_QUOTA) {
            fprintf(stderr, "AM_SERVER_DISK_QUOTA\n");
            OUTPUT(logFile, "Server disk quota message type. Exiting...\n");
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_SERVER_OUT_OF_MEM) {
            fprintf(stderr, "AM_SERVER_OUT_OF_MEM\n");
            OUTPUT(logFile, "Server out of mem message type. Exiting...\n");
            break;
        }
        
        // Huzzah! Output success to log file.
        if (ntohl(receivemsg->type) == AM_MAZE_SOLVED) {
            
            // Only output this stuff once.
            if (avatarID == slobAvatar) {
                fprintf(stdout, "SOLVED!!!\n");
                fprintf(logFile, "Maze solved with %d avatars on %d"
                        " difficulty in %d moves. The Hash key is: %d.\n", ntohl(receivemsg->maze_solved.nAvatars),\
                        ntohl(receivemsg->maze_solved.Difficulty), ntohl(receivemsg->maze_solved.\
                        nMoves), ntohl(receivemsg->maze_solved.Hash));
            }
            
            break;
        }
        
        if (ntohl(receivemsg->type) == AM_AVATAR_TURN) {
            // Only look at messages from the relevant reply messages
            if (ntohl(receivemsg->avatar_turn.TurnId) == avatarID) {
                
                if (firstMove) {
                    // Initialize the avatar.
                    avatar = (myAvatar*)calloc(1, sizeof(myAvatar));
                    MALLOC_CHECK(stderr, avatar);
                    avatar->fd = avatarID;
                    avatar->lastMoveDir = M_NORTH;  // everyone goes north initially
                    
                    // Initially, avatar's previous position and current position
                    // are the same. Retrieve these from server.
                    avatar->pos.x = ntohl(receivemsg->avatar_turn.Pos[avatarID].x);
                    avatar->pos.y = ntohl(receivemsg->avatar_turn.Pos[avatarID].y);
                    
                    // No previous initially.
                    
                    // Send the avatar north.
                    sendmsg->type = htonl(AM_AVATAR_MOVE);
                    sendmsg->avatar_move.AvatarId = htonl(avatarID);
                    sendmsg->avatar_move.Direction = htonl(M_NORTH);
                    
                    if (VERBOSE) {
                        fprintf(stdout, "Avatar %d: Initial pos (%d, %d) moved NORTH\n", avatarID,\
                                avatar->pos.x, avatar->pos.y);
                    }
                    // Send ready message to server containing avatar ID
                    send(sockfd, sendmsg, sizeof(AM_Message), 0);
                    turn = 1;
                    firstMove = 0;

                    if (GRAPHICS) {
                        //initialize graphics
                        AddAvatar(maze,avatar,width);
                        PrintMaze(maze, width, height);
                    }
                    
                    continue;
                    
                }
                
                else {  // not first move
                    
                    // If it's the avatar standing still, arbitrarily picked as
                    // avatar with ID = 0, then always stand still.
                    if (avatarID == slobAvatar) {
                        sendmsg->type = htonl(AM_AVATAR_MOVE);
                        sendmsg->avatar_move.AvatarId = htonl(avatarID); // should be 0
                        sendmsg->avatar_move.Direction = htonl(M_NULL_MOVE);
                        send(sockfd, sendmsg, sizeof(AM_Message), 0);
                        turn++;
                        continue;
                    }
                    
                    // Make the previous the current position
                    avatar->prev.x = avatar->pos.x;
                    avatar->prev.y = avatar->pos.y;
                    turn++;
                    // Make current position the new one from the server
                    int newX = ntohl(receivemsg->avatar_turn.Pos[avatarID].x);
                    int newY = ntohl(receivemsg->avatar_turn.Pos[avatarID].y);
                    avatar->pos.x = newX;
                    avatar->pos.y = newY;
                    
                    // See if the slob and the current avatar are on the same spot.
                    int deltaX = avatar->pos.x - ntohl(receivemsg->avatar_turn.Pos[slobAvatar].x);
                    int deltaY = avatar->pos.y - ntohl(receivemsg->avatar_turn.Pos[slobAvatar].y);
                    int checkSameCell = 0;
                    
                    if ((deltaY == 0) && (deltaX == 0)) {
                        checkSameCell = 1;
                    }
                    // If avatar is on same spot as slob, slob has been found.
                    // Don't move the other avatar.
                    if (checkSameCell) {
                        sendmsg->type = htonl(AM_AVATAR_MOVE);
                        sendmsg->avatar_move.AvatarId = htonl(avatarID);
                        sendmsg->avatar_move.Direction = htonl(M_NULL_MOVE);
                        send(sockfd, sendmsg, sizeof(AM_Message), 0);
                        turn++;
                        continue;
                    }
                    
                    // Avatar is not slob and has not yet met slob.
                    else {
                        
                        // See if the last move was productive
                        int lastMove = checkLastMove(avatar);
                        avatar->lastMoveSuccess = lastMove;

                        //update graphics based on last move

                        if(!lastMove){
                            AddWall(maze,avatar,width);
                        }
                        else{
                            //DelAvatar(maze,avatar,width);//comment out to see history
                            if(!AddMark(maze,avatar,width))//blocks square if test passes
                                AddAvatar(maze,avatar,width);
                        }
                        
                        if (GRAPHICS) {
                            PrintMaze(maze,width,height);
                        }
                        
                        
                        

                        //prep next move
                        int nextMove = getMove(avatar);
                        avatar->lastMoveDir = nextMove;
                        while(isKnown(maze, avatar, width)){
                            avatar->lastMoveSuccess = false;
                            nextMove = getMove(avatar);
                            avatar->lastMoveDir = nextMove;
                        }
                        
                        turn++;
                        sendmsg->type = htonl(AM_AVATAR_MOVE);
                        sendmsg->avatar_move.AvatarId = htonl(avatarID);
                        sendmsg->avatar_move.Direction = htonl(nextMove);
                        
                        if (VERBOSE) {
                            fprintf(stdout, "======== Turn %d ========\n", turn);
                            if (nextMove == M_NORTH) {
                                fprintf(stdout, "Avatar %d: Moved NORTH from (%d, %d).\n", avatarID,\
                                        avatar->pos.x, avatar->pos.y);
                            }
                            if (nextMove == M_SOUTH) {
                                fprintf(stdout, "Avatar %d: Moved SOUTH from (%d, %d).\n", avatarID,\
                                        avatar->pos.x, avatar->pos.y);
                            }
                            
                            if (nextMove == M_WEST) {
                                fprintf(stdout, "Avatar %d: Moved WEST from (%d, %d).\n", avatarID,\
                                        avatar->pos.x, avatar->pos.y);
                            }
                            
                            if (nextMove == M_EAST) {
                                fprintf(stdout, "Avatar %d: Moved EAST from (%d, %d).\n", avatarID,\
                                        avatar->pos.x, avatar->pos.y);
                            }
                            fprintf(stdout, "\n");
                        }
                        
                        send(sockfd, sendmsg, sizeof(AM_Message), 0);
                    }
                    
                }
            }
            
        }
        
    }
    shmctl(shmID, IPC_RMID, NULL);
    free(sendmsg); free(receivemsg); free(IP); free(avatar);
    fclose(logFile);
    close(sockfd);
    return 1;
    
}
Exemple #15
0
int main (void)
{
	unsigned char MoveDir=0;

	SetupCpu();
	SetupCode();
	rfPwrUp();
	rfRxMode();
	LED1ON;
	WaitForSwitch();
	LED1OFF;
//TimerAStart();


/*
while(1)
{
	if (CTS)
	{
		LED5TOGGLE;
	}
	if (!CTS) LED5OFF;
	if( TimerExpired || IfSwitch() )
	{
		CTS=0;
		TimerExpired=0;
		AssembleStartTimerPacket();
		rfStandbyMode();
		rfSendPacket2Module(&TxPacket[0],32);
		rfTxMode();
		softDelay(65535);
		rfStandbyMode();
		rfRxMode();
		LED1TOGGLE;
	}
}
*/






//	MAZE MAPPING CODE
	AddWall(SOUTH, GetMouseX(), GetMouseY() );
	ReserveCurrentCell();
	AnalyseCellLR();
	AnalyseCellFB();
	ReserveCellsAroundHere();
	IncrementCellVisits();
	SetThisCellMappedByThisMouse();
	TxCellInfo();

	while (1)
	{


		MoveDir = 0;

		while (!MoveDir) //If unable to get an exit, redo until can get exit
		{
			MoveDir=GetExitDir();
			LED7ON;
		}
		LED7OFF;

		ReserveCellsAround(MoveDir);

		Rotate( MoveDir );

		DriveToEndOfCurrentCellCorrecting();

		MoveToNewCellLogical(MoveDir);		// no walls in new cell, so will not correct until LR analysed

		DriveToStartOfNextCellNOTCorrecting();

		AnalyseCellLR();		// analysed, so if walls exist, mouse will correct itself

		DriveToMiddleOfNewCellCorrecting();

		AnalyseCellFB();

		IncrementCellCount();

		IncrementCellVisits();

		TxCellInfo();

		ReleaseOldCells(MoveDir);

		ReleaseWalledCells();

		DeadEndBlocking();

		if ( IsMazeMapped() ) break;


	}

	SetLedsLower(0x55);


		// count total visits in maze

	unsigned char x = 0;
	unsigned char y = 0;
	unsigned char count = 0;

	while (y < MAZEY)
	{
		while (x < MAZEX)
		{
			count += GetVisits(x,y);
			x++;
		}
		y++;
		x=0;
	}

//	SetLedsUpper (count);

	while (1)
	{
		WaitForSwitch();
//		SetLedsUpper(GetLargeErrors());

		WaitForSwitch();
//		SetLedsUpper(GetSmallErrors());
	}


	return 0;
}