Esempio n. 1
0
void NetworkManager::GameRun()
{
	PacketType type;

	Network::GameStartData gameStartData;
	puts("게임 시작 대기중");
	network.WaitForStart(&gameStartData);
	wprintf_s(L"매칭되었습니다. 상대방 이름: %s, 학번: %d\n", gameStartData.oppositionName, gameStartData.oppositionStudentID);

	bool allOver = false;

	while (!allOver)
	{
		
		GameInit();
		ShipSetting();

		try
		{
			GameStart();
			network.GetPacketType(&type);

			if (type == PKT_SC_NEXT_GAME)
			{
				puts("다음 게임을 준비해주세요.");
				
			}
			else if (type == PKT_SC_ALL_OVER)
			{
				Network::FinalResultData finalresult;
				finalresult = network.GetFinalResult();
				puts("모두 종료");
				printf_s("승리 횟수: %d, 평균 턴 수: %.1f", finalresult.winCount, finalresult.avgTurns);

				allOver = true;
			}
			else
			{
				throw Network::UNEXPECTED_PACKET;
			}
		}
		catch (Network::Exception ex)
		{
			switch (ex)
			{
			case Network::NETWORK_ERROR:
				puts("네트워크에 문제가 발생했습니다.");
				break;
			case Network::SERVER_CLOSED:
				puts("서버와의 연결이 끊어졌습니다.");
				break;
			case Network::PARAMETER_ERROR:
				puts("함수의 인수가 잘못되었습니다.");
				break;
			case Network::UNEXPECTED_PACKET:
				puts("서버에서 잘못된 정보가 전송되었습니다.");
				break;
			default:
				break;
			}
		}
		
	}
}
int
main(int argc, char *argv[])
{
	if (argc != 6)
	{
		fprintf(stderr, "Usage: %s <in bmp file> <out bmp file> <x> <y> <N>\n", argv[0]);
		return -1;
	}
	
	printf("Program started.\r\n");

	clock_t start_time = clock();

	int err_code = 0;
	try {
		// Read the input image
		bmp_in in;
		if ((err_code = bmp_in__open(&in, argv[1])) != 0)
			throw err_code;

		int location_x = atoi(argv[3]);
		int location_y = atoi(argv[4]);
		int out_size = atoi(argv[5]);

		int width = in.cols, height = in.rows;
		int n, num_comps = in.num_components;

		if (out_size % 2 == 1)
		{
			err_code = NOT_A_EVEN_NUMBER;
			throw err_code;
		}

		int half_outsize = out_size / 2;

		if (width < location_x) {
			err_code = X_ECCESS;
			throw err_code;
		}

		if (height < location_y) {
			err_code = Y_ECCESS;
			throw err_code;
		}

		my_aligned_image_comp *input_comps =
			new my_aligned_image_comp[num_comps];
		for (n = 0; n < num_comps; n++)
			input_comps[n].init(height, width, half_outsize+1); // Leave a border of output size

		int r; // Declare row index
		io_byte *line = new io_byte[width*num_comps];
		for (r = height - 1; r >= 0; r--)
		{ // "r" holds the true row index we are reading, since the image is
		  // stored upside down in the BMP file.
			if ((err_code = bmp_in__get_line(&in, line)) != 0)
				throw err_code;
			for (n = 0; n < num_comps; n++)
			{
				io_byte *src = line + n; // Points to first sample of component n
				float *dst = input_comps[n].buf + r * input_comps[n].stride;
				for (int c = 0; c < width; c++, src += num_comps)
					dst[c] = (float)*src; // The cast to type "float" is not
						  // strictly required here, since bytes can always be
						  // converted to floats without any loss of information.
			}
		}
		delete[] line;
		bmp_in__close(&in);

		// Allocate storage for the filtered output
		my_aligned_image_comp *output_comps =
			new my_aligned_image_comp[num_comps];

		for (n = 0; n < num_comps; n++) {
			output_comps[n].init(out_size, out_size, 0); // Don't need a border for output
		}

		  // Process the image, all in floating point (easy)
		for (n = 0; n < num_comps; n++) {
			input_comps[n].perform_boundary_extension();
		}

		for (int k = 0; k < num_comps; ++k)
			for (int i = -half_outsize; i < half_outsize; ++i)
				for (int j = -half_outsize; j < half_outsize; ++j) {
					output_comps[k].buf[(i+ half_outsize) * output_comps[k].stride + (j+ half_outsize)]
						= input_comps[k].buf[i * input_comps[k].stride + j 
						+ location_x + location_y * input_comps[k].stride];
				}

		for (n = 0; n < num_comps; n++) {
			output_comps[n].mean_substract();
			output_comps[n].hanning_window();
		}

		
		// Write the image back out again
		bmp_out out;
		io_byte *out_line = new io_byte[out_size*num_comps];
		if ((err_code = bmp_out__open(&out, argv[2], out_size, out_size, num_comps)) != 0)
			throw err_code;
		for (r = out_size - 1; r >= 0; r--)
		{ // "r" holds the true row index we are writing, since the image is
		  // written upside down in BMP files.
			for (n = 0; n < num_comps; n++)
			{
				io_byte *dst = out_line + n; // Points to first sample of component n
				float *src = output_comps[n].buf + r * output_comps[n].stride;
				for (int c = 0; c < out_size; c++, dst += num_comps) {
					
					if (src[c] > 255) {
						src[c] = 255;
					}
					else if (src[c] < 0) {
						src[c] = 0;
					}
						
					*dst = (io_byte)src[c];
				}
			}
			bmp_out__put_line(&out, out_line);
		}
		bmp_out__close(&out);
		delete[]out_line;
		delete[] input_comps;
		delete[] output_comps;

		clock_t end_time = clock();
		float elaps = ((float)(end_time - start_time)) / CLOCKS_PER_SEC;
		printf_s("The runtime is %f seconds!\n\r", elaps);
		system("Pause");

	}
	catch (int exc) {
		if (exc == IO_ERR_NO_FILE)
			fprintf(stderr, "Cannot open supplied input or output file.\n");
		else if (exc == IO_ERR_FILE_HEADER)
			fprintf(stderr, "Error encountered while parsing BMP file header.\n");
		else if (exc == IO_ERR_UNSUPPORTED)
			fprintf(stderr, "Input uses an unsupported BMP file format.\n  Current "
				"simple example supports only 8-bit and 24-bit data.\n");
		else if (exc == IO_ERR_FILE_TRUNC)
			fprintf(stderr, "Input or output file truncated unexpectedly.\n");
		else if (exc == IO_ERR_FILE_NOT_OPEN)
			fprintf(stderr, "Trying to access a file which is not open!(?)\n");
		else if (exc == X_ECCESS)
			fprintf(stderr, "The given location eccess x dimension!\n");
		else if (exc == Y_ECCESS)
			fprintf(stderr, "The given location eccess y dimension!\n");
		else if (exc == NOT_A_EVEN_NUMBER)
			fprintf(stderr, "The given output dimension is not a odd number!\n");
		return -1;
	}
	return 0;
}
Esempio n. 3
0
int main() {
	TList *list = new TList();
	printf_s("list.First() = %s\n", list->First());
	printf_s("list.Pop() = %s\n", list->Pop());

	list->Push("Hola");
	printf_s("Pushed \"Hola\"!\n");
	list->Push("Holita");
	printf_s("Pushed \"Holita\"!\n");
	list->Push("Que tal?");
	printf_s("Pushed \"Que tal?\"!\n");

	printf_s("list.Next() = %s\n", list->Next());
	printf_s("list.Next() = %s\n", list->Next());
	printf_s("list.Next() = %s\n", list->Next());
	printf_s("list.Next() = %s\n", list->Next());

	printf_s("list.First() = %s\n", list->First());
	printf_s("list.Pop() = %s\n", list->Pop());
	printf_s("list.First() = %s\n", list->First());

	list->Push("Hola");

	list->Reset();
	printf_s("list reset!\n");

	printf_s("list.First() = %s\n", list->First());
	printf_s("list.Next() = %s\n", list->Next());

	delete list;

	getchar();
}
Esempio n. 4
0
bool GameInterface::GameStartOrReset()
{
	bool startOrReset = true;
	int gotoX = (m_MapSize + 3) * 4 + 4;
	int gotoY = 7;
	SetColor(BLACK, GREEN);
	SetCursorPosition(gotoX + 2, gotoY + 12);
	printf_s("                  \n");
	SetCursorPosition(gotoX + 2, gotoY + 13);
	printf_s("    Start Game    \n");
	SetCursorPosition(gotoX + 2, gotoY + 14);
	printf_s("                  \n");
	SetColor(BLACK, WHITE);
	SetCursorPosition(gotoX + 2, gotoY + 17);
	printf_s("                  \n");
	SetCursorPosition(gotoX + 2, gotoY + 18);
	printf_s("       Reset      \n");
	SetCursorPosition(gotoX + 2, gotoY + 19);
	printf_s("                  ");
	while (true)
	{
		int keyinput;
		keyinput = _getch();
		if (keyinput == -32)
		{
			keyinput = _getch();
		}
		if (keyinput == KEY_DOWN && startOrReset == true)
		{
			SetColor(BLACK, WHITE);
			SetCursorPosition(gotoX + 2, gotoY + 12);
			printf_s("                  \n");
			SetCursorPosition(gotoX + 2, gotoY + 13);
			printf_s("    Start Game    \n");
			SetCursorPosition(gotoX + 2, gotoY + 14);
			printf_s("                  \n");
			SetColor(BLACK, DARK_RED);
			SetCursorPosition(gotoX + 2, gotoY + 17);
			printf_s("                  \n");
			SetCursorPosition(gotoX + 2, gotoY + 18);
			printf_s("       Reset      \n");
			SetCursorPosition(gotoX + 2, gotoY + 19);
			printf_s("                  ");
			startOrReset = false; //Reset
		}
		else if (keyinput == KEY_UP && startOrReset == false)
		{
			SetColor(BLACK, GREEN);
			SetCursorPosition(gotoX + 2, gotoY + 12);
			printf_s("                  \n");
			SetCursorPosition(gotoX + 2, gotoY + 13);
			printf_s("    Start Game    \n");
			SetCursorPosition(gotoX + 2, gotoY + 14);
			printf_s("                  \n");
			SetColor(BLACK, WHITE);
			SetCursorPosition(gotoX + 2, gotoY + 17);
			printf_s("                  \n");
			SetCursorPosition(gotoX + 2, gotoY + 18);
			printf_s("       Reset      \n");
			SetCursorPosition(gotoX + 2, gotoY + 19);
			printf_s("                  ");
			startOrReset = true; //Start
		}
		else if (keyinput == ENTER)
		{
			break;
		}
	}
	SetColor(WHITE, BLACK);
	return startOrReset;
}
Esempio n. 5
0
/* controls the car */
static void drive(int index, tCarElt* car, tSituation *situation)
{
	tdble angle;
	tdble brake;
	tdble b1;							/* brake value in case we are to fast HERE and NOW */
	tdble b2;							/* brake value for some brake point in front of us */
	tdble b3;							/* brake value for control (avoid loosing control) */
	tdble b4;							/* brake value for avoiding high angle of attack */
	tdble steer, targetAngle, shiftaccel;

	MyCar* myc = mycar[index-1];
	Pathfinder* mpf = myc->getPathfinderPtr();

	b1 = b2 = b3 = b4 = 0.0;
	shiftaccel = 0.0;

	/* update some values needed */
	myc->update(myTrackDesc, car, situation);

	/* decide how we want to drive */
	if ( car->_dammage < myc->undamaged/3 && myc->bmode != myc->NORMAL) {
		myc->loadBehaviour(myc->NORMAL);
	} else if (car->_dammage > myc->undamaged/3 && car->_dammage < (myc->undamaged*2)/3 && myc->bmode != myc->CAREFUL) {
		myc->loadBehaviour(myc->CAREFUL);
	} else if (car->_dammage > (myc->undamaged*2)/3 && myc->bmode != myc->SLOW) {
		myc->loadBehaviour(myc->SLOW);
	}

	/* update the other cars just once */
	if (currenttime != situation->currentTime) {
		currenttime = situation->currentTime;
		for (int i = 0; i < situation->_ncars; i++) ocar[i].update();
	}

	/* startmode */
	if (myc->trtime < 5.0 && myc->bmode != myc->START) {
		myc->loadBehaviour(myc->START);
		myc->startmode = true;
	}
	if (myc->startmode && myc->trtime > 5.0) {
		myc->startmode = false;
		myc->loadBehaviour(myc->NORMAL);
	}

	/* compute path according to the situation */
	mpf->plan(myc->getCurrentSegId(), car, situation, myc, ocar);

	/* clear ctrl structure with zeros and set the current gear */
	memset(&car->ctrl, 0, sizeof(tCarCtrl));
	car->_gearCmd = car->_gear;

	/* uncommenting the following line causes pitstop on every lap */
	//if (!mpf->getPitStop()) mpf->setPitStop(true, myc->getCurrentSegId());
	/* compute fuel consumption */
	if (myc->getCurrentSegId() >= 0 && myc->getCurrentSegId() < 5 && !myc->fuelchecked) {
		if (car->race.laps > 0) {
			myc->fuelperlap = MAX(myc->fuelperlap, (myc->lastfuel+myc->lastpitfuel-car->priv.fuel));
		}
		myc->lastfuel = car->priv.fuel;
		myc->lastpitfuel = 0.0;
		myc->fuelchecked = true;
	} else if (myc->getCurrentSegId() > 5) {
		myc->fuelchecked = false;
	}

	/* decide if we need a pit stop */
	if (!mpf->getPitStop() && (car->_remainingLaps-car->_lapsBehindLeader) > 0 && (car->_dammage > myc->MAXDAMMAGE ||
		(car->priv.fuel < 1.5*myc->fuelperlap &&
		 car->priv.fuel < (car->_remainingLaps-car->_lapsBehindLeader)*myc->fuelperlap)))
	{
		mpf->setPitStop(true, myc->getCurrentSegId());
	}

	if (mpf->getPitStop()) {
		car->_raceCmd = RM_CMD_PIT_ASKED;
	}

	/* steer to next target point */
	targetAngle = atan2(myc->destpathseg->getLoc()->y - car->_pos_Y, myc->destpathseg->getLoc()->x - car->_pos_X);
	targetAngle -= car->_yaw;
	NORM_PI_PI(targetAngle);
    steer = targetAngle / car->_steerLock;

	/* brakes */
    tdble brakecoeff = 1.0/(2.0*g*myc->currentseg->getKfriction()*myc->CFRICTION);
    tdble brakespeed, brakedist;
	tdble lookahead = 0.0;
	int i = myc->getCurrentSegId();
	brake = 0.0;

	while (lookahead < brakecoeff * myc->getSpeedSqr()) {
		lookahead += mpf->getPathSeg(i)->getLength();
		brakespeed = myc->getSpeedSqr() - mpf->getPathSeg(i)->getSpeedsqr();
		if (brakespeed > 0.0) {
			tdble gm, qb, qs;
			gm = myTrackDesc->getSegmentPtr(myc->getCurrentSegId())->getKfriction()*myc->CFRICTION*myTrackDesc->getSegmentPtr(myc->getCurrentSegId())->getKalpha();
			qs = mpf->getPathSeg(i)->getSpeedsqr();
			brakedist = brakespeed*(myc->mass/(2.0*gm*g*myc->mass + qs*(gm*myc->ca + myc->cw)));

			if (brakedist > lookahead - myc->getWheelTrack()) {
				qb = brakespeed*brakecoeff/brakedist;
				if (qb > b2) {
					b2 = qb;
				}
			}
		}
		i = (i + 1 + mpf->getnPathSeg()) % mpf->getnPathSeg();
	}

	if (myc->getSpeedSqr() > myc->currentpathseg->getSpeedsqr()) {
		b1 = (myc->getSpeedSqr() - myc->currentpathseg->getSpeedsqr()) / (myc->getSpeedSqr());
	}

	/* try to avoid flying */
	if (myc->getDeltaPitch() > myc->MAXALLOWEDPITCH && myc->getSpeed() > myc->FLYSPEED) {
		b4 = 1.0;
	}

	if (!mpf->getPitStop()) {
		steer = steer + MIN(0.1, myc->derror*0.02)*myc->getErrorSgn();
		if (fabs(steer) > 1.0) steer/=fabs(steer);
	}

	/* check if we are on the way */
	if (myc->getSpeed() > myc->TURNSPEED && myc->tr_mode == 0) {
		if (myc->derror > myc->PATHERR) {
			v3d r;
			myc->getDir()->crossProduct(myc->currentpathseg->getDir(), &r);
			if (r.z*myc->getErrorSgn() >= 0.0) {
				targetAngle = atan2(myc->currentpathseg->getDir()->y, myc->currentpathseg->getDir()->x);
				targetAngle -= car->_yaw;
				NORM_PI_PI(targetAngle);
				double toborder = MAX(1.0, myc->currentseg->getWidth()/2.0 - fabs(myTrackDesc->distToMiddle(myc->getCurrentSegId(), myc->getCurrentPos())));
				b3 = (myc->getSpeed()/myc->STABLESPEED)*(myc->derror-myc->PATHERR)/toborder;
			}
		}
	}

	/* try to control angular velocity */
	double omega = myc->getSpeed()/myc->currentpathseg->getRadius();
	steer += 0.1*(omega - myc->getCarPtr()->_yaw_rate);

	/* anti blocking and brake code */
	if (b1 > b2) brake = b1; else brake = b2;
	if (brake < b3) brake = b3;
	if (brake < b4) {
		brake = MIN(1.0, b4);
		tdble abs_mean;
		abs_mean = (car->_wheelSpinVel(REAR_LFT) + car->_wheelSpinVel(REAR_RGT))*car->_wheelRadius(REAR_LFT)/myc->getSpeed();
		abs_mean /= 2.0;
    	brake = brake * abs_mean;
	} else {
		brake = MIN(1.0, brake);
		tdble abs_min = 1.0;
		for (int i = 0; i < 4; i++) {
			tdble slip = car->_wheelSpinVel(i) * car->_wheelRadius(i) / myc->getSpeed();
			if (slip < abs_min) abs_min = slip;
		}
    	brake = brake * abs_min;
	}

	float weight = myc->mass*G;
	float maxForce = weight + myc->ca*myc->MAX_SPEED*myc->MAX_SPEED;
	float force = weight + myc->ca*myc->getSpeedSqr();
	brake = brake*MIN(1.0, force/maxForce);

	// Gear changing.
	if (myc->tr_mode == 0) {
		if (car->_gear <= 0) {
			car->_gearCmd =  1;
		} else {
			float gr_up = car->_gearRatio[car->_gear + car->_gearOffset];
			float omega = car->_enginerpmRedLine/gr_up;
			float wr = car->_wheelRadius(2);

			if (omega*wr*myc->SHIFT < car->_speed_x) {
				car->_gearCmd++;
			} else {
				float gr_down = car->_gearRatio[car->_gear + car->_gearOffset - 1];
				omega = car->_enginerpmRedLine/gr_down;
				if (car->_gear > 1 && omega*wr*myc->SHIFT > car->_speed_x + myc->SHIFT_MARGIN) {
					car->_gearCmd--;
				}
			}
		}
	}

	tdble cerror, cerrorh;
	cerrorh = sqrt(car->_speed_x*car->_speed_x + car->_speed_y*car->_speed_y);
	if (cerrorh > myc->TURNSPEED) cerror = fabs(car->_speed_x)/cerrorh; else cerror = 1.0;

	/* acceleration / brake execution */
	if (myc->tr_mode == 0) {
		if (brake > 0.0) {
			myc->accel = 0.0;
			car->_accelCmd = myc->accel;
			car->_brakeCmd = brake*cerror;
		} else {
			if (myc->getSpeedSqr() < mpf->getPathSeg(myc->getCurrentSegId())->getSpeedsqr()) {
				if (myc->accel < myc->ACCELLIMIT) {
					myc->accel += myc->ACCELINC;
				}
				car->_accelCmd = myc->accel/cerror;
			} else {
				if (myc->accel > 0.0) {
					myc->accel -= myc->ACCELINC;
				}
				car->_accelCmd = myc->accel = MIN(myc->accel/cerror, shiftaccel/cerror);
			}
			tdble slipspeed = myc->querySlipSpeed(car);
			if (slipspeed > myc->TCL_SLIP) {
				car->_accelCmd = car->_accelCmd - MIN(car->_accelCmd, (slipspeed - myc->TCL_SLIP)/myc->TCL_RANGE);
			}
		}
	}


	/* check if we are stuck, try to get unstuck */
	tdble bx = myc->getDir()->x, by = myc->getDir()->y;
	tdble cx = myc->currentseg->getMiddle()->x - car->_pos_X, cy = myc->currentseg->getMiddle()->y - car->_pos_Y;
	tdble parallel = (cx*bx + cy*by) / (sqrt(cx*cx + cy*cy)*sqrt(bx*bx + by*by));

	if ((myc->getSpeed() < myc->TURNSPEED) && (parallel < cos(90.0*PI/180.0))  && (mpf->dist2D(myc->getCurrentPos(), mpf->getPathSeg(myc->getCurrentSegId())->getLoc()) > myc->TURNTOL)) {
		myc->turnaround += situation->deltaTime;
	} else myc->turnaround = 0.0;
	if ((myc->turnaround >= waitToTurn) || (myc->tr_mode >= 1)) {
		if (myc->tr_mode == 0) {
			myc->tr_mode = 1;
		}
        if ((car->_gearCmd > -1) && (myc->tr_mode < 2)) {
			car->_accelCmd = 0.0;
			if (myc->tr_mode == 1) {
				car->_gearCmd--;
			}
			car->_brakeCmd = 1.0;
		} else {
			myc->tr_mode = 2;
			if (parallel < cos(90.0*PI/180.0) && (mpf->dist2D(myc->getCurrentPos(), mpf->getPathSeg(myc->getCurrentSegId())->getLoc()) > myc->TURNTOL)) {
				angle = queryAngleToTrack(car);
				car->_steerCmd = ( -angle > 0.0) ? 1.0 : -1.0;
				car->_brakeCmd = 0.0;

				if (myc->accel < 1.0) {
					myc->accel += myc->ACCELINC;
				}
				car->_accelCmd = myc->accel;
				tdble slipspeed = myc->querySlipSpeed(car);
				if (slipspeed < -myc->TCL_SLIP) {
					car->_accelCmd = car->_accelCmd - MIN(car->_accelCmd, (myc->TCL_SLIP - slipspeed)/myc->TCL_RANGE);
				}
			} else {
				if (myc->getSpeed() < 1.0) {
					myc->turnaround = 0;
					myc->tr_mode = 0;
					myc->loadBehaviour(myc->START);
					myc->startmode = true;
					myc->trtime = 0.0;
				}
				car->_brakeCmd = 1.0;
				car->_steerCmd = 0.0;
				car->_accelCmd = 0.0;
			}
		}
	}

	if (myc->tr_mode == 0) car->_steerCmd = steer;


	timeSinceLastUpdate[index - 1] += situation->deltaTime;
	
	//Only update once per second
	if(timeSinceLastUpdate[index - 1] >= 0.1)
	{
		/* steer to next target point */
		float targetAngleOut = atan2(myc->destpathseg->getLoc()->y - car->_pos_Y, myc->destpathseg->getLoc()->x - car->_pos_X);
		targetAngleOut -= car->_yaw;
		NORM_PI_PI(targetAngleOut);

		timeSinceLastUpdate[index - 1] = 0.0;
		sensors[index - 1]->sensors_update();

		//Write training data
		outputFiles[index - 1]<<"DATA"<<std::endl;

		//INPUT
		outputFiles[index - 1]<<"speed "<<myc->getSpeed()<<std::endl;
		outputFiles[index - 1]<<"angle "<<myc->getDeltaPitch()<<std::endl;
		outputFiles[index - 1]<<"targetAngle "<<targetAngleOut<<std::endl;

		//Distance sensors
		outputFiles[index - 1]<<"distR "<<sensors[index - 1]->getSensorOut(0)<<std::endl;
		outputFiles[index - 1]<<"distFR "<<sensors[index - 1]->getSensorOut(1)<<std::endl;
		outputFiles[index - 1]<<"distFFR "<<sensors[index - 1]->getSensorOut(2)<<std::endl;
		outputFiles[index - 1]<<"distF "<<sensors[index - 1]->getSensorOut(3)<<std::endl;
		outputFiles[index - 1]<<"distFFL "<<sensors[index - 1]->getSensorOut(4)<<std::endl;
		outputFiles[index - 1]<<"distFL "<<sensors[index - 1]->getSensorOut(5)<<std::endl;
		outputFiles[index - 1]<<"distL "<<sensors[index - 1]->getSensorOut(6)<<std::endl;

		//OUTPUT
		outputFiles[index - 1]<<"steer "<<car->ctrl.steer<<std::endl;
		outputFiles[index - 1]<<"accel "<<car->ctrl.accelCmd<<std::endl;
		outputFiles[index - 1]<<"brake "<<car->ctrl.brakeCmd<<std::endl;
		outputFiles[index - 1]<<"gear "<<car->ctrl.gear<<std::endl;
		outputFiles[index - 1]<<"clutch "<<car->ctrl.clutchCmd<<std::endl;

		//Write training data to console
		printf_s("-----------------------------\n");
		printf_s("Speed: %f\n", myc->getSpeed());
		printf_s("Steering: %f\n", car->ctrl.steer);
		printf_s("Acceleration: %f\n", car->ctrl.accelCmd);
		printf_s("Brake: %f\n", car->ctrl.brakeCmd);
		printf_s("Gear: %f\n", car->ctrl.gear);
		printf_s("Clutch: %f\n", car->ctrl.clutchCmd);
		printf_s("Angle: %f\n", myc->getDeltaPitch());
		printf_s("Target Angle: %f\n\n", targetAngleOut);

		printf_s("distR %f\n", sensors[index - 1]->getSensorOut(0));
		printf_s("distFR %f\n", sensors[index - 1]->getSensorOut(1));
		printf_s("distFFR %f\n", sensors[index - 1]->getSensorOut(2));
		printf_s("distF %f\n", sensors[index - 1]->getSensorOut(3));
		printf_s("distFFL %f\n", sensors[index - 1]->getSensorOut(4));
		printf_s("distFL %f\n", sensors[index - 1]->getSensorOut(5));
		printf_s("distL %f\n", sensors[index - 1]->getSensorOut(6));
	}
}
Esempio n. 6
0
// SET METHODS //
void Card::SetRank(int rank)
{
    // Set m_iFaceValue based upon "rank", and RANK as well. (A == 1 ... K == 13)
    switch (rank)
    {
    case 1:
        m_iFaceValue = rank;
        m_eRank = RANK::ACE;
        break;
    case 2:
        m_iFaceValue = rank;
        m_eRank = RANK::TWO;
        break;
    case 3:
        m_iFaceValue = rank;
        m_eRank = RANK::THREE;
        break;
    case 4:
        m_iFaceValue = rank;
        m_eRank = RANK::FOUR;
        break;
    case 5:
        m_iFaceValue = rank;
        m_eRank = RANK::FIVE;
        break;
    case 6:
        m_iFaceValue = rank;
        m_eRank = RANK::SIX;
        break;
    case 7:
        m_iFaceValue = rank;
        m_eRank = RANK::SEVEN;
        break;
    case 8:
        m_iFaceValue = rank;
        m_eRank = RANK::EIGHT;
        break;
    case 9:
        m_iFaceValue = rank;
        m_eRank = RANK::NINE;
        break;
    case 10:
        m_iFaceValue = rank;
        m_eRank = RANK::TEN;
        break;
    case 11:
        m_iFaceValue = rank;
        m_eRank = RANK::JACK;
        break;
    case 12:
        m_iFaceValue = rank;
        m_eRank = RANK::QUEEN;
        break;
    case 13:
        m_iFaceValue = rank;
        m_eRank = RANK::KING;
        break;
    default:
        m_iFaceValue = 1;
        m_eRank = RANK::ACE;
        // Throw a message here stating we did not get the appropriate card set up correctly
        printf_s("Card's RANK was not set correctly, rank VALUE: %d", rank);
        break;
    };
}
Esempio n. 7
0
int GameInterface::MenuSelect(int menuSize, int gotoX, int gotoY, int currentY, GameStatus gameStatus)
{
	int menuSelector = 0;
	bool okToStart = false;
	int sumShips;
	while (true)
	{
		int keyinput;
		keyinput = _getch();
		if (keyinput == -32)
		{
			keyinput = _getch();
		}
		if (keyinput == KEY_DOWN)
		{
			if (gameStatus == SELECT_PLAYER || gameStatus == SET_SHIP)
			{
				if (menuSelector >= 0 && menuSelector < menuSize - 1)
				{
					SetCursorPosition(gotoX, currentY);
					printf_s("  ");
					currentY += 3;
					menuSelector += 1;
					SetCursorPosition(gotoX, currentY);
					printf_s("¢º");
				}
			}
			else if (gameStatus == SELECT_MAP_SHIP)
			{
				if (menuSelector >= 0 && menuSelector < menuSize - 2)
				{
					SetCursorPosition(gotoX, currentY);
					printf_s("  ");
					currentY += 3;
					menuSelector += 1;
					SetCursorPosition(gotoX, currentY);
					printf_s("¢º");
				}
				else if (menuSelector == menuSize - 2)
				{
					sumShips = GetSumShip();
					SetCursorPosition(gotoX, currentY);
					printf_s("  ");
					currentY += 3;
					menuSelector += 1;
					if (sumShips == 0)
					{
						okToStart = false;
						SetColor(BLACK, DARK_RED);
						SetCursorPosition(gotoX + 18, gotoY + 20);
						printf_s("                   \n");
						SetCursorPosition(gotoX + 18, gotoY + 21);
						printf_s("      No Ship      \n");
						SetCursorPosition(gotoX + 18, gotoY + 22);
						printf_s("                   ");
					}
					else if (CheckEnoughSize() == false)
					{
						okToStart = false;
						SetColor(BLACK, DARK_RED);
						SetCursorPosition(gotoX + 18, gotoY + 20);
						printf_s("                   \n");
						SetCursorPosition(gotoX + 18, gotoY + 21);
						printf_s("   Too Many Ships  \n");
						SetCursorPosition(gotoX + 18, gotoY + 22);
						printf_s("                   ");
					}
					else
					{
						okToStart = true;
						SetColor(BLACK, GREEN);
						SetCursorPosition(gotoX + 18, gotoY + 20);
						printf_s("                   \n");
						SetCursorPosition(gotoX + 18, gotoY + 21);
						printf_s("      N E X T      \n");
						SetCursorPosition(gotoX + 18, gotoY + 22);
						printf_s("                   ");
					}
				}
			}
		}
		else if (keyinput == KEY_UP)
		{
			if (gameStatus == SELECT_PLAYER || gameStatus == SET_SHIP)
			{
				if (menuSelector >= 1 && menuSelector < menuSize)
				{
					SetCursorPosition(gotoX, currentY);
					printf_s("  ");
					currentY -= 3;
					menuSelector -= 1;
					SetCursorPosition(gotoX, currentY);
					printf_s("¢º");
				}
			}
			else if (gameStatus == SELECT_MAP_SHIP)
			{
				if (menuSelector >= 1 && menuSelector < menuSize - 1)
				{
					SetCursorPosition(gotoX, currentY);
					printf_s("  ");
					currentY -= 3;
					menuSelector -= 1;
					SetCursorPosition(gotoX, currentY);
					printf_s("¢º");
				}
				else if (menuSelector == menuSize - 1)
				{
					currentY -= 3;
					menuSelector -= 1;
					SetColor(BLACK, WHITE);
					SetCursorPosition(gotoX + 18, gotoY + 20);
					printf_s("                   \n");
					SetCursorPosition(gotoX + 18, gotoY + 21);
					printf_s("      N E X T      \n");
					SetCursorPosition(gotoX + 18, gotoY + 22);
					printf_s("                   ");
					SetColor(WHITE, BLACK);
					SetCursorPosition(gotoX, currentY);
					printf_s("¢º");
				}
			}
		}
		else if (keyinput == KEY_LEFT)
		{
			if (gameStatus == SELECT_MAP_SHIP)
			{
				if (menuSelector == 0)
				{
					if (m_MapSize > 5)
					{
						m_MapSize -= 1;
						SetCursorPosition(gotoX + 40, currentY);
						printf_s("¢¸ %d*%d ¢º", m_MapSize, m_MapSize);
					}
				}
				else if (menuSelector >= 1 && menuSelector <= menuSize - 2)
				{
					if (m_NumShip[menuSelector - 1] > 0)
					{
						m_NumShip[menuSelector - 1] -= 1;
						SetCursorPosition(gotoX + 40, currentY);
						printf_s("¢¸  %d  ¢º", m_NumShip[menuSelector - 1]);
					}
				}
			}
			if (gameStatus == WIN || gameStatus == LOSE)
			{
				if (menuSelector == 1)
				{
					menuSelector--;
					SetColor(BLACK, GREEN);
					SetCursorPosition(gotoX, gotoY);
					printf_s("                \n");
					SetCursorPosition(gotoX, gotoY + 1);
					printf_s("    To Title    \n");
					SetCursorPosition(gotoX, gotoY + 2);
					printf_s("  (New Setting) \n");
					SetCursorPosition(gotoX, gotoY + 3);
					printf_s("                ");
					SetColor(BLACK, WHITE);
					SetCursorPosition(gotoX + 20, gotoY);
					printf_s("                \n");
					SetCursorPosition(gotoX + 20, gotoY + 1);
					printf_s("   Play Again   \n");
					SetCursorPosition(gotoX + 20, gotoY + 2);
					printf_s(" (Same Setting) \n");
					SetCursorPosition(gotoX + 20, gotoY + 3);
					printf_s("                ");
					SetColor(WHITE, BLACK);
				}
				else if (menuSelector == 2)
				{
					menuSelector--;
					SetColor(BLACK, GREEN);
					SetCursorPosition(gotoX + 20, gotoY);
					printf_s("                \n");
					SetCursorPosition(gotoX + 20, gotoY + 1);
					printf_s("   Play Again   \n");
					SetCursorPosition(gotoX + 20, gotoY + 2);
					printf_s(" (Same Setting) \n");
					SetCursorPosition(gotoX + 20, gotoY + 3);
					printf_s("                ");
					SetColor(BLACK, WHITE);
					SetCursorPosition(gotoX + 40, gotoY);
					printf_s("                \n");
					SetCursorPosition(gotoX + 40, gotoY + 1);
					printf_s("      Quit      \n");
					SetCursorPosition(gotoX + 40, gotoY + 2);
					printf_s("      Game      \n");
					SetCursorPosition(gotoX + 40, gotoY + 3);
					printf_s("                ");
					SetColor(WHITE, BLACK);
				}
			}
		}
		else if (keyinput == KEY_RIGHT)
		{
			if (gameStatus == SELECT_MAP_SHIP)
			{
				if (menuSelector == 0)
				{
					if (m_MapSize < 9)
					{
						m_MapSize += 1;
						SetCursorPosition(gotoX + 40, currentY);
						printf_s("¢¸ %d*%d ¢º", m_MapSize, m_MapSize);
					}
				}
				if (menuSelector >= 1 && menuSelector <= menuSize - 2)
				{
					if (m_NumShip[menuSelector - 1] < 3)
					{
						m_NumShip[menuSelector - 1] += 1;
						SetCursorPosition(gotoX + 40, currentY);
						printf_s("¢¸  %d  ¢º", m_NumShip[menuSelector - 1]);
					}
				}
			}
			if (gameStatus == WIN || gameStatus == LOSE)
			{
				if (menuSelector == 0)
				{
					menuSelector++;
					SetColor(BLACK, WHITE);
					SetCursorPosition(gotoX, gotoY);
					printf_s("                \n");
					SetCursorPosition(gotoX, gotoY + 1);
					printf_s("    To Title    \n");
					SetCursorPosition(gotoX, gotoY + 2);
					printf_s("  (New Setting) \n");
					SetCursorPosition(gotoX, gotoY + 3);
					printf_s("                ");
					SetColor(BLACK, GREEN);
					SetCursorPosition(gotoX + 20, gotoY);
					printf_s("                \n");
					SetCursorPosition(gotoX + 20, gotoY + 1);
					printf_s("   Play Again   \n");
					SetCursorPosition(gotoX + 20, gotoY + 2);
					printf_s(" (Same Setting) \n");
					SetCursorPosition(gotoX + 20, gotoY + 3);
					printf_s("                ");
					SetColor(WHITE, BLACK);
				}
				else if (menuSelector == 1)
				{
					menuSelector++;
					SetColor(BLACK, WHITE);
					SetCursorPosition(gotoX + 20, gotoY);
					printf_s("                \n");
					SetCursorPosition(gotoX + 20, gotoY + 1);
					printf_s("   Play Again   \n");
					SetCursorPosition(gotoX + 20, gotoY + 2);
					printf_s(" (Same Setting) \n");
					SetCursorPosition(gotoX + 20, gotoY + 3);
					printf_s("                ");
					SetColor(BLACK, GREEN);
					SetCursorPosition(gotoX + 40, gotoY);
					printf_s("                \n");
					SetCursorPosition(gotoX + 40, gotoY + 1);
					printf_s("      Quit      \n");
					SetCursorPosition(gotoX + 40, gotoY + 2);
					printf_s("      Game      \n");
					SetCursorPosition(gotoX + 40, gotoY + 3);
					printf_s("                ");
					SetColor(WHITE, BLACK);
				}
			}
		}
		else if (keyinput == ENTER)
		{
			if (gameStatus == SELECT_PLAYER || gameStatus == SET_SHIP || gameStatus == WIN || gameStatus == LOSE)
				break;
			else if (gameStatus == SELECT_MAP_SHIP)
			{
				if (okToStart == true && CheckEnoughSize() == true && menuSelector == menuSize - 1)
				{
					SetColor(WHITE, BLACK);
					break;
				}
			}
		}
	}
	return menuSelector;
}
void TurnstileGate::Unlock()
{
	setState(unlocked);
	printf_s("Unlocked\n\n");
}
void TurnstileGate::Thankyou()
{
	printf_s("Thanks!\n\n");
}
Esempio n. 10
0
void CClientUdpSocket::Run()
{
	int nPacketCount = 1;
	m_blRun = true;
	SOCKET sckClient;
	SOCKET sckServer;

	//此部分为兼容Lua参数而设计
	//为了减少不必要的new和delete操作,所以参数在这里先声明好
	_ParamData* pSendParam1   = NULL;
	_ParamData* pSendParam2   = NULL;
	_ParamData* pSendParam3   = NULL;
	_ParamData* pSendParam4   = NULL;
	_ParamData* pSendParamOut = NULL;
	_ParamData* pRecvParam1   = NULL;
	_ParamData* pRecvParam2   = NULL;
	_ParamData* pRecvParam3   = NULL;
	_ParamData* pRecvParam4   = NULL;
	_ParamData* pRecvParamOut = NULL;

	int nLuaBufferMaxLength = m_pSocket_Info->m_pLogic->GetSendLength();

	if(m_pSocket_Info == NULL || m_pSocket_State_Info == NULL)
	{
		m_blRun = false;
		return;
	}

	//如果是高级模式
	if(m_pSocket_Info->m_blLuaAdvance == true)
	{
		m_objLuaFn.InitClass();

		bool blState = m_objLuaFn.LoadLuaFile(m_pSocket_Info->m_szLuaFileName);
		if(false == blState)
		{
			printf_s("[Main]Open Lua file error.\n");
			return;
		}

		//初始化所有要使用的Lua参数
		pSendParam1   = new _ParamData();
		pSendParam2   = new _ParamData();
		pSendParam3   = new _ParamData();
		pSendParam4   = new _ParamData();
		pSendParamOut = new _ParamData();
		pRecvParam1   = new _ParamData();
		pRecvParam2   = new _ParamData();
		pRecvParam3   = new _ParamData();
		pRecvParam4   = new _ParamData();
		pRecvParamOut = new _ParamData(); 

	}

	//看看是否是长连接,如果是长连接,则只处理一次。
	bool blIsConnect = false;

	//socket创建的准备工作
	struct sockaddr_in svrsockaddr;

	memset(&svrsockaddr, 0, sizeof(SOCKADDR_IN));
	svrsockaddr.sin_family = AF_INET;
	svrsockaddr.sin_port   = htons(m_pSocket_Info->m_nPort);
	svrsockaddr.sin_addr.S_un.S_addr = inet_addr(m_pSocket_Info->m_szSerevrIP);

	sckClient = socket(AF_INET, SOCK_DGRAM, 0);

	DWORD TimeOut = (DWORD)m_pSocket_Info->m_nRecvTimeout;
	::setsockopt(sckClient, SOL_SOCKET, SO_RCVTIMEO, (char *)&TimeOut, sizeof(TimeOut));

	//设置接收监听端口
	sckServer = socket(AF_INET, SOCK_DGRAM, 0);

	struct sockaddr_in clientsockaddr;
	memset(&clientsockaddr, 0, sizeof(SOCKADDR_IN));
	clientsockaddr.sin_family = AF_INET;
	clientsockaddr.sin_port   = htons(m_pSocket_Info->m_nUdpClientPort);
	clientsockaddr.sin_addr.S_un.S_addr = inet_addr(m_pSocket_Info->m_szSerevrIP);

	bind(sckServer, (SOCKADDR *) &clientsockaddr, sizeof(clientsockaddr));

	//发送次数
	int nSendIndex = 0;

	while(m_blRun)
	{
		unsigned int tBegin = (unsigned int)GetTickCount();
		if(m_pSocket_Info->m_nSendCount != 0 && m_pSocket_State_Info->m_nSuccessSend >= m_pSocket_Info->m_nSendCount)
		{
			//发送指定数目的数据包完成
			break;
		}

		//查看是否开启高级模式
		if(m_pSocket_Info->m_blLuaAdvance == true)
		{
			//重置缓冲最大长度
			m_pSocket_Info->m_pLogic->SetMaxSendLength(nLuaBufferMaxLength);

			//开始调用Lua脚本,去组织数据块
			CParamGroup objIn;
			CParamGroup objOut;

			objIn.NeedRetrieve(false);
			objOut.NeedRetrieve(false);

			int nLuaSendLen = m_pSocket_Info->m_pLogic->GetSendLength();
			pSendParam1->SetParam((char* )m_pSocket_Info->m_pLogic->GetSendData(), "void", sizeof(int));
			pSendParam2->SetParam((char* )&nLuaSendLen, "int", sizeof(int));
			pSendParam3->SetParam((char* )&m_nThreadID, "int", sizeof(int));
			pSendParam4->SetParam((char* )&nSendIndex, "int", sizeof(int));

			int nSendLength = 0;
			pSendParamOut->SetParam((char* )&nSendLength, "int", sizeof(int));

			objIn.Push(pSendParam1);
			objIn.Push(pSendParam2);
			objIn.Push(pSendParam3);
			objIn.Push(pSendParam4);
			objOut.Push(pSendParamOut);

			m_objLuaFn.CallFileFn("PassTcp_CreateSendData", objIn, objOut);

			int* pLength = (int* )pSendParamOut->GetParam();
			m_pSocket_Info->m_pLogic->SetMaxSendLength((int)(*pLength));
		}


		if(blIsConnect == false)
		{
			DWORD dwSleepTime = (DWORD)m_pSocket_Info->m_nDelaySecond;
			if(m_pSocket_Info->m_blIsRadomaDelay == true)
			{
				//如果是随机的,则从1-1000之间随机一个时间
				dwSleepTime = (DWORD)RandomValue(1, 1000);
			}

			//挂起指定的时间
			Sleep(dwSleepTime);

			m_pSocket_State_Info->m_nSuccessConnect++;
			m_pSocket_State_Info->m_nCurrectSocket = 1;
			blIsConnect = true;
		}

		if(blIsConnect == true)
		{
			//发送数据
			char szSendBuffData[MAX_BUFF_1024 * 100] = {'\0'};
			char szRecvBuffData[MAX_BUFF_1024 * 100] = {'\0'};

			char* pSendData   = NULL;
			int nSendLen      = 0;
			int nTotalRecvLen = 0;
			//如果数据为随机数据包
			if(m_pSocket_Info->m_blIsSendCount == true)
			{
				int nSendCount = RandomValue(1, 10);

				//这里追加一个逻辑,记录当前发包的总数是否匹配,随机数不能超过当前发包总数
				if(m_pSocket_Info->m_nSendCount != 0 && nSendCount + m_pSocket_State_Info->m_nSuccessSend > m_pSocket_Info->m_nSendCount)
				{
					nSendCount = m_pSocket_Info->m_nSendCount - m_pSocket_State_Info->m_nSuccessSend;
				}

				char* pData = m_pSocket_Info->m_pLogic->GetSendData(m_pSocket_Info->m_nThreadID, nSendIndex, nSendLen);
				for(int i = 0; i < nSendCount; i++)
				{
					MEMCOPY_SAFE(&szSendBuffData[i * nSendLen], 
						pData, 
						nSendLen);
				}
				nPacketCount = nSendCount;

				//发送数据
				pSendData     = (char* )szSendBuffData;
				nSendLen      = m_pSocket_Info->m_pLogic->GetSendLength() * nSendCount;
				nTotalRecvLen = m_pSocket_Info->m_pLogic->GetSendLength() * nSendCount;
			}
			else
			{
				//发送数据
				pSendData     = (char* )m_pSocket_Info->m_pLogic->GetSendData(m_pSocket_Info->m_nThreadID, nSendIndex, nSendLen);
				nTotalRecvLen = m_pSocket_Info->m_pLogic->GetRecvLength();
			}

			//记录应收字节总数
			int nRecvAllSize = nTotalRecvLen;

			//如果需要记录日志,则将数据计入日志
			if(m_pSocket_Info->m_blIsWriteFile == true)
			{
				WriteFile_SendBuff(pSendData, nSendLen);
			}

			int nTotalSendLen = nSendLen;
			int nBeginSend    = 0;
			int nCurrSendLen  = 0;
			bool blSendFlag   = false;
			int nBeginRecv    = 0;
			int nCurrRecvLen  = 0;
			bool blRecvFlag   = false;
			while(true)
			{
				//UDP发送
				int nssssSize = sizeof(SOCKADDR);
				nCurrSendLen = sendto(sckClient, pSendData + nBeginSend, nTotalSendLen, 0, (sockaddr* )&svrsockaddr, sizeof(SOCKADDR));
				if(nCurrSendLen <= 0)
				{
					DWORD dwError = GetLastError();
					WriteFile_Error("sendto error", (int)dwError);
					m_pSocket_State_Info->m_nFailSend += nPacketCount;
					m_pSocket_State_Info->m_nCurrectSocket = 0;
					blIsConnect = false;
					break;
				}
				else
				{
					nTotalSendLen -= nCurrSendLen;
					if(nTotalSendLen == 0)
					{
						//发送完成
						m_pSocket_State_Info->m_nSuccessSend += nPacketCount;
						blSendFlag = true;
						break;
					}
					else
					{
						nBeginSend += nCurrSendLen;
					}
				}
			}

			//接收数据
			if(blSendFlag == true && m_pSocket_Info->m_blIsRecv == true)
			{
				while(true)
				{
					//如果发送成功了,则处理接收数据
					int nClientAddrSize = sizeof(SOCKADDR_IN);

					//socket创建的准备工作
					struct sockaddr_in clientsockaddr1;
					/*
					struct sockaddr_in clientsockaddr;

					memset(&clientsockaddr, 0, sizeof(SOCKADDR_IN));
					clientsockaddr.sin_family = AF_INET;
					clientsockaddr.sin_port   = htons(20004);
					clientsockaddr.sin_addr.S_un.S_addr = inet_addr(m_pSocket_Info->m_szSerevrIP);
					*/

					nCurrRecvLen = recvfrom(sckServer, (char* )szRecvBuffData + nBeginRecv, nTotalRecvLen, 0, (sockaddr* )&clientsockaddr1, &nClientAddrSize);
					if(nCurrRecvLen <= 0)
					{
						DWORD dwError = GetLastError();
						WriteFile_Error("sendto error", (int)dwError);
						m_pSocket_State_Info->m_nFailRecv += nPacketCount;
						//closesocket(sckClient);
						m_pSocket_State_Info->m_nCurrectSocket = 0;
						blIsConnect = false;
						break;
					}
					else
					{
						//如果是高级模式,这里调用Lua接口方法
						if(m_pSocket_Info->m_blLuaAdvance == true)
						{
							m_pSocket_State_Info->m_nRecvByteCount += nCurrRecvLen;
							int nState = 0;

							CParamGroup objRecvIn;
							CParamGroup objRecvOut;

							objRecvIn.NeedRetrieve(false);
							objRecvOut.NeedRetrieve(false);

							pRecvParam1->SetParam((char* )szRecvBuffData, "void", sizeof(int));
							pRecvParam2->SetParam((char* )&nCurrRecvLen, "int", sizeof(int));
							pRecvParam3->SetParam((char* )&m_nThreadID, "int", sizeof(int));
							pRecvParam4->SetParam((char* )&nSendIndex, "int", sizeof(int));

							pRecvParamOut->SetParam((char* )&nState, "int", sizeof(int));

							objRecvIn.Push(pRecvParam1);
							objRecvIn.Push(pRecvParam2);
							objRecvIn.Push(pRecvParam3);
							objRecvIn.Push(pRecvParam4);
							objRecvOut.Push(pRecvParamOut);

							//调用接收函数
							m_objLuaFn.CallFileFn("PassTcp_GetRecvData", objRecvIn, objRecvOut);

							int* pReturn = (int* )pRecvParamOut->GetParam();
							nState = (int)(*pReturn);

							objRecvIn.Close(false);
							objRecvOut.Close(false);

							//判断脚本返回值
							if(nState == 0)
							{
								//接收验证成功
								m_pSocket_State_Info->m_nSuccessRecv += nPacketCount;
								blRecvFlag = true;

								//如果需要记录日志,则将数据计入日志
								if(m_pSocket_Info->m_blIsWriteFile == true)
								{
									WriteFile_RecvBuff(szRecvBuffData, nRecvAllSize);
								}

								//计算最小时间和最大时间
								int tTime = (int)((unsigned int)GetTickCount() - tBegin);
								if(tTime > 0 && m_pSocket_State_Info->m_nMinRecvTime == 0)
								{
									m_pSocket_State_Info->m_nMinRecvTime = tTime;
								}
								else if(tTime < m_pSocket_State_Info->m_nMinRecvTime)
								{
									m_pSocket_State_Info->m_nMinRecvTime = tTime;
								}

								if(tTime > 0 && m_pSocket_State_Info->m_nMaxRecvTime == 0)
								{
									m_pSocket_State_Info->m_nMaxRecvTime = tTime;
								}
								else if(tTime > m_pSocket_State_Info->m_nMaxRecvTime)
								{
									m_pSocket_State_Info->m_nMaxRecvTime = tTime;
								}

								break;
							}
							else if(nState == 1)
							{
								//继续接收
								nBeginRecv += nCurrRecvLen;
							}
							else
							{
								//接收包验证失败
								m_pSocket_State_Info->m_nFailRecv += nPacketCount;
								blRecvFlag = true;

								//如果需要记录日志,则将数据计入日志
								if(m_pSocket_Info->m_blIsWriteFile == true)
								{
									WriteFile_RecvBuff(szRecvBuffData, nRecvAllSize);
								}

								break;
							}
						}
						else
						{
							//如果不是高级模式,则采用配置的判定准则
							m_pSocket_State_Info->m_nRecvByteCount += nCurrRecvLen;
							nTotalRecvLen -= nCurrRecvLen;

							EM_DATA_RETURN_STATE emState = m_pSocket_Info->m_pLogic->GetRecvData(m_nThreadID, nSendLen, szRecvBuffData, nCurrRecvLen);
							if(emState == DATA_RETURN_STATE_SUCCESS)
							{
								//接收完成
								m_pSocket_State_Info->m_nSuccessRecv += nPacketCount;
								blRecvFlag = true;

								//如果需要记录日志,则将数据计入日志
								if(m_pSocket_Info->m_blIsWriteFile == true)
								{
									WriteFile_RecvBuff(szRecvBuffData, nRecvAllSize);
								}

								//计算最小时间和最大时间
								int tTime = (int)((unsigned int)GetTickCount() - tBegin);
								if(tTime > 0 && m_pSocket_State_Info->m_nMinRecvTime == 0)
								{
									m_pSocket_State_Info->m_nMinRecvTime = tTime;
								}
								else if(tTime < m_pSocket_State_Info->m_nMinRecvTime)
								{
									m_pSocket_State_Info->m_nMinRecvTime = tTime;
								}

								if(tTime > 0 && m_pSocket_State_Info->m_nMaxRecvTime == 0)
								{
									m_pSocket_State_Info->m_nMaxRecvTime = tTime;
								}
								else if(tTime > m_pSocket_State_Info->m_nMaxRecvTime)
								{
									m_pSocket_State_Info->m_nMaxRecvTime = tTime;
								}

								break;
							}
							else
							{
								nBeginRecv += nCurrRecvLen;
							}
						}
					}
				}
			}

			//如果有数据包间隔,则sleep指定的时间
			if(m_pSocket_Info->m_nPacketTimewait > 0)
			{
				DWORD dwSleepTime = (DWORD)m_pSocket_Info->m_nPacketTimewait;
				Sleep(dwSleepTime);
			}

			//如果是长连接,则不关闭连接
			if(m_pSocket_Info->m_blIsAlwayConnect == false)
			{
				//closesocket(sckClient);
				m_pSocket_State_Info->m_nCurrectSocket = 0;
				blIsConnect = false;
			}
		}

		//如果只发送一次,在这里退出
		if(m_pSocket_Info->m_blIsSendOne == true)
		{
			m_blRun = false;
		}
	}

	//如果连接没断,则断开
	closesocket(sckClient);
	closesocket(sckServer);
	m_pSocket_State_Info->m_nCurrectSocket = 0;
	blIsConnect = false;

	//回收所有的Lua申请的内存
	delete pSendParam1;
	delete pSendParam2;
	delete pSendParam3;
	delete pSendParam4;
	delete pSendParamOut;
	delete pRecvParam1;
	delete pRecvParam2;
	delete pRecvParam3;
	delete pRecvParam4;
	delete pRecvParamOut;
}
Esempio n. 11
0
void TurnstileGate::Lock()
{
	setState(locked);
	printf_s("Locked\n\n");
}
Esempio n. 12
0
void NPC::Dead()
{
	printf_s("NPC is Dead!! \n");
}
Esempio n. 13
0
// 初始化语音识别
HRESULT ThisApp::init_speech_recognizer(){
    HRESULT hr = S_OK;
    // 创建语音输入流
    if (SUCCEEDED(hr)){
        hr = CoCreateInstance(CLSID_SpStream, nullptr, CLSCTX_INPROC_SERVER, __uuidof(ISpStream), (void**)&m_pSpeechStream);;
    }
    // 与我们的Kinect语音输入相连接
    if (SUCCEEDED(hr)){
        WAVEFORMATEX wft = {
            WAVE_FORMAT_PCM, // PCM编码
            1, // 单声道
            16000,  // 采样率为16KHz
            32000, // 每分钟数据流 = 采样率 * 对齐
            2, // 对齐 : 单声道 * 样本深度 = 2byte
            16, // 样本深度 16BIT
            0 // 额外数据
        };
        // 设置状态
        hr = m_pSpeechStream->SetBaseStream(m_p16BitPCMAudioStream, SPDFID_WaveFormatEx, &wft);
    }
    // 创建语音识别对象
    if (SUCCEEDED(hr)){
        ISpObjectToken *pEngineToken = nullptr;
        // 创建语言识别器
        hr = CoCreateInstance(CLSID_SpInprocRecognizer, nullptr, CLSCTX_INPROC_SERVER, __uuidof(ISpRecognizer), (void**)&m_pSpeechRecognizer);
        if (SUCCEEDED(hr)) {
            // 连接我们创建的语音输入流对象
            m_pSpeechRecognizer->SetInput(m_pSpeechStream, TRUE);
            // 创建待识别语言 这里选择大陆汉语(zh-cn) 
            // 目前没有Kinect的汉语语音识别包 有的话可以设置"language=804;Kinect=Ture"
            hr = SpFindBestToken(SPCAT_RECOGNIZERS, L"Language=804", nullptr, &pEngineToken);
            if (SUCCEEDED(hr)) {
                // 设置待识别语言
                m_pSpeechRecognizer->SetRecognizer(pEngineToken);
                // 创建语音识别上下文
                hr = m_pSpeechRecognizer->CreateRecoContext(&m_pSpeechContext);
                // 适应性 ON! 防止因长时间的处理而导致识别能力的退化
                if (SUCCEEDED(hr))  {
                    hr = m_pSpeechRecognizer->SetPropertyNum(L"AdaptationOn", 0);
                }
            }
        }
        SafeRelease(pEngineToken);
    }
    // 创建语法
    if (SUCCEEDED(hr)){
        hr = m_pSpeechContext->CreateGrammar(1, &m_pSpeechGrammar);
    }
    // 加载静态SRGS语法文件
    if (SUCCEEDED(hr)){
        hr = m_pSpeechGrammar->LoadCmdFromFile(s_GrammarFileName, SPLO_STATIC);
    }
    // 激活语法规则
    if (SUCCEEDED(hr)){
        hr = m_pSpeechGrammar->SetRuleState(nullptr, nullptr, SPRS_ACTIVE);
    }
    // 设置识别器一直读取数据
    if (SUCCEEDED(hr)){
        hr = m_pSpeechRecognizer->SetRecoState(SPRST_ACTIVE_ALWAYS);
    }
    // 设置对识别事件感兴趣
    if (SUCCEEDED(hr)){
        hr = m_pSpeechContext->SetInterest(SPFEI(SPEI_RECOGNITION), SPFEI(SPEI_RECOGNITION));
    }
    // 保证语音识别处于激活状态
    if (SUCCEEDED(hr)){
        hr = m_pSpeechContext->Resume(0);
    }
    // 获取识别事件
    if (SUCCEEDED(hr)){
        m_p16BitPCMAudioStream->SetSpeechState(TRUE);
        m_hSpeechEvent = m_pSpeechContext->GetNotifyEventHandle();
		printf_s("init_speech_recognizer succeeded\n");
    }
#ifdef _DEBUG
    else
        printf_s("init_speech_recognizer failed\n");
#endif
    return hr;
}
Esempio n. 14
0
void NetworkManager::GameStart()
{
	PacketType type;
	ErrorType error;
	bool gameOver = false;

	Position attackpos;
	Position hitpos;

	while (!gameOver)
	{
		error = network.GetPacketType(&type);

		switch (type)
		{
		case PKT_SC_ERROR:
			if (error == ET_OPPOSITION_DISCONNECTED)
				puts("상대방의 접속이 끊어졌습니다.");
			else
				puts("알 수 없는 에러입니다.");
			return;
			break;
		case PKT_SC_MY_TURN:
		{
			while (true)
			{
				if (m_player->GetType() == Ai)
				{
					AI* ai = (AI*)m_player;
					attackpos = ai->AttackShip();
				}
				else
				{
					attackpos = m_player->AttackShip();
				}

				printf_s("%c%c\n", attackpos.x, attackpos.y);

				error = network.SubmitAttack(PositionToCoord(attackpos));

				if (error == ET_INVALID_ATTACK)
					puts("유효하지 않은 공격 위치입니다.");
				else
					break;
			}
		}
			break;
		case PKT_SC_ATTACK_RESULT:
		{
			Network::AttackResultData result;
			result = network.GetAttackResult();
			if (result.isMine)
			{
				puts("공격 결과:");

				printf_s("%c%c ", result.pos.mX + 'a', result.pos.mY + '1');

				switch (result.attackResult)
				{
				case AR_DESTROY_AIRCRAFT:
					printf_s("Result: DESTROY_AIRCRAFT\n");
					break;
				case AR_DESTROY_BATTLESHIP:
					printf_s("Result: DESTROY_BATTLESHIP\n");
					break;
				case AR_DESTROY_CRUISER:
					printf_s("Result: DESTROY_CRUISER\n");
					break;
				case AR_DESTROY_DESTROYER:
					printf_s("Result: DESTROY_DESTROYER\n");
					break;
				case AR_HIT:
					printf_s("Result: HIT");
					break;
				case AR_MISS:
					printf_s("Result: MISS");
					break;

				}


				if (m_player->GetType() == Ai)
				{
					AI* ai = (AI*)m_player;
					ai->TakeAttackResult(attackpos, result.attackResult);
				}
				else
				{
					m_player->TakeAttackResult(attackpos, result.attackResult);
				}

			}
			else
			{
				puts("피격 결과:");
				hitpos.x = result.pos.mX + 'a';
				hitpos.y = result.pos.mY + '1';

				m_player->HitCheck(hitpos);
				printf_s("%c%c", hitpos.x, hitpos.y);
			}
		}
			break;
		case PKT_SC_GAME_OVER:
		{
			Network::GameResultData gameresult;
			gameresult = network.GetGameResult();

			if (gameresult.isWinner)
				puts("승리!!!");
			else
				puts("패배...");
			printf_s("턴 수: %d\n", gameresult.turns);
			gameOver = true;
		}
			break;
		default:
			throw Network::UNEXPECTED_PACKET;
			break;
		}

	}


}
Esempio n. 15
0
int main(int argc, char *argv[])
{
	Win32LoadOpenCv();
	
	CvMat *imageLeft = OpenCvImreadM("images/obstacles_0stereo.jpg", CV_LOAD_IMAGE_GRAYSCALE);
	CvMat *imageRight = OpenCvImreadM("images/obstacles_10stereo.jpg", CV_LOAD_IMAGE_GRAYSCALE);
	
	if((imageLeft == 0) || (imageRight == 0))
	{
		printf_s("One or more images failed to load \n");
		return -1;
	}
	
	CvMat *imageDisparity16S = OpenCvCreateMat(imageLeft->rows, imageLeft->cols,
		CV_16S); // CvMat{imageLeft->rows, CV_16S};
	CvMat *imageDisparity8U = OpenCvCreateMat(imageLeft->rows, imageLeft->cols,
		CV_8UC1); // CvMat(imageLeft->rows, CV_8UC1);
	
	int32 disparities = 112;
	CvStereoBMState *stereoBMState = OpenCvCreateStereoBMState(CV_STEREO_BM_BASIC,
		disparities);
	stereoBMState->SADWindowSize = 9;
	stereoBMState->preFilterSize = 5;
	stereoBMState->preFilterCap = 61;
	stereoBMState->minDisparity = -39;
	stereoBMState->textureThreshold = 507;
	stereoBMState->uniquenessRatio = 0;
	stereoBMState->speckleWindowSize = 0;
	stereoBMState->speckleRange = 8;
	stereoBMState->disp12MaxDiff = 1;
	
	for(int i = 1;
		i < 4;
		i = i + 2)
	{
		OpenCvSmooth(imageLeft, imageLeft, CV_BLUR, i, i, 3, 3);
	}
	for(int i = 1;
		i < 4;
		i = i + 2)
	{
		OpenCvSmooth(imageRight, imageRight, CV_BLUR, i, i, 3, 3);
	}
	
	OpenCvFindStereoCorrespondenceBM(imageLeft, imageRight,
			imageDisparity16S, stereoBMState);
		
	double minValue;
	double maxValue;
	OpenCvMinMaxLoc(imageDisparity16S, &minValue, &maxValue, 0, 0, 0);
	
	printf_s("Min disparity: %f - Max disparity: %f \n",
		minValue, maxValue);
		
	OpenCvConvertScale(imageDisparity16S, imageDisparity8U,
		255.0/(maxValue - minValue), 0);
		
	// OpenCvNamedWindow(g_WindowName, CV_WINDOW_AUTOSIZE);
	// OpenCvShowImage(g_WindowName, imageDisparity8U);
	
	OpenCvSaveImage("../matlab/disparityMap.bmp", imageDisparity8U, 0);
	
	OpenCvWaitKey(0);
	
	OpenCvReleaseStereoBMState(&stereoBMState);
	
	return 0;
}
Esempio n. 16
0
void TurnstileGate::Alarm()
{
	printf_s("Alarm!\n\n");
}
Esempio n. 17
0
int main() {
	TList *list = new TList();
	printf_s("list.First() = %s\n", list->First());
	printf_s("list.Pop() = %s\n", list->Pop());

	list->Push("Hola");
	printf_s("Pushed \"Hola\"!\n");
	list->Push("Holita");
	printf_s("Pushed \"Holita\"!\n");
	list->Push("Que tal?");
	printf_s("Pushed \"Que tal?\"!\n");

	printf_s("list.Next() = %s\n", list->Next());
	printf_s("list.Next() = %s\n", list->Next());
	printf_s("list.Next() = %s\n", list->Next());
	printf_s("list.Next() = %s\n", list->Next());

	printf_s("list.First() = %s\n", list->First());
	printf_s("list.Pop() = %s\n", list->Pop());
	printf_s("list.First() = %s\n", list->First());

	list->Push("Hola");

	list->Reset();
	printf_s("list reset!\n");

	printf_s("list.First() = %s\n", list->First());
	printf_s("list.Next() = %s\n", list->Next());

	//copy constructor
	list->Push("Hola");
	list->Push("que");

	TList *list2 = new TList(*list);

	printf_s("list2.First() = %s\n", list2->First());
	printf_s("list2.Next() = %s\n", list2->Next());

	list2->Push("tal?");
	printf_s("list2.Next() = %s\n", list2->Next());

	delete list2;

	list->Push("tal");
	list->Push("estas?");

	//TList GetReverseList(TList lstSrc)
	TList listRev = GetReverseList(*list);

	printf_s("listRev.First() = %s\n", listRev.First());
	printf_s("listRev.Next() = %s\n", listRev.Next());
	printf_s("listRev.Next() = %s\n", listRev.Next());
	printf_s("listRev.Next() = %s\n", listRev.Next());

	//TList * GetReverseList(TList &lstSrc, TList *listCopy)
	//this is the way to avoid returning an object in the Stack
	TList * listInv = new TList();

	GetReverseList(*list, listInv);
	printf_s("listInv.First() = %s\n", listInv->First());
	printf_s("listInv.Next() = %s\n", listInv->Next());
	printf_s("listInv.Next() = %s\n", listInv->Next());
	printf_s("listInv.Next() = %s\n", listInv->Next());

	delete list;
	delete listInv;

	getchar();
}
Esempio n. 18
0
void TurnstileGate::ResetAlarm()
{
	printf_s("Alarm reset\n\n");
}
int main(int argc, char* argv[])
{
	int infoMago = 0xFFA82000;
	int opcion = 0;
	unsigned int balas = 0;

	do {
		printf_s("MENU DEL PERSONAJE:\n");

		printf_s("Elija una de las siguientes opciones\n");
		printf_s("1. Mostrar número de balas\n");
		printf_s("2. Añadir balas\n");
		printf_s("3. Comprobar si tienes balas infinitas\n");
		printf_s("4. Activar las balas infinitas\n");
		printf_s("5. Salir\n\n");

		scanf_s("%i", &opcion);
		printf_s("\n");


		switch (opcion) {
		case 1:
			printf_s("Balas en el inventario: %d\n", balasInventario(infoMago));
			printf_s("\n");
			break;
		case 2:
			printf_s("Número de balas actual: %u\n", balasInventario(infoMago));
			printf_s("¿Cuántas balas quieres añadir?: ");
			scanf_s("%i", &balas);
			printf_s("\n");
			if (balas > 255) {
				printf_s("El máximo de balas que puedes llevar es 255\n");
			}
			printf_s("Balas en el inventario: %u\n", anadirBalas(infoMago, balas));
			printf_s("\n");
			break;
		case 3:
			if (comprobarBalasInfinitas(infoMago)) {
				printf_s("Tienes balas infinitas\n");
				printf_s("\n");
			}
			else {
				printf_s("No tienes balas infinitas\n");
				printf_s("\n");
			}
			break;
		case 4:
			if (activarBalasInfinitas(infoMago)) {
				printf_s("Ya tienes balas infinitas\n");
				printf_s("\n");
			}
			else {
				printf_s("No tienes balas infinitas\n");
				printf_s("\n");
			}
			break;
		case 5:
			break;
		}
	} while (opcion != 5);
}
Esempio n. 20
0
void TurnstileGate::Violation()
{
	setState(violation);
	printf_s("Violation!\n\n");
}
Esempio n. 21
0
void GameInterface::AttachInterface(GameStatus gameStatus)
{
	int gotoX;
	int gotoY;
	int currentY;
	int menuSelector = 0;
	switch (gameStatus)
	{
	case TITLE:
		gotoX = 0;
		gotoY = 10;
		while (!_kbhit())
		{
			Sleep(600);
			SetCursorPosition(gotoX, gotoY);
			printf_s("\t\t\t     PRESS ENTER KEY TO START      \t\t\t");
			Sleep(1000);
			SetCursorPosition(gotoX, gotoY);
			printf_s("                                                                            ");
		}
		getchar();
		break;
	case SELECT_PLAYER:
		gotoX = 22;
		gotoY = 9;
		currentY = gotoY + 6;
		SetColor(BLACK, WHITE);
		SetCursorPosition(gotoX, gotoY);
		printf_s("                  \n");
		SetCursorPosition(gotoX, gotoY + 1);
		printf_s("   PLAYER SELECT  \n");
		SetCursorPosition(gotoX, gotoY + 2);
		printf_s("                  ");
		SetColor(WHITE, BLACK);
		SetCursorPosition(gotoX + 7, gotoY + 6);
		printf_s("VS Friend");
		SetCursorPosition(gotoX + 7, gotoY + 9);
		printf_s("VS AI");
		SetCursorPosition(gotoX + 7, gotoY + 12);
		printf_s("VS Network");
		SetCursorPosition(gotoX - 1, currentY);
		printf_s("¢º");
		menuSelector = MenuSelect(3, gotoX, gotoY, currentY, gameStatus);
		if (menuSelector == 0)
		{
			m_GameType = PVP_PLAY;
		}
		else if (menuSelector == 1)
		{
			m_GameType = AI_PLAY;
		}
		else if (menuSelector == 2)
		{
			m_GameType = NET_PLAY;
		}
		break;
	case SELECT_MAP_SHIP:
		gotoX = 4;
		gotoY = 9;
		currentY = gotoY + 5;
		SetColor(BLACK, WHITE);
		SetCursorPosition(gotoX + 18, gotoY);
		printf_s("                  \n");
		SetCursorPosition(gotoX + 18, gotoY + 1);
		printf_s("    SHIP SELECT   \n");
		SetCursorPosition(gotoX + 18, gotoY + 2);
		printf_s("                  ");
		SetColor(WHITE, BLACK);
		SetCursorPosition(gotoX + 6, gotoY + 5);
		printf_s("Map size");
		SetCursorPosition(gotoX + 6, gotoY + 8);
		printf_s("Aircraft Carrier");
		SetCursorPosition(gotoX + 6, gotoY + 11);
		printf_s("Battleship");
		SetCursorPosition(gotoX + 6, gotoY + 14);
		printf_s("Cruiser");
		SetCursorPosition(gotoX + 6, gotoY + 17);
		printf_s("Destroyer");
		SetColor(BLACK, WHITE);
		SetCursorPosition(gotoX + 18, gotoY + 20);
		printf_s("                   \n");
		SetCursorPosition(gotoX + 18, gotoY + 21);
		printf_s("      N E X T      \n");
		SetCursorPosition(gotoX + 18, gotoY + 22);
		printf_s("                   ");
		SetColor(WHITE, BLACK);
		SetCursorPosition(gotoX + 40, gotoY + 5);
		printf_s("¢¸ %d*%d ¢º", m_MapSize, m_MapSize);
		SetCursorPosition(gotoX + 40, gotoY + 8);
		printf_s("¢¸  %d  ¢º", m_NumShip[0]);
		SetCursorPosition(gotoX + 40, gotoY + 11);
		printf_s("¢¸  %d  ¢º", m_NumShip[1]);
		SetCursorPosition(gotoX + 40, gotoY + 14);
		printf_s("¢¸  %d  ¢º", m_NumShip[2]);
		SetCursorPosition(gotoX + 40, gotoY + 17);
		printf_s("¢¸  %d  ¢º", m_NumShip[3]);
		SetCursorPosition(gotoX, currentY);
		printf_s("¢º");
		menuSelector = MenuSelect(6, gotoX, gotoY, currentY, gameStatus);
		break;
	case SET_SHIP:
		gotoX = (m_MapSize + 3) * 4 + 4;
		gotoY = 7;
		currentY = gotoY + 5;
		SetCursorPosition(gotoX + 6, gotoY + 5);
		printf_s("Manual Set");
		SetCursorPosition(gotoX + 6, gotoY + 8);
		printf_s("Random Set");
		SetCursorPosition(gotoX, currentY);
		printf_s("¢º");
		SetColor(BLACK, WHITE);
		SetCursorPosition(gotoX + 2, gotoY + 12);
		printf_s("                  \n");
		SetCursorPosition(gotoX + 2, gotoY + 13);
		printf_s("    Start Game    \n");
		SetCursorPosition(gotoX + 2, gotoY + 14);
		printf_s("                  \n");
		SetCursorPosition(gotoX + 2, gotoY + 17);
		printf_s("                  \n");
		SetCursorPosition(gotoX + 2, gotoY + 18);
		printf_s("       Reset      \n");
		SetCursorPosition(gotoX + 2, gotoY + 19);
		printf_s("                  ");
		SetColor(WHITE, BLACK);
		menuSelector = MenuSelect(2, gotoX, gotoY, currentY, gameStatus);
		if (menuSelector == 0)
		{
			m_ManualOrRandom = true;
		}
		else if (menuSelector == 1)
		{
			m_ManualOrRandom = false;
		}
		SetColor(WHITE, BLACK);
		break;
	case GAMEPLAY:
		break;
	case WIN:
		gotoX = 3;
		gotoY = 13;
		currentY = 0;
		SetColor(BLACK, GREEN);
		SetCursorPosition(gotoX, gotoY);
		printf_s("                \n");
		SetCursorPosition(gotoX, gotoY + 1);
		printf_s("    To Title    \n");
		SetCursorPosition(gotoX, gotoY + 2);
		printf_s("  (New Setting) \n");
		SetCursorPosition(gotoX, gotoY + 3);
		printf_s("                ");
		SetColor(BLACK, WHITE);
		SetCursorPosition(gotoX + 20, gotoY);
		printf_s("                \n");
		SetCursorPosition(gotoX + 20, gotoY + 1);
		printf_s("   Play Again   \n");
		SetCursorPosition(gotoX + 20, gotoY + 2);
		printf_s(" (Same Setting) \n");
		SetCursorPosition(gotoX + 20, gotoY + 3);
		printf_s("                ");
		SetCursorPosition(gotoX + 40, gotoY);
		printf_s("                \n");
		SetCursorPosition(gotoX + 40, gotoY + 1);
		printf_s("      Quit      \n");
		SetCursorPosition(gotoX + 40, gotoY + 2);
		printf_s("      Game      \n");
		SetCursorPosition(gotoX + 40, gotoY + 3);
		printf_s("                ");
		SetColor(WHITE, BLACK);
		m_LastMenu = MenuSelect(3, gotoX, gotoY, currentY, gameStatus);
		break;
	case LOSE:
		gotoX = 6;
		gotoY = 13;
		currentY = 0;
		SetColor(BLACK, GREEN);
		SetCursorPosition(gotoX, gotoY);
		printf_s("                \n");
		SetCursorPosition(gotoX, gotoY + 1);
		printf_s("    To Title    \n");
		SetCursorPosition(gotoX, gotoY + 2);
		printf_s("  (New Setting) \n");
		SetCursorPosition(gotoX, gotoY + 3);
		printf_s("                ");
		SetColor(BLACK, WHITE);
		SetCursorPosition(gotoX + 20, gotoY);
		printf_s("                \n");
		SetCursorPosition(gotoX + 20, gotoY + 1);
		printf_s("   Play Again   \n");
		SetCursorPosition(gotoX + 20, gotoY + 2);
		printf_s(" (Same Setting) \n");
		SetCursorPosition(gotoX + 20, gotoY + 3);
		printf_s("                ");
		SetCursorPosition(gotoX + 40, gotoY);
		printf_s("                \n");
		SetCursorPosition(gotoX + 40, gotoY + 1);
		printf_s("      Quit      \n");
		SetCursorPosition(gotoX + 40, gotoY + 2);
		printf_s("      Game      \n");
		SetCursorPosition(gotoX + 40, gotoY + 3);
		printf_s("                ");
		SetColor(WHITE, BLACK);
		m_LastMenu = MenuSelect(3, gotoX, gotoY, currentY, gameStatus);
		break;
	}
}
Esempio n. 22
0
unsigned int WINAPI IocpManager::IoWorkerThread(LPVOID lpParam)
{
	LThreadType = THREAD_IO_WORKER;
	LIoThreadId = reinterpret_cast<int>(lpParam);
	LTimer = new Timer;
	LLockOrderChecker = new LockOrderChecker(LIoThreadId);

	HANDLE hComletionPort = GIocpManager->GetComletionPort();

	while (true)
	{
		/// 타이머 작업은 항상 돌리고
		LTimer->DoTimerJob();

		/// IOCP 작업 돌리기
		DWORD dwTransferred = 0;
		OverlappedIOContext* context = nullptr;
		ULONG_PTR completionKey = 0;

		int ret = GetQueuedCompletionStatus(hComletionPort, &dwTransferred, (PULONG_PTR)&completionKey, (LPOVERLAPPED*)&context, GQCS_TIMEOUT);

		ClientSession* theClient = context ? context->mSessionObject : nullptr ;
		
		if (ret == 0 || dwTransferred == 0)
		{
			int gle = GetLastError();

			/// check time out first 
			if( gle == WAIT_TIMEOUT && context == nullptr )
					continue;
		
			if (context->mIoType == IO_RECV || context->mIoType == IO_SEND )
			{
				CRASH_ASSERT(nullptr != theClient);

				/// In most cases in here: ERROR_NETNAME_DELETED(64)

				theClient->DisconnectRequest(DR_COMPLETION_ERROR);

				DeleteIoContext(context);

				continue;
			}
		}

		CRASH_ASSERT(nullptr != theClient);
	
		bool completionOk = false;
		switch (context->mIoType)
		{
		case IO_DISCONNECT:
			theClient->DisconnectCompletion(static_cast<OverlappedDisconnectContext*>(context)->mDisconnectReason);
			completionOk = true;
			break;

		case IO_ACCEPT:
			theClient->AcceptCompletion();
			completionOk = true;
			break;

		case IO_RECV_ZERO:
			completionOk = PreReceiveCompletion(theClient, static_cast<OverlappedPreRecvContext*>(context), dwTransferred);
			break;

		case IO_SEND:
			completionOk = SendCompletion(theClient, static_cast<OverlappedSendContext*>(context), dwTransferred);
			break;

		case IO_RECV:
			completionOk = ReceiveCompletion(theClient, static_cast<OverlappedRecvContext*>(context), dwTransferred);
			break;

		default:
			printf_s("Unknown I/O Type: %d\n", context->mIoType);
			CRASH_ASSERT(false);
			break;
		}

		if ( !completionOk )
		{
			/// connection closing
			theClient->DisconnectRequest(DR_IO_REQUEST_ERROR);
		}

		DeleteIoContext(context);
	}

	return 0;
}
Esempio n. 23
0
/* main:  register the interface, start listening for clients */
void __cdecl main(int argc, char * argv[])
{
    RPC_STATUS status;
    unsigned char * pszProtocolSequence = "ncacn_ip_tcp";
    unsigned char * pszSecurity         = NULL;
    unsigned char * pszEndpoint         = "8765";
    unsigned char * pszSpn              = NULL;	
    unsigned int    cMinCalls           = 1;
    unsigned int    cMaxCalls           = 20;
    unsigned int    fDontWait           = FALSE;

    int i;

    /* allow the user to override settings with command line switches */
    for (i = 1; i < argc; i++) {
        if ((*argv[i] == '-') || (*argv[i] == '/')) {
            switch (tolower(*(argv[i]+1))) {
            case 'p':  // protocol sequence
                pszProtocolSequence = argv[++i];
                break;
            case 'e':
                pszEndpoint = argv[++i];
                break;
            case 'a':
                pszSpn = argv[++i];
                break;
            case 'm':
                cMaxCalls = (unsigned int) atoi(argv[++i]);
                break;
            case 'n':
                cMinCalls = (unsigned int) atoi(argv[++i]);
                break;
            case 'f':
                fDontWait = (unsigned int) atoi(argv[++i]);
                break;
	  /* case 'i':
		if(!_stricmp(argv[++i],"No_Authenticate"))
			ifFlag = RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH;
		break;*/

            case 'h':
            case '?':
            default:
                Usage(argv[0]);
            }
        }
        else
            Usage(argv[0]);
    }

    status = RpcServerUseProtseqEp(pszProtocolSequence,
                                   cMaxCalls,
                                   pszEndpoint,
                                   pszSecurity);  // Security descriptor
    printf_s("RpcServerUseProtseqEp returned 0x%x\n", status);
    if (status) {
        exit(status);
    }

    /* User did not specify spn, construct one. */
    if (pszSpn == NULL) {
        MakeSpn(&pszSpn);
    }

    /* Using Negotiate as security provider */
    status = RpcServerRegisterAuthInfo(pszSpn,
                                       RPC_C_AUTHN_GSS_NEGOTIATE,
                                       NULL,
                                       NULL);
	
    printf_s("RpcServerRegisterAuthInfo returned 0x%x\n", status);
    if (status) {
        exit(status);
    }	

    status = RpcServerRegisterIfEx(umarsh_ServerIfHandle,
		                           NULL,
		                           NULL,
		                           0,
		                           RPC_C_LISTEN_MAX_CALLS_DEFAULT,
		                           NULL );

    printf_s("Calling RpcServerListen\n");
    status = RpcServerListen(cMinCalls,
                             cMaxCalls,
                             fDontWait);
    printf_s("RpcServerListen returned: 0x%x\n", status);
    if (status) {
        exit(status);
    }

    if (fDontWait) {
        printf_s("Calling RpcMgmtWaitServerListen\n");
        status = RpcMgmtWaitServerListen();  //  wait operation
        printf_s("RpcMgmtWaitServerListen returned: 0x%x\n", status);
        if (status) {
            exit(status);
        }
    }

}  // end main()
Esempio n. 24
0
/**
 * Print out an array of integers with a new line.
 */
void println_s(int64_t* input, size_t input_size) {
	printf_s(input, input_size);
	printf("\n");
}
Esempio n. 25
0
int main()
{
	int i, j, len, a, b;
	char *src = "6*(5+(2+3)*8+3)";
	char des[255];
	Stack S;

	S = createStack();
	if (S == NULL) {
		printf_s("Error\n");
		return 1;
	}

	i = len = 0;
	while (src[i++] != '\0')
		len++;

	/* 将中缀转换为后缀 */
	for (i = j = 0; i < len; i++) {
		if (isSymbol(src[i])) {
			if (src[i] != ')') {
				if (isEmpty(S))
					pushChar(src[i], S);
				else if (pricmp(src[i], topChar(S)) > 0)
					pushChar(src[i], S);                      
				else {
					while (!isEmpty(S) && pricmp(src[i], topChar(S)) <= 0) {
						des[j++] = topChar(S);
						pop(S);
					}
					pushChar(src[i], S);
				}
			}
			else if (src[i] == ')') {
				while (topChar(S) != '(' && !isEmpty(S)) {
					des[j++] = topChar(S);
					pop(S);
				}
				pop(S);
			}
		}
		else {
			des[j++] = src[i];
		}
	}
	/* 将栈里的剩余符号弹出 */
	while (!isEmpty(S)) {
		des[j++] = topChar(S);
		pop(S);
	}
	des[j--] = '\0';
	printf("%s\n", des);
	/* 转换结束 */
	
	/* 用后缀表达式完成计算 */
	i = len = 0;
	while (des[i++] != '\0')
		len++;

	for (i = 0; i < len; i++) {
		if (!isSymbol(des[i]))
			pushInt(des[i] - 48, S);
		else {
			a = topInt(S);
			pop(S);
			b = topInt(S);
			pop(S);
			//printf_s("\na=%d, b=%d\n", a, b);
			switch (des[i]) {
			case '+':
				pushInt(a + b, S);
				break;
			case '-':
				pushInt(a - b, S);
				break;
			case '*':
				pushInt(a*b, S);
				break;
			case '/':
				pushInt(a / b, S);
				break;
			}
		}
	}
	printf_s("Result=%d\n", topInt(S));
	return 0;
}
Esempio n. 26
0
int main(void)
{
    ItemStruct *itemList = NULL;
    int slotCount = 0;
    char selection;
    int errorFlag = TRUE;
    int continueFlag = TRUE;
    char fileName[C_FILE_NAME_LENGTH] = "test.bin";

    printf_s("Welcome to the shopping list!\n");

    itemList = (ItemStruct*)malloc(sizeof(ItemStruct));

    do
    {
        if (itemList == NULL)
        {
            printf_s("\n");
            printf_s("*** Out of Memory! Program abort! ***\n");
            Sleep(1000);
            return 1;
        }
        printMeny();
        selection = _getch();
        printf_s("%c\n\n", selection);
        Sleep(400);


        switch (selection)
        {
        case '1':
        {
            // 1 - Add item to itemlist.
            itemList = addItemToListinHeap(itemList, &slotCount);
            break;
        }
        case '2':
        {
            // 2 - Load itemlist from file
            // Vi ska ladda en lista, kasta bort den gamla
            // TODO: Fråga om operatorn vill kasta den gamla listan: om inte återgå till menyn.
            free(itemList);
            itemList = loadItemList("test.bin", &slotCount);
            break;
        }
        case '3':
        {
            // 3 - Print itemlist
            printList(itemList, slotCount);
            break;
        }
        case '4':
        {
            // 4 - Save itemlist to file.
            errorFlag = saveItemList("test.bin", itemList, slotCount);
            break;
        }
        case '5':
        {
            // 5 - Edit item in itemlist. 
            // TODO:
            break;
        }
        case '6':
        {
            // 6 - Delete item in itemlist.
            // TODO:
            int itemId, index;
            int errorFlag;

            do
            {
                // Se till att användaren matar in korrekt id.
                printf_s("Enter the item ID that you want to remove: ");
                scanf_s("%d", &itemId);
                flushRestOfLine();

                if (itemId <= 0)
                {
                    printf_s("Please enter item ID > 0 !\n\n");
                    errorFlag = TRUE;
                }
                else
                {
                    errorFlag = FALSE;
                }

            } while (errorFlag);

            // Leta upp ID i listan, om ej hittat returneras -1;
            index = searchItemId(itemList, slotCount, itemId);
            if (index < 0)
            {
                printf_s("*** Index not Found. No item Removed! ***\n\n");
            }
            else
            {
                // TODO: Gör en print på item och be om bekräftelse!

                // Vi blankar item ID för att markera ledig slot
                itemList[index].isId = 0;
                printf_s("You have now removed item-Id: %d\n", itemId);

            }
            break;
        }
        case '7':
        {
            // 7 - Exit Program.
            continueFlag = FALSE;
            break;
        }
        default:
            printf_s("*** Please select a number between 1 and 7! ***\n");
            break;
        }
    } while (continueFlag);

    printf_s("Thank you for using the shopping list!\n\n");

    free(itemList);
    itemList = NULL;
    return 0;
} // Main
Esempio n. 27
0
int main()
{
	
#ifdef TEST_STRING
#ifdef CREATE_FILE
	ASCFileIO StringFile;
	ASCString strString = "Test";

	if(StringFile.Open("StringTest.ascinib", IO_OUT_BINARY))
	{
		StringFile.Clear();
		strString.Serialize(&StringFile);
		StringFile.Close();
	}
#else
	ASCFileIO StringFile;
	ASCString strString;
	if(StringFile.Open("StringTest.ascinib", IO_IN_BINARY))
	{
		void* pData = StringFile.ReadBinary();
		void* pDataOrig = pData;
		strString.LoadBinary(pData);
		SafeDelete( pDataOrig );
		StringFile.Close();
	}
	
	printf_s(strString.c_str());
	printf_s("\n");

	printf_s("Press Any Key To Continue...");
	getchar();
#endif
#endif

#ifdef TEST_VECTOR
#ifdef CREATE_FILE
	ASCFileIO VectorFile;
	ASCVector<ASCString> vecTest;
	vecTest.push_back("Vec Test");
	vecTest.push_back("Vec TestAgain");

	if(VectorFile.Open("VectorTest.ascinib", IO_OUT_BINARY))
	{
		VectorFile.Clear();
		vecTest.Serialize(&VectorFile);
		VectorFile.Close();
	}
#else
	ASCFileIO VectorFile;
	ASCVector<ASCString> vecTest;
	if(VectorFile.Open("VectorTest.ascinib", IO_IN_BINARY))
	{
		void* pData = VectorFile.ReadBinary();
		void* pDataOrig = pData;
		vecTest.LoadBinary(pData);
		SafeDelete( pDataOrig );
		VectorFile.Close();
	}
	
	printf_s(vecTest[0].c_str());
	printf_s("\n");
	printf_s(vecTest[1].c_str());
	printf_s("\n");

	printf_s("Press Any Key To Continue...");
	getchar();
#endif
#endif

#ifdef TEST_TREE
#ifdef CREATE_FILE
	ASCTree<ASCString> m_tTree;
	ASCFileIO File;
	m_tTree.Add("Test", "Val");
	m_tTree.Add("TestAgain", "Value");

	if(File.Open("TreeTest.ascinib", IO_OUT_BINARY))
	{
		File.Clear();
		m_tTree.Serialize(&File);
		File.Close();
	}
#else
	ASCTree<ASCString> m_tTree;
	ASCFileIO File;
	if(File.Open("TreeTest.ascinib", IO_IN_BINARY))
	{
		void* pData = File.ReadBinary();
		void* pDataOrig = pData;
		m_tTree.LoadBinary(pData);
		SafeDelete( pDataOrig );
		File.Close();
	}
	
	printf_s(m_tTree.At("Test").c_str());
	printf_s("\n");
	printf_s(m_tTree.At("TestAgain").c_str());
	printf_s("\n");

	printf_s("Press Any Key To Continue...");
	getchar();
#endif
#endif

	
#ifdef TEST_INI
	ASCINIFile INIFile;
	if(INIFile.Load("DBInterfaceAtlas.ascatl"))
	{
		printf_s("INI File loaded\n");
	}
	printf_s("Press Any Key To Continue...");
	getchar();
#endif

	ASCFinalShutdownDelay::SetCanEnd( true );
	return 0;
}
Esempio n. 28
0
void systemAbort(char* ir_message)
{
    printf_s("\n\n ***** %s ****** \n\n", ir_message);
    Sleep(2000);
    exit(EXIT_FAILURE);
} // systemAbort
Esempio n. 29
0
// Creates a spn if the user hasn't specified one.
void MakeSpn(unsigned char **pszSpn)
{
    DWORD status = ERROR_SUCCESS;
    ULONG ulSpn = 1;
    unsigned char ** arrSpn = NULL;
    HANDLE hDS;
    PDOMAIN_CONTROLLER_INFO pDomainControllerInfo;
    char lpCompDN[128];
    ULONG ulCompDNSize = sizeof(lpCompDN);
    BOOL NoFailure = TRUE;

    status = DsGetSpn(DS_SPN_NB_HOST,
                      "usrdef",
                      NULL, // DN of this service.
                      0, // Use the default instance port.
                      0, // Number of additional instance names.
                      NULL, // No additional instance names.
                      NULL, // No additional instance ports.
                      &ulSpn, // Size of SPN array.
                      &arrSpn); // Returned SPN(s).	
				  
    printf_s("DsGetSpn returned 0x%x\n", status);
    if (status != ERROR_SUCCESS) {
        exit(status);
    }
	
    // Get the name of domain if it is domain-joined
    if (status = DsGetDcName(NULL,
                             NULL,
                             NULL,
                             NULL,
                             DS_RETURN_DNS_NAME,
                             &pDomainControllerInfo) != NO_ERROR) {
        printf_s("DsGetDcName returned %d\n", GetLastError());
        NoFailure = FALSE;
    }
	
    // if it is domain joined 
    if (NoFailure) {
        // Bind to the domain controller for our domain 
        if ((status = DsBind(NULL,
                             pDomainControllerInfo->DomainName,
                             &hDS)) != ERROR_SUCCESS) {
            printf_s("DsBind returned %d\n", GetLastError());
            NoFailure = FALSE;
        }
    }

    if (NoFailure) {
        if ((status = NetApiBufferFree(pDomainControllerInfo)) != NERR_Success) {
            printf_s("NetApiBufferFree returned %d\n", status);
            exit(status);
        }

        if (GetComputerObjectName(NameFullyQualifiedDN, lpCompDN, &ulCompDNSize) == 0) {
            printf_s("GetComputerObjectName returned %d\n", GetLastError());
            exit(status);
        }

        /* We could check whether the SPN is already registered for this
        computer's DN, but we don't have to.  Modification is performed
        permissiely by this function, so that adding a value that already 
        exists does not return an error.  This way we can opt for the internal
        check instead of doing it ourselves. */
	
        status = DsWriteAccountSpn(hDS, DS_SPN_ADD_SPN_OP, lpCompDN, ulSpn, arrSpn);
        if (status != NO_ERROR) {
            printf_s("DsWriteAccountSpn returned %d\n", status);
            exit(status);
        }
        DsUnBind(&hDS);
    }

    *pszSpn = *arrSpn;
}
Esempio n. 30
0
/*
==================
==================
*/
void Lamorna_Setup(

	game_data_& game_data,
	FILE *boot_log

)
{
	game_data.memory_chunk.chunk_ptr = game_data.memory_chunk.chunk;

	Get_System_Info(game_data.thread_pool);

	Initialise_Input(game_data.timer, game_data.user_input);

	Load_UI(game_data.user_interface, game_data.memory_chunk);

	Load_Map_Elements(game_data.model_token_manager);

	Load_External_Models(game_data.model_manager, game_data.memory_chunk);

	Hardcode_Cube_Template(

		game_data.model_manager.model[model_::id_::CUBE],
		game_data.model_manager.model[model_::id_::CUBE_BACKFACE],
		game_data.memory_chunk
	);

	Specialise_Cube_Template(game_data.model_manager, game_data.memory_chunk);

	Create_BVH(

		game_data.model_token_manager,
		game_data.lightmap_manager,
		game_data.model_manager,
		game_data.memory_chunk,
		game_data.grid
	);

	Load_Sounds(game_data.memory_chunk, game_data.sound_system.wavs);

	Initialise_Sound(game_data.sound_system.direct_sound, game_data.sound_system.sound_buffer, game_data.sound_system.sound_mixer);

	{
		for (__int32 i_thread = 0; i_thread < thread_pool_::MAX_WORKER_THREADS; i_thread++) {
			for (__int32 bin_y = 0; bin_y < display_::N_BINS_Y; bin_y++) {
				for (__int32 bin_x = 0; bin_x < display_::N_BINS_X; bin_x++) {

					screen_bin_& bin = game_data.display.screen_bin[i_thread][bin_y][bin_x];

					for (__int32 i_draw_call = 0; i_draw_call < draw_call_::id_::COUNT; i_draw_call++) {
						bin.draw_id[i_draw_call] = -1;
						bin.n_tris[i_draw_call] = 0;
					}

					bin.n_draw_calls = -1;
					bin.n_triangles = 0;
				}
			}
		}
	}

	Initialise_Systems(

		game_data.sound_system.sound_event_table,
		game_data.animation_manager,
		game_data.behaviour_manager,
		game_data.collision_manager,
		game_data.way_point_manager,
		game_data.lightmap_manager,
		game_data.model_manager,
		game_data.component_data,
		game_data.model_token_manager,
		game_data.timer,
		game_data.particle_manager,
		game_data.command_buffer_handler,
		game_data.collision_response,
		game_data.grid,
		game_data.memory_chunk
	);

	Load_Frame_Jobs(

		game_data.model_token_manager,
		game_data.model_manager,
		game_data.user_input,
		game_data.timer,
		game_data.sound_system,
		game_data.display,
		game_data.game_matrices,
		game_data.behaviour_manager,
		game_data.animation_manager,
		game_data.way_point_manager,
		game_data.command_buffer_handler,
		game_data.collision_response,
		game_data.particle_manager,
		game_data.collision_manager,
		game_data.lightmap_manager,
		game_data.component_data,
		game_data.frame_jobs,
		game_data.thread_pool,
		game_data.user_interface,
		game_data.grid

	);

	{
		for (__int32 i_thread = 0; i_thread < thread_pool_::MAX_WORKER_THREADS; i_thread++) {
			Clear_Tile_Buffer(i_thread, game_data.display);
		}
	}

	const __int64 num_bytes_allocated = (char*)game_data.memory_chunk.chunk_ptr - (char*)game_data.memory_chunk.chunk;
	const __int64 num_bytes_unallocated = memory_chunk_::NUM_BYTES - num_bytes_allocated;
	printf_s("MEMORY REMAINING: %i \n", (__int32)num_bytes_unallocated);

	Thread_Pool_Initialise(game_data.thread_pool);

	printf_s("\n...WELCOME to Lamorna Engine! \n");
}