Exemplo n.º 1
0
int64_t getTimerFrequency()
{
	if (highResTimerFrequency == 0)
		initTime();

	return highResTimerFrequency;
}
Exemplo n.º 2
0
void Control::bulkInsert()
{
    QSqlQuery query;
    query.exec("exec DaoRu");
    if(query.lastError().type() != QSqlError::NoError)
    {
        QMessageBox* message = new QMessageBox();
        QString str;
        str += query.lastError().databaseText();
        message->setWindowTitle("错误");
        message->setText(str);
        message->exec();
//        ui->confirm->setEnabled(true);
        return;
    }
    initTime();
    addBTSname();
    addCellID();
    QMessageBox* message = new QMessageBox();
    QString str;
    str += "批量导入成功!";
    message->setWindowTitle("成功");
    message->setText(str);
    message->exec();
}
Exemplo n.º 3
0
void setup(void) {
	init_messages();
	init_motors();
	init_inertial_sensors();
	init_control();
	initTime();
}
Exemplo n.º 4
0
int main() {
	int ch;
	int n, i, h, m, s;
	scanf("%d", &n);
	Time *t = (Time*) malloc(sizeof(Time)*n);
	while ((ch = getchar()) != EOF) {
		switch(ch) {
			case 'i':
				scanf("%d", &i);
				initTime(&t[i]);
				break;
			case 's':
				scanf("%d%d%d%d", &i, &h, &m, &s);
				setTime(&t[i], h, m, s);
				break;
			case 'a':
				scanf("%d%d%d%d", &i, &h, &m, &s);
				addTime(&t[i], h, m, s);
				break;
			case 'p':
				scanf("%d", &i);
				printTime(&t[i]);
				printTime24(&t[i]);
				break;
			default:
				break;
		}
	}
	free(t);
	return 0;
}
Exemplo n.º 5
0
TimeUnit::TimeUnit(TimeUnit::UTimeUnitFields timeUnitField) {
    fTimeUnitField = timeUnitField;
    switch (fTimeUnitField) {
    case UTIMEUNIT_YEAR:
        initTime("year");
        break;
    case UTIMEUNIT_MONTH:
        initTime("month");
        break;
    case UTIMEUNIT_DAY:
        initTime("day");
        break;
    case UTIMEUNIT_WEEK:
        initTime("week");
        break;
    case UTIMEUNIT_HOUR:
        initTime("hour");
        break;
    case UTIMEUNIT_MINUTE:
        initTime("minute");
        break;
    case UTIMEUNIT_SECOND:
        initTime("second");
        break;
    default:
        U_ASSERT(false);
        break;
    }
}
Exemplo n.º 6
0
int main(void)
{
	Time *time = (Time *)malloc(sizeof(Time));
	initTime(time);
	setTime(time, 15, 56, 17);
	addTime(time, 1, 8, 56);
	printTime(time);
	return 0;
}
Exemplo n.º 7
0
uint64_t et::queryContiniousTimeInMilliSeconds()
{
	if (shouldInitializeTime)
		initTime();

	LARGE_INTEGER c = { };
	QueryPerformanceCounter(&c);

	return 1000 * (c.QuadPart - initialCounter) / performanceFrequency;
}
Exemplo n.º 8
0
void Control::data_in()
{
    ui->confirm->setEnabled(false);
    in->data_in(ui->comboBox->currentIndex());
    initTime();
    addBTSname();
    addCellID();
    QMessageBox* message = new QMessageBox();
    QString str;
    str += "已导入!";
    message->setWindowTitle("成功");
    message->setText(str);
    message->exec();
    ui->confirm->setEnabled(true);
}
Exemplo n.º 9
0
bool GameGuiLayer::init() {
    if (!Layer::init())
    {
        return false;
    }
    gotoResultLayer = false;
    Size visibleSize = Director::getInstance()->getVisibleSize();
    //add pause btn to this layer
    MenuItemImage* start_btn = MenuItemImage::create(
                                   "btn_setting.png", "btn_setting.png", CC_CALLBACK_0(GameGuiLayer::pauseGame, this));
    Menu* start_game = Menu::create(start_btn, NULL);
    start_game->setPosition(visibleSize.width - 30, visibleSize.height - 30);
    this->addChild(start_game);
    //add player score
    playerScore = LabelAtlas::create(
                      cocos2d::String::createWithFormat("%d", GAMEDATA::getInstance()->getScore())->_string, "game_result_score_num.png", 49, 70, '0');
    playerScore->setScale(0.8f);
    playerScore->setAnchorPoint(ccp(0.5, 0.5));
    playerScore->setPosition(ccp(240, 760));
    this->addChild(playerScore);
    //init palyer time
    initTime();

    //add time progress
    gameSlioder = GameSlioder::create();
    gameSlioder->setAnchorPoint(ccp(0, 0));
    gameSlioder->setPosition(ccp(0, 0));
    this->addChild(gameSlioder);
    //add play time
    LabelAtlas* zero = LabelAtlas::create("00", "time_num.png", 17, 20, '0');
    zero->setPosition(ccp(195, 695));
    this->addChild(zero);

    Sprite* devide = Sprite::create("time_devide_icon.png");
    devide->setPosition(ccp(234, 707));
    this->addChild(devide);
    std::string time_string = "";
    if (totalTime - passTime < 10) {
        std::string time_string = "0";
    }
    palyTime = LabelAtlas::create(time_string +
                                  cocos2d::String::createWithFormat("%d", (int)(totalTime - passTime))->_string, "time_num.png", 17, 20, '0');
    palyTime->setPosition(ccp(240, 695));
    this->addChild(palyTime);
    scheduleUpdate();
    schedule(schedule_selector(GameGuiLayer::updateTime), 1.0f, kRepeatForever, 0);
    return true;
}
Exemplo n.º 10
0
int main()
{
    Time t;
    initTime(&t);
    addTime(&t, 14, 30, 2);
    printTime(&t);
    addTime(&t, 19, 32, 36);
    printTime(&t);
    setTime(&t, 2, 7, 12);
    printTime(&t);
    addTime(&t, 15, 5, 45);
    printTime(&t);
    setTime(&t, 15, 30, 21);
    printTime(&t);
    return 0;
}
Exemplo n.º 11
0
bool GameGuiLayer::init(){
	if ( !Layer::init() )
	{
		return false;
	}
	Size visibleSize = Director::getInstance()->getVisibleSize();
	//add pause btn to this layer
	MenuItemImage* start_btn = MenuItemImage::create("btn_bg_normal.png","btn_bg_click.png",CC_CALLBACK_0(GameGuiLayer::pauseGame,this));
	Menu* start_game = Menu::create(start_btn,NULL);
	start_game->setPosition(50,visibleSize.height-50);
	this->addChild(start_game);


	initTime();
	scheduleUpdate();
	return true;
}
Exemplo n.º 12
0
Control::Control(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Control)
{
    ui->setupUi(this);
    setWindowTitle("GSM管理界面");
    out = new Dataout(0,"0",this);
    in = new DataIn();
    ui->stackedWidget->setCurrentIndex(0);
    ui->stackedWidget_2->setCurrentIndex(0);
    QRegExp regExp("0?[.][0-9]+$");
    ui->lineEdit->setValidator(new QRegExpValidator(regExp,this));
    initTime();
    addBTSname();
    addCellID();
    connect(ui->confirm,SIGNAL(clicked()),this,SLOT(data_in()));
    connect(ui->confirm_2,SIGNAL(clicked()),this,SLOT(data_out()));
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(page1()));
    connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(page2()));
    connect(ui->confirm_3,SIGNAL(clicked()),this,SLOT(queryBTS()));
    connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(page3()));
    connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(page4()));
    connect(ui->confirm_4,SIGNAL(clicked()),this,SLOT(queryCell()));
    connect(ui->pushButton_6,SIGNAL(clicked()),this,SLOT(bulkInsert()));
    connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(page5()));
    connect(ui->pushButton_9,SIGNAL(clicked()),this,SLOT(reCalculateDatas()));
    connect(ui->pushButton_7,SIGNAL(clicked()),this,SLOT(page6()));
    connect(ui->pushButton_11,SIGNAL(clicked()),this,SLOT(printNeighbor()));
    connect(ui->pushButton_8,SIGNAL(clicked()),this,SLOT(page7()));
    connect(ui->pushButton_10,SIGNAL(clicked()),this,SLOT(findNeighbor()));
    connect(ui->pushButton_12,SIGNAL(clicked()),this,SLOT(findCellInfo()));


    connect(ui->pushButton_13,SIGNAL(clicked()),this,SLOT(page13()));
    connect(ui->pushButton_14,SIGNAL(clicked()),this,SLOT(page14()));
    connect(ui->pushButton_15,SIGNAL(clicked()),this,SLOT(page15()));
    connect(ui->pushButton_16,SIGNAL(clicked()),this,SLOT(page16()));
    connect(ui->pushButton_17,SIGNAL(clicked()),this,SLOT(page17()));
    connect(ui->pushButton_18,SIGNAL(clicked()),this,SLOT(page18()));

    connect(ui->pushButton_22,SIGNAL(clicked()),this,SLOT(action22()));
    connect(ui->pushButton_23,SIGNAL(clicked()),this,SLOT(action23()));
}
Exemplo n.º 13
0
void TimingData::init()
{
    // Set up the timing system.
    initTime();

    // Create the frame info object
    if (!timingData) timingData = new TimingData();

    // Set up the frame info structure.
    timingData->frameNumber = 0;

    timingData->lastFrameTimestamp = systemTime();
    timingData->lastFrameDuration = 0;

    timingData->lastFrameClockstamp = getClock();
    timingData->lastFrameClockTicks = 0;

    timingData->isPaused = false;

    timingData->averageFrameDuration = 0;
    timingData->fps = 0;
}
Exemplo n.º 14
0
static void *
xrayswarm_init (Display *d, Window w)
{
  struct state *st = (struct state *) calloc (1, sizeof(*st));
  int i;

  st->dpy = d;
  st->win = w;

  st->dt = 0.3;
  st->targetVel = 0.03;
  st->targetAcc = 0.02;
  st->maxVel = 0.05;
  st->maxAcc = 0.03;
  st->noise = 0.01;
  st->minVelMultiplier = 0.5;

  st->nbugs = -1;
  st->ntargets = -1;
  st->trailLen = -1;

  st->colorScheme = /* -1 */  2;
  st->changeProb = 0.08;

  if (!initGraphics(st)) abort();

  computeConstants(st);
  initBugs(st);
  initTime(st);
  computeColorIndices(st);

  if (st->changeProb > 0) {
    for (i = random()%5+5; i >= 0; i--) {
      randomSmallChange(st);
    }
  }

  return st;
}
Exemplo n.º 15
0
void run(struct Computer *computer) {
	struct CPU *cpu = &computer->cpu;
	struct RAM *ram = &computer->ram;
	struct GPU *gpu = &computer->gpu;
	struct DMA *dma = &computer->dma;
	
	struct Screen *screen = computer->screen;
	
	// TODO boot computer
	initTime();
	
	// init CPU
	cpu->IP = CODE_ADDR;
	cpu->SP = ram->size - 1;
	
	CPU_run(cpu);
	
	// how many emulated cycles can we do until the next refresh
	uint32 cpuCycles = cpu->clockRate / gpu->refreshRate;
	uint32 tickCounter = 0;
		
	double refreshTimeMs = 1000.0 / (double) gpu->refreshRate;
	double sleepTimeMs = 0.0;
	
	double tickStartMs = 0.0;
	double tickEndMs = 0.0;
	double tickDiffMs = 0.0;
	
	printf("CPU clock rate: %ld Hz\n", cpu->clockRate);
	printf("Video refresh rate: %ld Hz\n", gpu->refreshRate);
	printf("CPU cycles per frame: %ld\n", cpuCycles);
	printf("Refresh time: %f ms\n", refreshTimeMs);
	
	while (CPU_isRunning(cpu)) {
		tickCounter = cpuCycles;
	
		tickStartMs = getMilliTime();
	
		while (CPU_isRunning(cpu) && tickCounter > 0) {
			CPU_tick(cpu);
			DMA_tick(dma);
			
			tickCounter--;
		}

		// update the screen
		if (screen != NULL) {
			draw(gpu, screen);
			CPU_interrupt(cpu, VBLANK_INTERRUPT);
		}
		
		// we need to pump events or the window freezes
		SDL_PumpEvents();
		
		SDL_RenderClear(screen->renderer);
		SDL_RenderCopy(screen->renderer, screen->texture, NULL, NULL);
		SDL_RenderPresent(screen->renderer);

		tickEndMs = getMilliTime();
		tickDiffMs = tickEndMs - tickStartMs;
		
		sleepTimeMs = refreshTimeMs - tickDiffMs;

		// printf("> %f %f\n", tickDiffMs, sleepTimeMs);
		
		if (sleepTimeMs >= 1.0) {
			SDL_Delay((Uint32) sleepTimeMs);
		}
	}
}
Exemplo n.º 16
0
int main(int argc, char* argv[])
{
    /* INITIALISATIONS DES BIBLIOTHEQUES : IMG, SDL, TTF */
    IMG_Init(IMG_INIT_PNG);
    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();

    Message msgs[NOMBRE_MESSAGES];
    initMessage(msgs);

    SDL_Surface *ecran = SDL_SetVideoMode(LARGEUR, HAUTEUR, BPP, SDL_HWSURFACE | SDL_DOUBLEBUF);

    /* Titre */
    SDL_WM_SetCaption("Duck Hunt", NULL);

    /* Icone */
    SDL_WM_SetIcon(SDL_LoadBMP("sprites/icon.bmp"), NULL);

    /* Initialisation des variables en rapport avec le temps */
    Time temps;
    initTime(temps);
    srand((unsigned)time(NULL));

    int modeJeu = 0;    // Le mode de jeu.
    int modeMenu = 1;   // Détermine la page du menu à afficher.

    Partie partie;
    partie.score = 0;
    partie.niveau = 0;
    Sprites sprites;
    Chien chien;

    Boutons boutons;
    initBouton(boutons);

    chargerImages(sprites, chien, boutons, "classique");
    boutons.bouton[BOUTON_THEME_CLASSIQUE].actif = true;

    Uint8 *keystate = SDL_GetKeyState(NULL);
    SourisEvent sourisEvent;
    initSourisEvent(sourisEvent);

    initFichiers();

    SDL_ShowCursor(SDL_DISABLE);

    menu(ecran, sprites, boutons, modeMenu, modeJeu, sourisEvent, temps, msgs, partie, chien);
    while (modeJeu != 0)
    {
        if (modeMenu != 0)
        {
            menu(ecran, sprites, boutons, modeMenu, modeJeu, sourisEvent, temps, msgs, partie, chien);
        }
        temps.currentTime = SDL_GetTicks();
        partie.alreadyShot = partie.alreadyGetEvent = partie.alreadyClic = false;
        for (int i = 0 ; i < sprites.canardActifs ; i++)
        {
            shoot(sourisEvent, sprites.canard[i], partie, temps, modeJeu);
            if ((temps.currentTime >= sprites.canard[i].vitesseTime + sprites.canard[i].vitesse))
            {
                mouvementsCanard(sprites.canard[i]);
                detectionBordsCanard(sprites.canard[i], partie, i);
                changementDirection(sprites.canard[i]);
                if(sprites.canard[i].etat == TOUCHED)
                {
                    touched(sprites.canard[i], temps);
                }
                sprites.canard[i].vitesseTime = temps.currentTime;
            }
            if (temps.currentTime >= sprites.canard[i].vitesseAnimationTime + sprites.canard[i].vitesseAnimation)
            {
                switchSpriteCanard(sprites.canard[i]);
                sprites.canard[i].vitesseAnimationTime = temps.currentTime;
            }
        }
        if(partie.shots <= 0)
        {
            for(int i = 0 ; i < sprites.canardActifs ; i++)
            {
                canardSurvivant(sprites, partie, i);
            }
        }
        if (temps.currentTime >= chien.vitesseAnimationTime + chien.vitesseAnimation)
        {
            switchSpriteChien(chien, partie);
            controlesChien(chien, partie, sprites);
            ramasserCanard(chien, partie, sprites);

            chien.vitesseAnimationTime = temps.currentTime;
            ramasserCanard(chien, partie, sprites);
        }
        if(partie.relancer)
        {
            relancerPartie(partie, sprites);
        }
        if(partie.round >= 5)
        {
            if(finPartie(partie))
            {
                if (testHighScore("scoresClassic", partie))
                {
                    modeMenu = 8;
                }
                else
                {
                    modeMenu = 9;
                }
            }
            else
            {
                partie.round = 0;
                partie.niveau ++;
                initPartie(partie, sprites.canardActifs);
                partie.jeu = true;
                for (int i=0; i<sprites.canardActifs; i++)
                {
                    initCanard(sprites.canard[i], partie);
                }
                initTableau(partie.tableauChasse, sprites);
                modeMenu = 6;
            }
        }
        if (keystate[SDLK_ESCAPE])
        {
            modeMenu = 5;
        }
        if (temps.currentTime >= temps.timeFps + temps.fpsTime)
        {
            genererRendu(ecran, sprites, sourisEvent, partie, chien, msgs);
            SDL_Flip(ecran);
            temps.timeFps = temps.currentTime;
        }

        SDL_Delay(1);
    }
    libererImages(sprites, chien, boutons);
    SDL_Quit();
    IMG_Quit();
    TTF_Quit();
    return EXIT_SUCCESS;
}
int main (void)
{
	//Set Pin Modes
//	pinMode(PIN_RaspiReset, OUTPUT);
//	pinMode(PIN_IHTempSensor, INPUT/*_ANALOG*/);
//	pinMode(PIN_MotorPosSensor, INPUT_PULLUP);
	pinMode(PIN_Ventil, OUTPUT);
//	pinMode(PIN_SafetyChain, OUTPUT);
	pinMode(PIN_PusherLocked, INPUT_PULLUP);
	pinMode(PIN_LidLocked, INPUT_PULLUP);
	pinMode(PIN_LidClosed, INPUT_PULLUP);
//	pinMode(PIN_SimulateButton0, OUTPUT);
//	pinMode(PIN_IHOff, OUTPUT);
//	pinMode(PIN_isIHOn, INPUT_PULLUP);
//	pinMode(PIN_IHOn, OUTPUT);
//	pinMode(PIN_MotorPWM, OUTPUT/*_PWM*/);
//	pinMode(PIN_IHPowerPWM, OUTPUT/*_PWM*/);
//	pinMode(PIN_IHFanPWM, OUTPUT/*_PWM*/);

	Motor_init();
	Heating_init();
	
	
	initTime();
	//Init LoL-Shield
//	#ifdef GRAYSCALE
	LedSign_Init(DOUBLE_BUFFER | GRAYSCALE);  //Initializes the screen
//	#else
//	LedSign_Init(DOUBLE_BUFFER);  //Initializes the screen
//	#endif
	LedSign_Clear(0);
	LedSign_Flip(false);
	
	//initialize time messurement
	//initTime();
	
	//Init SPI
	SPI_init(wdtRestart);
	
	//Disable JTAG interface
	MCUCR = _BV(JTD);
	MCUCR = _BV(JTD); //Need to write twice to disable it (Atmega_644.pdf, page 267, 23.8.1)
	
	
#ifdef DEBUG_MODE
	if (isExternalReset){
		wdtRestartCount = wdtRestartCount + 1;
	}
	//TODO remove, test was WTD reset
	if (wdtRestart && wdtRestartLast){
		wdtRestart = false;
	}
	wdtRestartLast = wdtRestart;
	digitalWrite(PIN_Ventil, wdtRestart);
	wdtRestart = false;
	
	char valueAsString[10];
	sprintf(valueAsString, "R%X", wdtRestartCount); //HEX
	//sprintf(valueAsString, "%d", wdtRestartCount);  //DEC
	DisplayHandler_setText2(valueAsString);
	DisplayHandler_displayText(false);
	_delay_ms(50);
#endif

	LedSign_Clear(PIXEL_HALF);
	LedSign_Flip(true);
	_delay_ms(100);
	LedSign_Clear(PIXEL_OFF);
	LedSign_Flip(true);
	
	/*
	digitalWrite(PIN_Ventil, HIGH);
	_delay_ms(5000);
	digitalWrite(PIN_Ventil, LOW);
	*/
	if (isStartup){
		//Was power On reset		
		LedSign_Clear(PIXEL_OFF);
		LedSign_Flip(true);
		DisplayHandler_setText("EveryCook is starting");
		currentMode = SPI_MODE_DISPLAY_TEXT;	
	} else {
		//is other than power on reset
		DisplayHandler_setPicture(&picture_hi[0]);
		DisplayHandler_DisplayBitMap();
	}

	initWatchDog();
	

	
	while(1){
		Motor_motorControl();
		Heating_heatControl();
		Heating_controlIHTemp();
		checkLocks();
		if (!LidClosed) Motor_setMotor(0);
		if (availableSPI() > 0) {
			triggerWatchDog(true);
			uint8_t data;
			uint8_t newMode = readSPI(true);
			char* newText;
			uint8_t readAmount = 0;
			boolean setOn = false;
			boolean setOff = false;
			switch(newMode){
				case SPI_MODE_IDLE:
				//DisplayHandler_setPicture(&picture_0[0]);
				//DisplayHandler_DisplayBitMap();
				break;
				case SPI_MODE_GET_STATUS:
					nextResponse = StatusByte;
					//DisplayHandler_setPicture(&picture_1[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				case SPI_MODE_DISPLAY_CLEAR:
					LedSign_Clear(0);
					LedSign_Flip(true);
					currentMode = 0;
					nextResponse = SPI_CommandOK;
				break;
				case SPI_MODE_MOTOR:
					data = readSPI(true);
					wdt_reset();
					if(LidClosed){
						Motor_setMotor(data);
					}else{
						Motor_setMotor(0);
					}
					nextResponse = SPI_CommandOK;
					//DisplayHandler_setPicture(&picture_2[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				case SPI_MODE_HEATING:
					data = readSPI(true);
					wdt_reset();
					Heating_setHeating(data);
					nextResponse = SPI_CommandOK;
					//DisplayHandler_setPicture(&picture_3[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				case SPI_MODE_GET_DEBUG:
					nextResponse = Vdebug;
					//DisplayHandler_setPicture(&picture_18[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				case SPI_MODE_VENTIL:
					VentilState = readSPI(true);
					wdt_reset();
					digitalWrite(PIN_Ventil, VentilState);
					nextResponse = SPI_CommandOK;
					//DisplayHandler_setPicture(&picture_10[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				
				case SPI_MODE_DISPLAY_PERCENT:
				case SPI_MODE_DISPLAY_PERCENT_TEXT:
					data = readSPI(true);
					wdt_reset();
					DisplayHandler_displayProgress(data, newMode == SPI_MODE_DISPLAY_PERCENT_TEXT);
					lastPercentValue = data;
					if (newMode != SPI_MODE_DISPLAY_PERCENT_TEXT){
						nextResponse = SPI_CommandOK;
						currentMode = newMode;
						break;
					}
				case SPI_MODE_DISPLAY_TEXT:
				case SPI_MODE_DISPLAY_TEXT_SMALL:
					if (DisplayHandler_readText()) {//[01]<textlen 1 Byte><text>[00<control byte>]
						if (newMode == SPI_MODE_DISPLAY_TEXT){
							DisplayHandler_displayText(false);
						} else {
							DisplayHandler_displayText(true);
						}
						lastTextUpdate = millis();
						if (newMode == SPI_MODE_DISPLAY_PERCENT_TEXT){
							updatePercentAgain = true;
						}
						nextResponse = SPI_CommandOK;
						currentMode = newMode;
					} else {
						nextResponse = SPI_Error_Text_Invalid;
					}
				break;
				
				case SPI_MODE_DISPLAY_PICTURE:
					readAmount=0;
					while (readAmount < 9){
						if (availableSPI() >= 2) {
							data = readSPI(true);
							picture[readAmount] = data << 8;
							data = readSPI(true);
							picture[readAmount] |= data;
							readAmount++;
							wdt_reset();
						} else {
							_delay_ms(1);
						}
					}
					if (availableSPI() == 0) {
						_delay_ms(10);
						if (availableSPI() == 0) {
							_delay_ms(20);
						}
					}
					if (availableSPI() > 0 && peekSPI() == 0x00) {
						readSPI(false);
						DisplayHandler_setPicture(&picture[0]);
						DisplayHandler_DisplayBitMap();
						currentMode = newMode;
						nextResponse = SPI_CommandOK;
					} else {
						DisplayHandler_setPicture(&picture[0]);
						DisplayHandler_DisplayBitMap();
						currentMode = newMode;
						nextResponse = SPI_Error_Picture_Invalid;
					}
				break;
				
				case SPI_MODE_MAINTENANCE:
					data = readSPI(true);
					if (data == 0x99) {
						setOn = true;
					} else if (data == 0x22){
						setOff = true;
					}
					//be sure its change to maintenance, it has the be send 2 times
					data = readSPI(true);
					if (data == SPI_MODE_MAINTENANCE) {
						data = readSPI(true);
						if (setOn && data != 0x99) {
							setOn = false;
						} else if (setOff && data != 0x22){
							setOff = false;
						}
						data = readSPI(true);
						//00 as command end mark
						if (data == 0x00){
							if (setOn){
								isMaintenanceMode = true;
								nextResponse = SPI_CommandOK;
							} else if (setOff){
								isMaintenanceMode = false;
								nextResponse = SPI_CommandOK;
							} else {
								nextResponse = SPI_Error_Unknown_Command;
							}
						} else {
							nextResponse = SPI_Error_Unknown_Command;
						}
					} else {
						nextResponse = SPI_Error_Unknown_Command;
					}
				break;
				
				case SPI_MODE_GET_MOTOR_SPEED:
					nextResponse = outputValueMotor;
					//DisplayHandler_setPicture(&picture_12[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				
				case SPI_MODE_GET_IGBT_TEMP:
					nextResponse = ihTemp8bit;
					//DisplayHandler_setPicture(&picture_hi[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				case SPI_MODE_GET_FAN_PWM:
					nextResponse = lastIHFanPWM;
					//DisplayHandler_setPicture(&picture_17[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				
				case SPI_MODE_GET_HEATING_OUTPUT_LEVEL:
					nextResponse = 0;
					//nextResponse = Heating_getLastOnPWM();
					//DisplayHandler_setPicture(&picture_14[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				
				case SPI_MODE_GET_MOTOR_POS_SENSOR:
					nextResponse = lastSensorValue;
					//DisplayHandler_setPicture(&picture_15[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				
				case SPI_MODE_GET_MOTOR_RPM:
					nextResponse = rpm;
					//DisplayHandler_setPicture(&picture_16[0]);
					//DisplayHandler_DisplayBitMap();
				break;
				
				default:
					nextResponse = SPI_Error_Unknown_Command;
			}
		} else {
			triggerWatchDog(false);
			switch(currentMode){
				case SPI_MODE_IDLE:
				break;
				case SPI_MODE_DISPLAY_PERCENT_TEXT:
					if (updatePercentAgain) {
						DisplayHandler_displayProgress(lastPercentValue, true);
						updatePercentAgain = false;
					}
				case SPI_MODE_DISPLAY_TEXT:
				case SPI_MODE_DISPLAY_TEXT_SMALL:
					if ((millis() - lastTextUpdate) > TEXT_UPDATE_TIMEOUT){
						lastTextUpdate = millis();
						if(!DisplayHandler_displayText(currentMode != SPI_MODE_DISPLAY_TEXT)){
							currentMode = 0;
						}
					}
				break;
			}
			//DisplayHandler_setPicture(&picture_0[0]);
			//DisplayHandler_DisplayBitMap();
		}	
	}
	
	return 0;
}
Exemplo n.º 18
0
// Make sure timer frequency is initialized before anyone tries to use it
struct StaticTime { StaticTime() { initTime(); } }staticTimeInst;
Exemplo n.º 19
0
int main(void)
{
	//some setup code
	storePin(1337); //only once needed
	initPincode();
	//initizialize power controle pins
	initPowerControle();
	//initizialize rotary.
	initRotary();
	//initialize shifter.
	initShifter();
	//initialize display code.
	initDisplay();
	//initialize serial comm
	init_uart();
	//initialize the servo code.
	initServo();
	//initialize time code
	initTime();
	//main loop.
	DDRB  |= (1<<PB4)|(1<<PB5);
	PORTB |= (1<<PB5)|(1<<PB4);
	while(1)
	{
		//get the input from user for pincode
		getInputPinCode();
		//if there is new data we check to see the commands.
		if(serial_available)
		{
			serial_available = 0;
			runSerialInputCommands(inputStr);
		}
		//check the servo state, disable it when it's active
		//for longer then a second.7
		if(isServoActive) //check to see if the state of the servo is active.
		{
			if(time-previousServo > timeScale)//see if a second has passed
			{
				if(finalServoPos != getCurrentServoState())
				{
					setServoPos(finalServoPos);
				}
				else
				{
					disableServo();
				}
			}
		}
		
		//send number if logged in and ticks changed and rotary has turned.
		//to prevent spam
		if(rotary_has_turned && ticks != previous_ticks && isLoggedIn)
		{
			previous_ticks = ticks;
			rotary_has_turned = 0;
			sendNumber(pin);
		}
		
		if(timeinSeconds >= 360)
		{
			powerOff();
		}
		else
		{
			powerOn();
		}
		
		//if pin is correctly set set green led, else red on.
		if(pin == actual_pin)
		{
			open();
			PORTB |= (1<<PB5);
			PORTB &= ~(1<<PB4);
		}
		else
		{
			if(!timeinSeconds%2)
				close();
			PORTB |= (1<<PB4);
			PORTB &= ~(1<<PB5);
		}
	}
	
	return 1;
}
Exemplo n.º 20
0
//////////////////////////////////////////////////////////////////////////
// Game-related
//////////////////////////////////////////////////////////////////////////
void Menu::init(bool doSavegame, SavegameType type, uint32 value) {

	bool useSameIndex = true;

	if (getGlobalTimer()) {
		value = 0;

		// Check if the CD file is present
		ArchiveIndex index = kArchiveCd1;
		switch (getProgress().chapter) {
		default:
		case kChapter1:
			break;

		case kChapter2:
		case kChapter3:
			index = kArchiveCd2;
			break;

		case kChapter4:
		case kChapter5:
			index = kArchiveCd3;
			break;
		}

		if (ResourceManager::isArchivePresent(index)) {
			setGlobalTimer(0);
			useSameIndex = false;

			// TODO remove existing savegame and reset index & savegame name
			warning("Menu::initGame: not implemented!");
		}

		doSavegame = false;
	} else {
		// TODO rename saves?
	}

	// Create a new savegame if needed
	if (!SaveLoad::isSavegamePresent(_gameId))
		getSaveLoad()->create(_gameId);

	if (doSavegame)
		getSaveLoad()->saveGame(kSavegameTypeEvent2, kEntityPlayer, kEventNone);

	if (!getGlobalTimer()) {
		// TODO: remove existing savegame temp file
	}

	// Init savegame & menu values
	_lastIndex = getSaveLoad()->init(_gameId, true);
	_lowerTime = getSaveLoad()->getTime(_lastIndex);

	if (useSameIndex)
		_index = _lastIndex;

	//if (!getGlobalTimer())
	//	_index3 = 0;

	if (!getProgress().chapter)
		getProgress().chapter = kChapter1;

	getState()->time = (TimeValue)getSaveLoad()->getTime(_index);
	getProgress().chapter = getSaveLoad()->getChapter(_index);

	if (_lowerTime >= kTimeStartGame) {
		_currentTime = (uint32)getState()->time;
		_time = (uint32)getState()->time;
		_clock->draw(_time);
		_trainLine->draw(_time);

		initTime(type, value);
	}
}
Exemplo n.º 21
0
int main ( int argc, char * const argv[] ) 
{
    Crypto  *crypto         = new Crypto();
    bool    loggedIn        = false;
    time_t  last_ping       = time( NULL );
    
    Socket  a_socket( crypto );
    Socket  g_socket( crypto );
    
    GameMap     *gameMap        = new GameMap( &g_socket );
    Dialogue    *dialogue       = new Dialogue();
    MapFile     *mapFile        = new MapFile();
    User        *user           = new User( &g_socket, gameMap, dialogue, mapFile );
    
    AccountInfo                     acct_info;
    std::vector< PET_PACKET >       PetList;
    
    char path[255];
    strcpy( path, GAMEFILESPATH );
    strcat( path, "ini/map.ini" );
    
    mapFile->process( path );
    
    initTime();
    srand( time( NULL ) );
    
    if ( argc != 2 )
        acct_info = account_info( "Whitey" );
    else
        acct_info = account_info( argv[1] );
    
    if ( !strcmp( acct_info.username, "NOTFOUND" ) || 
        !strcmp( acct_info.username, "" ) || 
        !strcmp( acct_info.password, "" ) ||
        !strcmp( acct_info.serverip, "" ) ||
        !strcmp( acct_info.servername, "" ) )
    {
        std::cout   << "Error: .account_info.conf must include a username and password, "
                    << "and optionally a server and protection code." << std::endl;
    }
    
    if ( !a_socket.connect( acct_info.serverip, ACCOUNTPORT ) )
        return 0;
    
    g_socket = login( a_socket, crypto, acct_info );
	
    while ( true )
    {
        g_socket.select();
		
        if ( g_socket.is_readable() )
        {
            CPacket packet;
			
            packet = g_socket.read_packet();
			
            if ( packet.header.size == 0 && packet.header.id == 0 )
            {
                std::cout << "Error while reading packet... time: " << timeGetTime() << std::endl;
                return 0;
            }
            
            if ( difftime( last_ping, time( NULL ) ) >  300 )
                return 0;
            
            switch ( packet.header.id )
            {
                case 1002:
                {
                    memset( ( void * )( packet.data + 0x04 ), 0, packet.header.size - sizeof( CPacketHeader ) );
                    packet.data[8] = 0xC5;
					
                    g_socket.send_packet( packet );
				}
                    
                    break;
					
                case 1004:
                {
                    MessagePacket *msg = new MessagePacket( packet );
                    
                    if ( msg->m_channel == CH_SYSTEM )
                        printf( "[%s]%s\n", msg->m_channelName, msg->m_message );
                    else if ( msg->m_channel == CH_VENDOR )
                        printf( "[%s](%s): %s\n", msg->m_channelName, 
                               msg->m_sender, msg->m_message );
                    else
                        printf( "[%s]%s %s speaks to %s: %s\n", msg->m_channelName, msg->m_sender, msg->m_emotion, 
                               msg->m_target, msg->m_message );
                    
                    if ( strcmp( msg->m_sender, OWNER ) && msg->m_channel == CH_PRIVATE )
                    {                        
                        MessagePacket *fffffu = new MessagePacket( user->m_name, msg->m_sender, "F**k you, stop PMing me.", CH_PRIVATE );
                        
                        g_socket.send_packet( fffffu->pack() );
                        
                        delete fffffu;
                    }
                    
                    if ( !strcmp( msg->m_sender, OWNER ) && msg->m_channel == CH_PRIVATE )
                    {
                        if ( !strcmp( msg->m_message, "@givemoney" ) )
                        {
                            PlayerList playerlist = gameMap->list_players();
                            PlayerList::iterator it;
                            
                            for ( it = playerlist.begin(); it != playerlist.end(); it++ )
                                user->give_money( it->first, 1 );
                        }
                    }
                    
                    delete msg;
                }
					
                    break;
					
                case 1005:
                {
                    WalkPacket  *walk   = new WalkPacket( packet );
                    Player      *player = gameMap->find_player( walk->m_playerID );
                    
                    if ( player->m_id == -1 )
                    {
                        delete player;
                        break;
                    }
                    
                    player->m_x = walk->m_destX;
                    player->m_y = walk->m_destY;

                    //printf( "%s has moved to [%d, %d]\n", PlayerList[id].m_name, x, y );
                    
                    delete walk;
                }
                    break;
				
                case 1006:
                {
                    ActionPacket    *action = new ActionPacket( packet );
                    Player          *player = gameMap->find_player( action->m_playerID );
                    
                    if ( player->m_id == -1 )
                    {
                        delete player;
                        break;
                    }
                    
                    break;
                    
                    switch ( action->m_actionID )
                    {
                        case 4:
                            printf( "* %s faints.\n", player->m_name );
                            break;
							
                        case 6:
                            printf( "* %s waves.\n", player->m_name );
                            break;
							
                        case 7:
                            printf( "* %s kneels.\n", player->m_name );
                            break;
							
                        case 8:
                            printf( "* %s is crying.\n", player->m_name );
                            break;
							
                        case 9:
                            printf( "* %s is angry.\n", player->m_name );
                            break;
							
                        case 10:
                            printf( "* %s sits.\n", player->m_name );
                            break;
							
                        case 12:
                            printf( "* %s is happy.\n", player->m_name );
                            break;
							
                        case 13:
                            printf( "* %s bows.\n", player->m_name );
                            break;
						
                        case 15:
                            printf( "* %s throws.\n", player->m_name );
                            break;
							
                        default:
                            printf( "* Unknown action preformed by %s [%d]\n", player->m_name, action->m_actionID );
                            break;
                    }
                    
                    delete action;
                }
					
                    break;
					
                case 1007:
                {
                    JumpPacket  *jump   = new JumpPacket( packet );
                    Player      *player = gameMap->find_player( jump->m_playerID );
                    
                    if ( player->m_id == -1 )
                    {
                        delete player;
                        break;
                    }
                    
                    if ( jump->m_mode == 2 )
                    {
                        player->m_x = jump->m_x;
                        player->m_y = jump->m_y;
                        
                        //printf( "%s has moved to [%d, %d]\n", PlayerList[id].m_name, x, y );
                    }
                    else if ( jump->m_direction == 8 )
                    {
                        //printf( "%s has left the map.\n", PlayerList[id].m_name );
                        
                        printf( "%s has left the map.\n", player->m_name );
                        
                        char msg[55];
                        strcpy( msg, "Cya later, " );
                        strcat( msg, player->m_name );
                        
                        MessagePacket *bai = new MessagePacket( user->m_name, player->m_name, msg, CH_PRIVATE );
                        
                        g_socket.send_packet( bai->pack() );
                        
                        delete bai;
						
                        gameMap->del_player( jump->m_playerID );
                    }
                    
                    delete jump;
                }
					
                    break;
					
                case 1008:
                {
                    CharInfoPacket *info = new CharInfoPacket( packet );
                    
                    user->process( info );
                    user->m_accountID = account_id;
                    
                    delete info;
                }
                    
                    break;
					
                case 1020:
                {
                    int response = timeGetTime() ^ ( ( user->m_characterID * user->m_characterID ) + 0x2537 );
					
                    memcpy( ( void * )( packet.data + 0x04 ), ( void * )&response, sizeof( response ) );
					
                    g_socket.send_packet( packet );
                }
					
                    break;
                
                case 1031:
                {
                    MapInfoPacket *info = new MapInfoPacket( packet );
                    gameMap->process( info );
                    
                    dialogue->m_open = false;
                    
                    user->m_x = info->m_x;
                    user->m_y = info->m_y;
                    
                    printf( "Entered: %s\n", gameMap->m_name );
					
                    if ( !loggedIn )
                    {
                        user->jump( 0, 0, 19, 0 );
                        
                        if ( strcmp( acct_info.pcode, "" ) )
                        {
                            char unlock[255];
                            
                            strcpy( unlock, "/unlock " );
                            strcat( unlock, acct_info.pcode );
                            
                            MessagePacket *umsg = new MessagePacket( user->m_name, user->m_name, unlock, CH_PRIVATE );
                            g_socket.send_packet( umsg->pack() );
                            delete umsg;
                        }
                        
                        MessagePacket *pokeman = new MessagePacket( user->m_name, "All", "A wild BlakeKing appears!", CH_NORMAL );
                        
                        g_socket.send_packet( pokeman->pack() );
                        
                        delete pokeman;
                    }
                    
                    delete info;
                }
					
                    break;
					
                case 1032:
                {
                    Player *player = new Player( packet );
                    
                    gameMap->add_player( player );
                    
                    //printf( "%s has entered the map (%d, %d)\n", player.m_name, player.m_x, player.m_y );
                    
                    if ( loggedIn )
                    {
                        char msg[55];
                        strcpy( msg, "Welcome to Water City, " );
                        strcat( msg, player->m_name );
                        
                        MessagePacket *hai = new MessagePacket( user->m_name, player->m_name, msg, CH_PRIVATE );
                        
                        g_socket.send_packet( hai->pack() );
                        
                        delete hai;
                    }
                    
                    delete player;
                }
					
                    break;
                    
                case 1033:
                {
                    /*int pet_id = *( int * )packet.data;
                    std::vector< PET_PACKET >::iterator it;
                    
                    for ( it = PetList.begin(); it != PetList.end(); it++ )
                        if ( it->id == pet_id ) 
                            printf( "Marching Pet: %s\n\n", it->name );*/
                }

                    break;
                    
                case 1034:
                {
                    PET_PACKET pp;
                
                    memcpy( ( void * )&pp, ( void * )packet.data, ( packet.header.size - sizeof( CPacketHeader ) ) );

                    PetList.push_back( pp );
                }
                    
                    break;
                    
                case 1038:
                {
                    last_ping = time( 0 );
                    
                    if ( !loggedIn )
                        loggedIn = true;
                }
                    
                    break;
                    
                case 1043: 
                {
                    // Has more data that needs to be reversed
                    /* Don't want to write a class for this quite yet, because
                     * I want to see if this packet is used when a player changes
                     * their actual body in the reborn room, or if it's just
                     * for disguising as a pet.
                     */
                    int     id      = *( int * )packet.data;
                    Player  *player = gameMap->find_player( id );
                    
                    if ( player->m_id == -1 )
                    {
                        delete player;
                        break;
                    }
                    
                    //printf( "* %s has disguised as a pet.\n", player->m_name );
                }
                    break;
					
                case 1050:
                    /* Why don't i have anything for this packet? It's the first
                     * Received packet from the game server...
                     */
                    break;
                    
                case 2030:
                {
                    NpcInfoPacket   *info   = new NpcInfoPacket( packet );
                    Npc             *npc    = new Npc( info );
                    
                    gameMap->add_npc( npc );
                    
                    //printf( "* Added NPC: %s (id=%d)(type=%d)\n", npc->m_name, npc->m_id, npc->m_type );
                    
                    delete info;
                    delete npc;
                }
                    
                    break;
                    
                case 2031:
                {
                    NpcUpdatePacket *update = new NpcUpdatePacket( packet );
                    
                    if ( update->m_action == 3 )
                        gameMap->del_npc( update->m_npcID );
                    
                    delete update;
                }
                    
                    break;
                    
                case 2033:
                {
                    NpcDialoguePacket *dialog = new NpcDialoguePacket( packet );
                    dialogue->process( dialog );
                    
                    delete dialog;
                }
                    
                    break;
					
                default:
                    /*printf( "ID: %d Length: %d Data:\n", packet.header.id, packet.header.size );
                    hexdump( ( void * )packet.data, ( packet.header.size - sizeof( CPacketHeader ) ) );
                    printf( "\n");*/
                    break;
            }
        }
    }
    
    return 1;
}
Exemplo n.º 22
0
void Game::play()
{
	long maxp = gameSettings->getMaxp();
	long maxl = gameSettings->getMaxl();
	long maxg = gameSettings->getMaxg();
	int level = gameSettings->getLevel();
	int preview = gameSettings->getPreview();
	int stat = gameSettings->getStat();
	int size = gameSettings->getSize();
	int sliding = gameSettings->getSliding();
	int delay = gameSettings->getDelay();
	int animate = gameSettings->getAnimate();
	int exit = gameSettings->getExit();
	int pieceStartX = gameSettings->getPieceStartX();
	int frameRateDelay = gameSettings->getFrameRateDelay();
	int nextPiece = 0;
	int viewBoard = gameSettings->getViewBoard();
	int stepMode = gameSettings->getStepMode();
	milisec1 = GetTickCount();
	milisec2 = GetTickCount();
	seconds = time(NULL);

	if (strlen(gameSettings->getWgameFilename()) != 0)
	{
		if (wGameFile.open(gameSettings->getWgameFilename()))
		{
			cout << "Could not open the file  \"" << gameSettings->getWgameFilename() << "\"" << endl;

			return;
		}
	}

	if (strlen(gameSettings->getRgameFilename()) != 0)
	{
		if (rGameFile.open(gameSettings->getRgameFilename()))
		{
			cout << "Could not open the file  \"" << gameSettings->getRgameFilename() << "\"" << endl;

			return;
		}
	}

	if (strlen(gameSettings->getWhtmlFilename()) != 0)
	{
		wHtml.open(gameSettings->getWhtmlFilename());

		if (!wHtml.good())
		{
			cout << "Could not open the file  \"" << gameSettings->getWhtmlFilename() << "\"" << endl;

			return;
		}
	}

  board = new Board(gameSettings->getWidth(), gameSettings->getHeight(), sliding, pieceStartX);

	Piece setStaticInitializersPiece(board, 1, sliding, 1);

	Player *player = new Player(board);

	Random random = Random(gameSettings->getSeed());
	GameInfo gameInfo(maxCntblockstat);

  writeTmpFile(board);

	double equity = player->evaluate();
	double maxDiff = 0;

	int pieces[10];

	if (preview > 1)
		pieces[0] = random.getRandomP();

	pieces[1] = 0;
	pieces[2] = 0;
	pieces[3] = 0;
	pieces[4] = 0;
	pieces[5] = 0;
	pieces[6] = 0;
	pieces[7] = 0;
	pieces[8] = 0;
	pieces[9] = 0;

	if (wGameFile.isOpen())
	{
		// 1. Version of the file
		wGameFile.writeShort(1);													// # Version (short)
		
		// 2. Header
		wGameFile.writeShort(DATA_HEADER);								// # Type of block
		wGameFile.writeShort(1);													// # Version
		wGameFile.writeShort(gameSettings->getWidth());		// # Width (short)
		wGameFile.writeShort(gameSettings->getHeight());	// # Height (short)
		wGameFile.writeInt(gameSettings->getSeed());			// # Seed (int)
		wGameFile.writeByte(gameSettings->getLevel());		// # Level (byte)
		wGameFile.writeByte(gameSettings->getPreview());	// # Preview (byte)
		wGameFile.writeByte(pieces[0]);      							// # Piece (byte)
	}

	while ((maxg==0 && maxl==0 && maxp==0) || 
		     ((maxg > 0 && games < maxg) ||
		      (maxl > 0 && totalLines < maxl) ||
				  (maxp > 0 && totalPieces < maxp)))
	{
		if (exit == 1 || gameSettings->getExit() == 1)
			break;

		//-------------------------------------------
		if (stepMode != gameSettings->getStepMode()) {
			stepMode = gameSettings->getStepMode();
			initTime();
		}
		
		if (level != gameSettings->getLevel()) {
			level = gameSettings->getLevel();
			initTime();
		}

		if (sliding != gameSettings->getSliding())
		{
			sliding = gameSettings->getSliding();
			board->setSliding(sliding);
			initTime();
		}

		if (preview != gameSettings->getPreview())
		{
			preview = gameSettings->getPreview();

			if (preview == 1)
				pieces[1] = 0;
			else
			{
				if (nextPiece == 0)
					nextPiece = pieces[1] = random.getRandomP();
				else
					pieces[1] = nextPiece;
			}

			initTime();
		}

		if (animate != gameSettings->getAnimate()) {
			animate = gameSettings->getAnimate();
			initTime();
		}

		if (delay != gameSettings->getDelay()) {
			delay = gameSettings->getDelay();
			initTime();
		}

		if (frameRateDelay != gameSettings->getFrameRateDelay()) {
			frameRateDelay = gameSettings->getFrameRateDelay();
			initTime();
		}

		if (viewBoard != gameSettings->getViewBoard()) {
			viewBoard = gameSettings->getViewBoard();
			initTime();
		}

		while (gameSettings->isPause())
			::Sleep(10);

		if (board->getWidth() != gameSettings->getWidth())
		{
			delete board;
			pieceStartX = gameSettings->getPieceStartX();
			board = new Board(gameSettings->getWidth(), gameSettings->getHeight(), sliding, pieceStartX);
			Piece setStaticInitializersPiece(board, 1, sliding, 1);			
		}
		//-------------------------------------------

		if (preview > 1)
			nextPiece = pieces[1] = random.getRandomP();
		else
			pieces[0] = random.getRandomP();

		if (wGameFile.isOpen())
			wGameFile.writeByte(pieces[1]);									// # Piece

		Piece bestPiece(board, pieces[0]);


		gameObserverList.notify(board, 
														&gameInfo, 
														pieces[0], 
														pieces[1], 
														1, 
														milisec1,
														milisec2,
														cntblockstat, 
														games,
														cntPieces,
														cntLines,
														totalMoves,
														totalSlided,
														totalLines,
														totalLines2,
														totalPieces,
														totalPieces2,
														minLines,
														maxLines,
														linesPerGame);


		if (!animate)
			::Sleep(delay*10);

		int playAgain;
		Move *bestMove;
		MoveList *moveList;

		do
		{
			playAgain = 0;
			gameSettings->setIsThinking();

			if (animate != gameSettings->getAnimate()) {
				animate = gameSettings->getAnimate();
				initTime();
			}

			bestMove = player->play(pieces, level, preview, animate, &gameObserverList);

			if (bestMove > 0)
				bestPiece.set(bestMove->getV(), bestMove->getX(), bestMove->getY(), bestMove->getClearedLines());

			gameSettings->setIsNotThinking();

			moveList = board->getMoveList(level);

			gameObserverList.notify(moveList);

			while (gameSettings->isStepModeOn() && gameSettings->isStepWait())
			{
				if (level != gameSettings->getLevel()) {
					level = gameSettings->getLevel();
					initTime();
					playAgain = 1;
					break;
				}

				if (preview != gameSettings->getPreview())
				{
					preview = gameSettings->getPreview();

					if (preview == 1)
						pieces[1] = 0;
					else
					{
						if (nextPiece == 0)
							nextPiece = pieces[1] = random.getRandomP();
						else
							pieces[1] = nextPiece;
					}

					initTime();
					playAgain = 1;

					gameObserverList.notify(board, 
																	&gameInfo, 
																	pieces[0], 
																	pieces[1], 
																	1, 
																	milisec1,
																	milisec2,
																	cntblockstat, 
																	games,
																	cntPieces,
																	cntLines,
																	totalMoves,
																	totalSlided,
																	totalLines,
																	totalLines2,
																	totalPieces,
																	totalPieces2,
																	minLines,
																	maxLines,
																	linesPerGame);



					break;
				}

				if (sliding != gameSettings->getSliding() && bestMove > 0)
				{
					sliding = gameSettings->getSliding();
					board->setSliding(sliding);

					initTime();
					playAgain = 1;
					break;
				}

				::Sleep(10);
			}
		} while (playAgain);

		if (gameSettings->isStepModeOn())
			gameSettings->setStepWait();

		if (!animate && bestMove > 0)
		{
			bestPiece.setPiece();

			if (bestPiece.getClearedLines() > 0)
				board->clearLines(bestPiece.getY(), bestPiece.getHeight());
		}

		Move *move;
		int index = 0;

		int length = moveList->getLength();

		totalMoves += length;

		if (animate && bestMove > 0)
		{
			// Animate the moves.
			MovePath *movePath = board->getMovePath(level);
			MovePathStep *s = movePath->getPath(bestMove->getV(), bestMove->getX(), bestMove->getY());

			int skipFirst = 0;

			int prevy = -1;

			while (s > 0)
			{
				//----
				// Calculate the number of steps for the current line (y value).
				MovePathStep *s1 = s;
				int y1 = s1->y;
				int cnt;

				if (prevy != y1)
				{
					cnt = 0;

					while (s1 > 0 && s1->y == y1) {
						cnt++;
						s1 = s1->next;
					}
					prevy = y1;
				}
				//----
				
				if (animate != gameSettings->getAnimate())
					break;

				if (delay != gameSettings->getDelay())
					delay = gameSettings->getDelay();

				int v = s->v;
				int x = s->x;
				int y = s->y;

				Piece piece(board, bestPiece.getP());
				piece.setPiece(v, x, y);

				if (skipFirst)
					gameObserverList.notify(board, 
																	&gameInfo, 
																	pieces[0], 
																	pieces[1], 
																	0, 
																	milisec1,
																	milisec2,
																	cntblockstat, 
																	games,
																	cntPieces,
																	cntLines,
																	totalMoves,
																	totalSlided,
																	totalLines,
																	totalLines2,
																	totalPieces,
																	totalPieces2,
																	minLines,
																	maxLines,
																	linesPerGame);

				if (gameSettings->isSlidingOn())
					::Sleep((double)delay / cnt);
				else
					::Sleep((double)delay);

				piece.clearPiece();
				skipFirst = 1;
				s = s->next;

				while (gameSettings->isPause())
					::Sleep(10);
			}

			bestPiece.setPiece();

			if (bestPiece.getClearedLines() > 0)
			{
				int clearedLinesBits = board->getClearedLines(bestPiece.getY(), bestPiece.getHeight());

				for (int n=0; n<4; n++)
				{
					board->flashLines(bestPiece.getY(), bestPiece.getHeight(), clearedLinesBits);
					
					if (n<3)
					{
						gameObserverList.notify(board, 
																		&gameInfo, 
																		pieces[0], 
																		pieces[1], 
																		0, 
																		milisec1,
																		milisec2,
																		cntblockstat, 
																		games,
																		cntPieces,
																		cntLines,
																		totalMoves,
																		totalSlided,
																		totalLines,
																		totalLines2,
																		totalPieces,
																		totalPieces2,
																		minLines,
																		maxLines,
																		linesPerGame);

						if (delay > 0)
						{
							if (delay >= 50)
								::Sleep(150);
							else
								::Sleep(150-(50-delay)*2);
						}
					}
				}

				board->clearLines(bestPiece.getY(), bestPiece.getHeight());
			}
		}

		cntPieces++;
		totalPieces++;
		
		if (bestMove > 0)
			totalSlided += bestMove->isSlided();

		// Log the moves
		if (wGameFile.isOpen())
		{
			wGameFile.writeShort(length);											// # Number of legal moves.
			wGameFile.writeByte(bestPiece.getV());						// # V
			wGameFile.writeShort(bestPiece.getX());						// # X
			wGameFile.writeShort(bestPiece.getY());						// # Y

			move = moveList->getFirstMove();

			while (move != 0)
			{																									// Move:
				wGameFile.writeByte(move->getV());							// # V
				wGameFile.writeShort(move->getX());							// # X
				wGameFile.writeShort(move->getY());							// # Y

				for (int i=preview; i<=level; i++)							// Equity (e.g):
					wGameFile.writeFloat(move->getEquity(i));			// L2, L3, L4

				move = moveList->getNextMove();
			}
		}

		if (preview > 1)
			pieces[0] = pieces[1];

  	int clearedLines = bestPiece.getClearedLines();

  	if (bestMove == 0) 
		{
  		games++;
  		
			linesPerGame = totalLines/games;
		}
		else
		{
			cntLines += clearedLines;
			totalLines += clearedLines;

			cntBlock += 4 - clearedLines * board->getWidth();

			if (DEBUG == 0)
			{
				int xxx = cntBlock/4;
				if (xxx < maxCntblockstat)
					cntblockstat[xxx]++;
			}
		}

  	if (cntLines > maxLines)
  		maxLines = cntLines;

		if (bestMove == 0)
		{
  		if (cntLines < minLines || minLines==-1)
  			minLines = cntLines;
			
			cntBlock = 0;
			cntPieces = 0;
  		cntLines = 0;
		  board->clear();
			pieces[0] = random.getRandomP();
		}
	}

	delete board;
	delete player;

	if (wGameFile.isOpen())
	{
		wGameFile.writeByte(END_PIECE);				// # Piece
		wGameFile.close();
	}

	if (rGameFile.isOpen() && strlen(gameSettings->getWhtmlFilename()) > 0)
	{
		readGame(maxp, size);
		rGameFile.close();
	}

	gameSettings->setExit(2);
}
Exemplo n.º 23
0
void initMetricsData( Metrics *metrics )  /*  metrics struct to initialize */
{   /*  begin initMetricsData() */
    Time temp;   /*  variable used to find current time          */

    assert( metrics );

    /*
     *  Initialize timer
     */
    initTime();

    /*
     *  Setup timing marks for metric collection
     */
    temp = getTime();
    metrics->totalTime  = temp;
    metrics->inputTime  = temp;
    metrics->outputTime = temp;
    
    /*
     *  Set initial values for each command metric.  The statistical values for 
     *  the worst, best, average, and standard deviation values are set to 
     *  "impossible" values which should be easily noticed if unchanged and
     *  output as a metric result.
     */
    metrics->insertCommandMetric.lastTimeMark   = MINIMUM_VALUE_OF_TIME;
    metrics->insertCommandMetric.numOfCommands  = 0;
    metrics->insertCommandMetric.sum            = 0.0;
    metrics->insertCommandMetric.sumSquares     = 0.0;
    metrics->insertCommandMetric.worst          = MINIMUM_VALUE_OF_TIME;
    metrics->insertCommandMetric.best           = MAXIMUM_VALUE_OF_TIME;
    metrics->insertCommandMetric.avg            = MINIMUM_VALUE_OF_FLOAT;
    metrics->insertCommandMetric.deviation      = MINIMUM_VALUE_OF_FLOAT;

    metrics->queryCommandMetric.lastTimeMark    = MINIMUM_VALUE_OF_TIME;
    metrics->queryCommandMetric.numOfCommands   = 0;
    metrics->queryCommandMetric.sum             = 0.0;
    metrics->queryCommandMetric.sumSquares      = 0.0;
    metrics->queryCommandMetric.worst           = MINIMUM_VALUE_OF_TIME;
    metrics->queryCommandMetric.best            = MAXIMUM_VALUE_OF_TIME;
    metrics->queryCommandMetric.avg             = MINIMUM_VALUE_OF_FLOAT;
    metrics->queryCommandMetric.deviation       = MINIMUM_VALUE_OF_FLOAT;

    metrics->deleteCommandMetric.lastTimeMark   = MINIMUM_VALUE_OF_TIME;
    metrics->deleteCommandMetric.numOfCommands  = 0;
    metrics->deleteCommandMetric.sum            = 0.0;
    metrics->deleteCommandMetric.sumSquares     = 0.0;
    metrics->deleteCommandMetric.worst          = MINIMUM_VALUE_OF_TIME;
    metrics->deleteCommandMetric.best           = MAXIMUM_VALUE_OF_TIME;
    metrics->deleteCommandMetric.avg            = MINIMUM_VALUE_OF_FLOAT;
    metrics->deleteCommandMetric.deviation      = MINIMUM_VALUE_OF_FLOAT;

    /*
     *  The routine updateMetricsData() expects the lastCommand field of the 
     *  Metric structure to indicate which command metric should be updated.  
     *  The value is set to INVALID for initialization, but should be set before
     *  the first call to updateMetricsData().
     */
    metrics->lastCommand = INVALID;

    return;
}   /*  end of initMetricsData()    */
Exemplo n.º 24
0
int EncodeMonitoringFile()
{
   fit::Encode encode;
   std::fstream file;

   time_t current_time_unix = time(0);
   fit::DateTime initTime(current_time_unix);

   file.open("ExampleMonitoringFile.fit", std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);

   if (!file.is_open())
   {
      printf("Error opening file ExampleMonitoringFile.fit\n");
      return -1;
   }

   encode.Open(file);

   fit::FileIdMesg fileIdMesg; // Every FIT file requires a File ID message
   fileIdMesg.SetType(FIT_FILE_MONITORING_B);
   fileIdMesg.SetManufacturer(FIT_MANUFACTURER_DYNASTREAM);
   fileIdMesg.SetProduct(1001);
   fileIdMesg.SetSerialNumber(54321);

   encode.Write(fileIdMesg);

   fit::DeviceInfoMesg deviceInfoMesg;
   deviceInfoMesg.SetTimestamp(initTime.GetTimeStamp()); // Convert to FIT time and write timestamp.
   deviceInfoMesg.SetBatteryStatus(FIT_BATTERY_STATUS_GOOD);

   encode.Write(deviceInfoMesg);

   fit::MonitoringMesg monitoringMesg;

   // By default, each time a new message is written the Local Message Type 0 will be redefined to match the new message.
   // In this case,to avoid having a definition message each time there is a DeviceInfoMesg, we can manually set the Local Message Type of the MonitoringMessage to '1'.
   // By doing this we avoid an additional 7 definition messages in our FIT file.
   monitoringMesg.SetLocalNum(1);

   monitoringMesg.SetTimestamp(initTime.GetTimeStamp()); // Initialise Timestamp to now
   monitoringMesg.SetCycles(0); // Initialise Cycles to 0
   for(int i = 0; i < 4; i++) // This loop represents 1/6 of a day
   {
      for(int j = 0; j < 4; j++) // Each one of these loops represent 1 hour
      {
         fit::DateTime walkingTime(current_time_unix);
         monitoringMesg.SetTimestamp(walkingTime.GetTimeStamp());
         monitoringMesg.SetActivityType(FIT_ACTIVITY_TYPE_WALKING); // By setting this to WALKING, the Cycles field will be interpretted as Steps
         monitoringMesg.SetCycles(monitoringMesg.GetCycles() + (rand()%1000+1)); // Cycles are accumulated (i.e. must be increasing)
         encode.Write(monitoringMesg);
         current_time_unix += (time_t)(3600); //Add an hour to our contrieved timestamp
      }
      fit::DateTime statusTime(current_time_unix);
      deviceInfoMesg.SetTimestamp(statusTime.GetTimeStamp());
      deviceInfoMesg.SetBatteryStatus(FIT_BATTERY_STATUS_GOOD);
      encode.Write(deviceInfoMesg);

   }

   if (!encode.Close())
   {
      printf("Error closing encode.\n");
      return -1;
   }
   file.close();

   printf("Encoded FIT file ExampleMonitoringFile.fit.\n");
   return 0;
}
Exemplo n.º 25
0
 Timer() {
   initTime();
 }
Exemplo n.º 26
0
int main()
{
	/* Perform processor initialization */

	sysinit();	
	
	printf("\nRunning the SolderTermo_v2 project.\r\n");
	
	initTime();

	initNVRAM();
	
	readNVRAM();	
	
	printf("Version %hd\tCRC %hd\r\n", nvram.Version, nvram.nvramCrc);

	initDisplay();

	//initMAX31855();
	initThermocoupleADC();

	initPowerPWM();

	initHMI();

	initButtons();

	initStateMachine();

	int fastLog = 0;
	while(1)
	{
		if (fastLog)
			printf("%hd\t%hd\r\n", vram.ADCVal, vram.CurrTemp);
		else
			printf("%hd\t%hd\t%hd\t%hd\t%hd\t%hd\r\n", vram.CurrTemp / 10, nvram.Tsp, vram.PWM_Sp,
					nvram.Kp, nvram.Ki, nvram.Kd);


		if ( UART_CharPresent(UART2) )
		{
			uint8_t c;
			uint8_t charNo = 0;
			memset(uartBuff, 0, UART_MAX_BUFF);
			printf("Finish your input by ENTER\r\n");
			printf("\r\n");
			do
			{
				c = uartBuff[charNo++] = UART_GetChar(UART2); // wait for char to come
				UART_PutChar(UART2, c);
				WAIT_Waitms(50);
			}
			while ( c != '\r' && charNo < UART_MAX_BUFF );

			switch(uartBuff[0])
			{
				case 'f': fastLog = 1; break;  // fast logging
				case 's': fastLog = 0; break;  // slow logging
				case 'p': nvram.Kp = atoi(uartBuff + 1); break;  // fast logging
				case 'i': nvram.Ki = atoi(uartBuff + 1); break;  // slow logging
				case 'd': nvram.Kd = atoi(uartBuff + 1); break;  // slow logging
			}
		}

		WAIT_Waitms(fastLog ? 20 : 200);
	}

	return 0; // should never come here
}
Exemplo n.º 27
0
Boolean doInit(PtpClock *ptpClock)
{
  DBG("manufacturerIdentity: %s\n", MANUFACTURER_ID);
  
  /* initialize networking */
  netShutdown(ptpClock);
  if(!netInit(ptpClock))
  {
    ERROR("failed to initialize network\n");
    toState(PTP_FAULTY, ptpClock);
    return FALSE;
  }

  /* initialize timing, may fail e.g. if timer depends on hardware */
  if(!initTime(ptpClock))
  {
    ERROR("failed to initialize timing\n");
    toState(PTP_FAULTY, ptpClock);
    return FALSE;
  }

  switch (ptpClock->runTimeOpts.time) {
  case TIME_SYSTEM:
  case TIME_SYSTEM_LINUX_HW:
  case TIME_SYSTEM_LINUX_SW:
      /*
       * send time stamp will be returned to socket when available,
       * either via IP_MULTICAST_LOOP or SIOCSHWTSTAMP + error queue
       */
      ptpClock->delayedTiming = FALSE;
      break;
  default:
      /* ask for time stamp shortly after sending */
      ptpClock->delayedTiming = TRUE;
      break;
  }

  /* initialize other stuff */
  initData(ptpClock);
  initTimer();
  initClock(ptpClock);
  m1(ptpClock);
  msgPackHeader(ptpClock->msgObuf, ptpClock);
  
  DBG("sync message interval: %d\n", PTP_SYNC_INTERVAL_TIMEOUT(ptpClock->sync_interval));
  DBG("clock identifier: %s\n", ptpClock->clock_identifier);
  DBG("256*log2(clock variance): %d\n", ptpClock->clock_variance);
  DBG("clock stratum: %d\n", ptpClock->clock_stratum);
  DBG("clock preferred?: %s\n", ptpClock->preferred?"yes":"no");
  DBG("bound interface name: %s\n", ptpClock->runTimeOpts.ifaceName);
  DBG("communication technology: %d\n", ptpClock->port_communication_technology);
  DBG("uuid: %02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx\n",
    ptpClock->port_uuid_field[0], ptpClock->port_uuid_field[1], ptpClock->port_uuid_field[2],
    ptpClock->port_uuid_field[3], ptpClock->port_uuid_field[4], ptpClock->port_uuid_field[5]);
  DBG("PTP subdomain name: %s\n", ptpClock->subdomain_name);
  DBG("subdomain address: %hhx.%hhx.%hhx.%hhx\n",
    ptpClock->subdomain_address[0], ptpClock->subdomain_address[1],
    ptpClock->subdomain_address[2], ptpClock->subdomain_address[3]);
  DBG("event port address: %hhx %hhx\n",
    ptpClock->event_port_address[0], ptpClock->event_port_address[1]);
  DBG("general port address: %hhx %hhx\n",
    ptpClock->general_port_address[0], ptpClock->general_port_address[1]);
  
  toState(PTP_LISTENING, ptpClock);
  return TRUE;
}