static void turnTest(){ AI ar = AI("Arun", 5); Deck inPlay; inPlay.initialize(); Table blds; for (int i = 0; i < 20; ++i) { ar.stockPile.push(inPlay.draw(blds.getOutofPlay())); } ar.takeTurn(inPlay, blds); }
void TempSummon::InitSummon() { Unit* owner = GetSummoner(); if (owner) { if (owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsAIEnabled) owner->ToCreature()->AI()->JustSummoned(this); if (IsAIEnabled) AI()->IsSummonedBy(owner); } }
void C_Rat::Update() { AI(); Move(); DeadCount(); }
/*-----------------------------------------------*/ void Chicken::update(int ms) { /* PURPOSE: Control chicken movements based on probabilities RECEIVES: diff_time - milliseconds since last frame RETURNS: REMARKS: */ AnimatedSprite::update(ms); AI(); }
Game::Game() { // Collision stuff phys = new PhysicsEngine(Vec3(-1000, -1000, -1000), Vec3(1000, 1000, 1000)); // Player initializations player = new Player(Vec3(0, 2, 0), Vec3(0, 0, 0), Vec3(0, 0, 0), 10); phys->add(player); this->ai = AI(); }
void TempSummon::InitSummon() { Unit* owner = GetSummoner(); if (owner) { if (owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsAIEnabled) owner->ToCreature()->AI()->JustSummoned(this); } // Xinef: Allow to call this hook when npc is summoned by gameobject, in this case pass this as summoner to avoid possible null checks if (IsAIEnabled) AI()->IsSummonedBy(owner); }
// \brief Terminate the location range for all variables, described by registers // clobbered by @MI. static void clobberRegisterUses(RegDescribedVarsMap &RegVars, const MachineInstr &MI, const TargetRegisterInfo *TRI, DbgValueHistoryMap &HistMap) { for (const MachineOperand &MO : MI.operands()) { if (!MO.isReg() || !MO.isDef() || !MO.getReg()) continue; for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid(); ++AI) { unsigned RegNo = *AI; clobberRegisterUses(RegVars, RegNo, HistMap, MI); } } }
void TemporarySummon::UnSummon() { CombatStop(); if (m_linkedToOwnerAura & TEMPSUMMON_LINKED_AURA_REMOVE_OWNER) RemoveAuraFromOwner(); if (GetSummonerGuid().IsCreatureOrVehicle()) { if (Creature* sum = GetMap()->GetCreature(GetSummonerGuid())) if (sum->AI()) sum->AI()->SummonedCreatureDespawn(this); } else if (GetSummonerGuid().IsPlayer()) // if player that summoned this creature was MCing it, uncharm if (Player* player = GetMap()->GetPlayer(GetSummonerGuid())) if (player->GetMover() == this) player->Uncharm(); if (AI()) AI()->SummonedCreatureDespawn(this); AddObjectToRemoveList(); }
int player_turn( int player ) { unsigned int x, y; if(player == 0) { write_screen("Computer will start playing"); AI(); moves++; player = 1; } if(player == 1) { write_screen("You will start to play"); puts("Insert the cordinates like this: x y"); scanf("%d %d", &x, &y); if(table[y][x] == 'O' || table[y][x] == 'X') { do { write_screen("*This position is already checked, please choose another."); scanf("%d %d", &x, &y); if(table[y][x] != 'O' && table[y][x] != 'X') { table[y][x] = 'O'; return false; } } while(true); } else { table[y][x] = 'O'; } moves++; player = 0; } return player; }
int main() { #ifdef debug printf("%X %X\n",&player,main); #endif do { printf("请选择走棋次序。\n输入1先走,或者-1后走。"); scanf("%d",&player); } while(player!=1&&player!=-1); int pl; //落子位置 DrawField(); int i; for(i=1;i<=9;i++) { if(isWin())break; if(player==1) { printf("请输入落子位置:"); scanf("%d",&pl); if(pl>9||pl<1||field[pl]!=0) { printf("输入错误,无此格子或格内已有子\n请重新输入:"); i--; DrawField(); continue; } else { field[pl]=player; player=-player; if(isWin())break; } } else AI(); } if(i>=9)printf("平局\n"); else printf("赢家是%d\n",sym(-player)); getchar();getchar(); //延迟窗口关闭 return 0; }
void Enemy::Update() { if(hp_ <= 0) { living_ = false; if(aitype_ == WANDERER) theplayer->AddToScore(25); if(aitype_ == PREDATOR) theplayer->AddToScore(10); if(aitype_ == PREDATOR_IMMUNE) theplayer->AddToScore(50); if(aitype_ == BOSS) theplayer->AddToScore(100); } AI(); }
void TempSummon::UnSummon(uint32 msTime) { if (msTime) { ForcedUnsummonDelayEvent* pEvent = new ForcedUnsummonDelayEvent(*this); m_Events.AddEvent(pEvent, m_Events.CalculateTime(msTime)); return; } // Custom operations switch(GetEntry()) { // Force of Nature case 36070: // If not it's directly handled in JustDied if(IsAIEnabled && isAlive()) { AI()->JustDied(this); } break; } //ASSERT(!isPet()); if (isPet()) { ((Pet*)this)->Remove(PET_SAVE_NOT_IN_SLOT); ASSERT(!IsInWorld()); return; } Unit* owner = GetSummoner(); if (owner && owner->GetTypeId() == TYPEID_UNIT && owner->ToCreature()->IsAIEnabled) owner->ToCreature()->AI()->SummonedCreatureDespawn(this); AddObjectToRemoveList(); }
static int ambsample( /* initial ambient division sample */ AMBHEMI *hp, int i, int j, int n ) { AMBSAMP *ap = &ambsam(hp,i,j); RAY ar; int hlist[3], ii; double spt[2], zd; /* generate hemispherical sample */ /* ambient coefficient for weight */ if (ambacc > FTINY) setcolor(ar.rcoef, AVGREFL, AVGREFL, AVGREFL); else copycolor(ar.rcoef, hp->acoef); if (rayorigin(&ar, AMBIENT, hp->rp, ar.rcoef) < 0) return(0); if (ambacc > FTINY) { multcolor(ar.rcoef, hp->acoef); scalecolor(ar.rcoef, 1./AVGREFL); } hlist[0] = hp->rp->rno; hlist[1] = j; hlist[2] = i; multisamp(spt, 2, urand(ilhash(hlist,3)+n)); resample: SDsquare2disk(spt, (j+spt[1])/hp->ns, (i+spt[0])/hp->ns); zd = sqrt(1. - spt[0]*spt[0] - spt[1]*spt[1]); for (ii = 3; ii--; ) ar.rdir[ii] = spt[0]*hp->ux[ii] + spt[1]*hp->uy[ii] + zd*hp->rp->ron[ii]; checknorm(ar.rdir); /* avoid coincident samples */ if (!n && ambcollision(hp, i, j, ar.rdir)) { spt[0] = frandom(); spt[1] = frandom(); goto resample; /* reject this sample */ } dimlist[ndims++] = AI(hp,i,j) + 90171; rayvalue(&ar); /* evaluate ray */ ndims--; zd = raydistance(&ar); if (zd <= FTINY) return(0); /* should never happen */ multcolor(ar.rcol, ar.rcoef); /* apply coefficient */ if (zd*ap->d < 1.0) /* new/closer distance? */ ap->d = 1.0/zd; if (!n) { /* record first vertex & value */ if (zd > 10.0*thescene.cusize + 1000.) zd = 10.0*thescene.cusize + 1000.; VSUM(ap->p, ar.rorg, ar.rdir, zd); copycolor(ap->v, ar.rcol); } else { /* else update recorded value */ hp->acol[RED] -= colval(ap->v,RED); hp->acol[GRN] -= colval(ap->v,GRN); hp->acol[BLU] -= colval(ap->v,BLU); zd = 1.0/(double)(n+1); scalecolor(ar.rcol, zd); zd *= (double)n; scalecolor(ap->v, zd); addcolor(ap->v, ar.rcol); } addcolor(hp->acol, ap->v); /* add to our sum */ return(1); }
static void ambHessian( /* anisotropic radii & pos. gradient */ AMBHEMI *hp, FVECT uv[2], /* returned */ float ra[2], /* returned (optional) */ float pg[2] /* returned (optional) */ ) { static char memerrmsg[] = "out of memory in ambHessian()"; FVECT (*hessrow)[3] = NULL; FVECT *gradrow = NULL; FVECT hessian[3]; FVECT gradient; FFTRI fftr; int i, j; /* be sure to assign unit vectors */ VCOPY(uv[0], hp->ux); VCOPY(uv[1], hp->uy); /* clock-wise vertex traversal from sample POV */ if (ra != NULL) { /* initialize Hessian row buffer */ hessrow = (FVECT (*)[3])malloc(sizeof(FVECT)*3*(hp->ns-1)); if (hessrow == NULL) error(SYSTEM, memerrmsg); memset(hessian, 0, sizeof(hessian)); } else if (pg == NULL) /* bogus call? */ return; if (pg != NULL) { /* initialize form factor row buffer */ gradrow = (FVECT *)malloc(sizeof(FVECT)*(hp->ns-1)); if (gradrow == NULL) error(SYSTEM, memerrmsg); memset(gradient, 0, sizeof(gradient)); } /* compute first row of edges */ for (j = 0; j < hp->ns-1; j++) { comp_fftri(&fftr, hp, AI(hp,0,j), AI(hp,0,j+1)); if (hessrow != NULL) comp_hessian(hessrow[j], &fftr, hp->rp->ron); if (gradrow != NULL) comp_gradient(gradrow[j], &fftr, hp->rp->ron); } /* sum each row of triangles */ for (i = 0; i < hp->ns-1; i++) { FVECT hesscol[3]; /* compute first vertical edge */ FVECT gradcol; comp_fftri(&fftr, hp, AI(hp,i,0), AI(hp,i+1,0)); if (hessrow != NULL) comp_hessian(hesscol, &fftr, hp->rp->ron); if (gradrow != NULL) comp_gradient(gradcol, &fftr, hp->rp->ron); for (j = 0; j < hp->ns-1; j++) { FVECT hessdia[3]; /* compute triangle contributions */ FVECT graddia; double backg; backg = back_ambval(hp, AI(hp,i,j), AI(hp,i,j+1), AI(hp,i+1,j)); /* diagonal (inner) edge */ comp_fftri(&fftr, hp, AI(hp,i,j+1), AI(hp,i+1,j)); if (hessrow != NULL) { comp_hessian(hessdia, &fftr, hp->rp->ron); rev_hessian(hesscol); add2hessian(hessian, hessrow[j], hessdia, hesscol, backg); } if (gradrow != NULL) { comp_gradient(graddia, &fftr, hp->rp->ron); rev_gradient(gradcol); add2gradient(gradient, gradrow[j], graddia, gradcol, backg); } /* initialize edge in next row */ comp_fftri(&fftr, hp, AI(hp,i+1,j+1), AI(hp,i+1,j)); if (hessrow != NULL) comp_hessian(hessrow[j], &fftr, hp->rp->ron); if (gradrow != NULL) comp_gradient(gradrow[j], &fftr, hp->rp->ron); /* new column edge & paired triangle */ backg = back_ambval(hp, AI(hp,i+1,j+1), AI(hp,i+1,j), AI(hp,i,j+1)); comp_fftri(&fftr, hp, AI(hp,i,j+1), AI(hp,i+1,j+1)); if (hessrow != NULL) { comp_hessian(hesscol, &fftr, hp->rp->ron); rev_hessian(hessdia); add2hessian(hessian, hessrow[j], hessdia, hesscol, backg); if (i < hp->ns-2) rev_hessian(hessrow[j]); } if (gradrow != NULL) { comp_gradient(gradcol, &fftr, hp->rp->ron); rev_gradient(graddia); add2gradient(gradient, gradrow[j], graddia, gradcol, backg); if (i < hp->ns-2) rev_gradient(gradrow[j]); } } } /* release row buffers */ if (hessrow != NULL) free(hessrow); if (gradrow != NULL) free(gradrow); if (ra != NULL) /* extract eigenvectors & radii */ eigenvectors(uv, ra, hessian); if (pg != NULL) { /* tangential position gradient */ pg[0] = DOT(gradient, uv[0]); pg[1] = DOT(gradient, uv[1]); } }
void STATE_PLAYING_LOOP() { while (SDL_PollEvent(&Application.e)) { switch (Application.e.type) { case SDL_KEYDOWN: switch (Application.e.key.keysym.sym) { case SDLK_ESCAPE: if ((SDL_GetModState() & KMOD_CTRL) > 0) PROGRAM_SWITCH_STATE(STATE_MAIN_MENU); break; case SDLK_LEFT: KeyDown.Left = 1; break; case SDLK_RIGHT: KeyDown.Right = 1; break; case SDLK_UP: KeyDown.Up = 1; break; case SDLK_DOWN: KeyDown.Down = 1; break; case SDLK_PAGEUP: TownCreatePeasant(Match.SelectedTown); break; case SDLK_PAGEDOWN: TownCreateWarrior(Match.SelectedTown); break; case SDLK_c: Match.Viewport.X = Match.SelectedTown->Position.X * IMAGINARY_GRID_SIZE - Application.Output->w / 2; Match.Viewport.Y = Match.SelectedTown->Position.Y * IMAGINARY_GRID_SIZE - Application.Output->h / 2; break; default: break; } break; case SDL_KEYUP: switch (Application.e.key.keysym.sym) { case SDLK_LEFT: KeyDown.Left = 0; break; case SDLK_RIGHT: KeyDown.Right = 0; break; case SDLK_UP: KeyDown.Up = 0; break; case SDLK_DOWN: KeyDown.Down = 0; break; default: break; } break; case SDL_MOUSEMOTION: Application.Cursor.X = Application.e.motion.x; Application.Cursor.Y = Application.e.motion.y; break; case SDL_MOUSEBUTTONDOWN: { Town *it; for (it = Match.TOWNS->NEXT; it != NULL; it = it->NEXT) { if ( it->Position.X * IMAGINARY_GRID_SIZE - TOWN_TILE_SIZE / 2 - Match.Viewport.X < Application.e.button.x && it->Position.X * IMAGINARY_GRID_SIZE + TOWN_TILE_SIZE / 2 - Match.Viewport.X > Application.e.button.x && it->Position.Y * IMAGINARY_GRID_SIZE - TOWN_TILE_SIZE / 2 - Match.Viewport.Y < Application.e.button.y && it->Position.Y * IMAGINARY_GRID_SIZE + TOWN_TILE_SIZE / 2 - Match.Viewport.Y > Application.e.button.y ) { if (Application.e.button.button == SDL_BUTTON_LEFT) { if (it->Color == Match.PlayerColor) Match.SelectedTown = it; else Match.SelectedEnemyTown = it; } if (Application.e.button.button == SDL_BUTTON_RIGHT) { if (Match.SelectedTown->warriors >= UNIT_SIZE) { TownSendUnit(Match.SelectedTown, it); Match.SelectedEnemyTown = it; } } } } } break; default: break; } } /* ** MAIN CYCLE */ Town *t_it; Unit *u_it, *u_tmp; // faluk bejárása, alapvető játékdinamika for (t_it = Match.TOWNS->NEXT; t_it != NULL; t_it = t_it->NEXT) { t_it->resources += t_it->peasants * (PEASANT_PRODUCTION_PER_MIN / 60.0) / Application.LPS_CAP; t_it->resources -= t_it->warriors * (WARRIOR_CONSUPTION_PER_MIN / 60.0) / Application.LPS_CAP; t_it->PRODUCTION = t_it->peasants * PEASANT_PRODUCTION_PER_MIN - t_it->warriors * WARRIOR_CONSUPTION_PER_MIN; if (t_it->resources < 0) { if (t_it->warriors > 0) t_it->warriors--; else t_it->resources = 0; } if (t_it->peasants < 0) t_it->peasants = 0; } // egységek bejárása és vizsgálata u_it = Match.UNITS_BEGIN->NEXT; while (u_it != Match.UNITS_END) { if (u_it->ARRIVE <= Application.LastRun) { // megérkezett if (u_it->TO->Color == u_it->Color) { // saját színű faluba u_it->TO->warriors += UNIT_SIZE; } else { // ellenséges faluba if (u_it->TO->warriors >= UNIT_SIZE) { // több védő katona volt, mint ahány támadó u_it->TO->warriors -= UNIT_SIZE; } else { // kevesebb katona volt, mint ahány támadó if (u_it->TO->warriors * PEASANT_WARRIOR_RATIO + u_it->TO->peasants > PEASANT_WARRIOR_RATIO * UNIT_SIZE) { // ha parasztokkal több u_it->TO->warriors = 0; u_it->TO->peasants = (u_it->TO->warriors * PEASANT_WARRIOR_RATIO + u_it->TO->peasants - PEASANT_WARRIOR_RATIO * UNIT_SIZE); } else { // ha parasztokkal is kevesebb if (u_it->TO->Color == Match.PlayerColor && Match.SelectedTown == u_it->TO) { for (t_it = Match.TOWNS->NEXT; t_it != NULL && t_it->Color != Match.PlayerColor; t_it = t_it->NEXT); if (t_it != NULL) Match.SelectedTown = t_it; else Match.SelectedTown = NULL; } u_it->TO->peasants = u_it->TO->warriors = UNIT_SIZE / 2; u_it->TO->Color = u_it->Color; if (Match.SelectedEnemyTown == u_it->TO) Match.SelectedEnemyTown = NULL; } } } /* ** CHECK VICTORY/DEFEAT */ if (CheckPlayerVictory()) PROGRAM_SWITCH_STATE(STATE_VICTORY); if (CheckPlayerDefeat()) PROGRAM_SWITCH_STATE(STATE_DEFEAT); u_tmp = u_it->NEXT; u_it->PREV->NEXT = u_it->NEXT; u_it->NEXT->PREV = u_it->PREV; free(u_it); u_it = u_tmp; } else { u_it = u_it->NEXT; } } // mesterséges intelligencia minden egyes falun for (t_it = Match.TOWNS->NEXT; t_it != NULL; t_it = t_it->NEXT) { if (t_it->Color != Match.PlayerColor) AI(t_it); } /* ** RENDER */ // térképmozgatás if (KeyDown.Left) Match.Viewport.X -= VIEWPORT_MOVE_VALUE; if (KeyDown.Right) Match.Viewport.X += VIEWPORT_MOVE_VALUE; if (KeyDown.Up) Match.Viewport.Y -= VIEWPORT_MOVE_VALUE; if (KeyDown.Down) Match.Viewport.Y += VIEWPORT_MOVE_VALUE; // nézőpont beszorítása if (Match.Viewport.X < Match.VIEWPORT_MIN.X) Match.Viewport.X = Match.VIEWPORT_MIN.X; if (Match.Viewport.Y < Match.VIEWPORT_MIN.Y) Match.Viewport.Y = Match.VIEWPORT_MIN.Y; if (Match.Viewport.X > Match.VIEWPORT_MAX.X) Match.Viewport.X = Match.VIEWPORT_MAX.X; if (Match.Viewport.Y > Match.VIEWPORT_MAX.Y) Match.Viewport.Y = Match.VIEWPORT_MAX.Y; // fűkitöltés SDL_Rect rect; int x, y, t_y; x = (Match.Viewport.X % TOWN_TILE_SIZE + TOWN_TILE_SIZE) * -1; t_y = y = (Match.Viewport.Y % TOWN_TILE_SIZE + TOWN_TILE_SIZE) * -1; while (x < Application.Output->w) { y = t_y; while (y < Application.Output->h) { rect.x = x; rect.y = y; SDL_BlitSurface(Image.GRASS, NULL, Application.Output, &rect); y += TOWN_TILE_SIZE; } x += TOWN_TILE_SIZE; } // faluk megjelenítése t_it = Match.TOWNS; for (t_it = Match.TOWNS->NEXT; t_it != NULL; t_it = t_it->NEXT) { rect.x = t_it->Position.X * IMAGINARY_GRID_SIZE - TOWN_TILE_SIZE / 2 - Match.Viewport.X; rect.y = t_it->Position.Y * IMAGINARY_GRID_SIZE - TOWN_TILE_SIZE / 2 - Match.Viewport.Y; rect.w = TOWN_TILE_SIZE; rect.h = TOWN_TILE_SIZE; SDL_BlitSurface(Image.Town[t_it->Color], NULL, Application.Output, &rect); if (Match.SelectedTown == t_it) { rect.x = t_it->Position.X * IMAGINARY_GRID_SIZE - TOWN_TILE_SIZE / 2 - Match.Viewport.X; rect.y = t_it->Position.Y * IMAGINARY_GRID_SIZE - TOWN_TILE_SIZE / 2 - Match.Viewport.Y; SDL_BlitSurface(Image.SELECTED_TOWN_BORDER, NULL, Application.Output, &rect); } if (Match.SelectedEnemyTown == t_it) { rect.x = t_it->Position.X * IMAGINARY_GRID_SIZE - TOWN_TILE_SIZE / 2 - Match.Viewport.X; rect.y = t_it->Position.Y * IMAGINARY_GRID_SIZE - TOWN_TILE_SIZE / 2 - Match.Viewport.Y; SDL_BlitSurface(Image.SELECTED_ENEMY_TOWN_BORDER, NULL, Application.Output, &rect); } char chars[10]; sprintf(chars, "%d", t_it->peasants); rect.y = t_it->Position.Y * IMAGINARY_GRID_SIZE - Match.Viewport.Y + 33; rect.x = t_it->Position.X * IMAGINARY_GRID_SIZE - Match.Viewport.X + 25; TTF_RenderText_Outline(Application.Output, chars, Application.FONT, rect.x, rect.y, TextColor.WHITE, TextColor.BLACK); sprintf(chars, "%.0lf", t_it->resources); rect.y += 15; rect.x -= 48; TTF_RenderText_Outline(Application.Output, chars, Application.FONT, rect.x, rect.y, TextColor.WHITE, TextColor.BLACK); sprintf(chars, "%d", t_it->warriors); rect.y -= 92; rect.x -= 16; TTF_RenderText_Outline(Application.Output, chars, Application.FONT, rect.x, rect.y, TextColor.WHITE, TextColor.BLACK); } // egységek megjelenítése for (u_it = Match.UNITS_BEGIN->NEXT; u_it != Match.UNITS_END; u_it = u_it->NEXT) { double angle = atan2(u_it->TO->Position.Y - u_it->FROM->Position.Y, u_it->TO->Position.X - u_it->FROM->Position.X); double movement = (double)(Application.LastRun - u_it->LEAVE) / UNIT_MARCHING_TIME; double x = cos(angle) * movement; double y = sin(angle) * movement; SDL_Rect r; r.x = (x + u_it->FROM->Position.X) * IMAGINARY_GRID_SIZE - Match.Viewport.X - 20; r.y = (y + u_it->FROM->Position.Y) * IMAGINARY_GRID_SIZE - Match.Viewport.Y - 30; SDL_BlitSurface(Image.Unit[u_it->Color], NULL, Application.Output, &r); } // idő kiírása char bar[50]; int seconds = (SDL_GetTicks() - Match.STARTED) / 1000; sprintf(bar, "%i:%02i", seconds / 60, seconds % 60); SDL_Surface *text = TTF_RenderText_Solid(Application.FONT, bar, TextColor.BLACK); SDL_Rect r; r.x = r.y = 10; SDL_BlitSurface(text, NULL, Application.Output, &r); SDL_FreeSurface(text); text = TTF_RenderText_Solid(Application.FONT, bar, TextColor.WHITE); r.x = r.y = 9; SDL_BlitSurface(text, NULL, Application.Output, &r); SDL_FreeSurface(text); /* ** "< PRESS CTRL+ESC TO RETURN TO MENU >" */ text = TTF_RenderText_Solid(Application.FONT, "< PRESS CTRL+ESC TO RETURN TO MENU >", TextColor.BLACK); r.x = Application.Output->w / 2 - text->w / 2; r.y = Application.Output->h - 30; SDL_BlitSurface(text, NULL, Application.Output, &r); SDL_FreeSurface(text); r.x = Application.Cursor.X; r.y = Application.Cursor.Y; SDL_BlitSurface(Image.HAND, NULL, Application.Output, &r); }
void Transport::Update(uint32 diff) { uint32 const positionUpdateDelay = 200; if (AI()) AI()->UpdateAI(diff); else if (!AIM_Initialize()) TC_LOG_ERROR("entities.transport", "Could not initialize GameObjectAI for Transport"); if (GetKeyFrames().size() <= 1) return; if (IsMoving() || !_pendingStop) m_goValue.Transport.PathProgress += diff; uint32 timer = m_goValue.Transport.PathProgress % GetTransportPeriod(); bool justStopped = false; // Set current waypoint // Desired outcome: _currentFrame->DepartureTime < timer < _nextFrame->ArriveTime // ... arrive | ... delay ... | departure // event / event / for (;;) { if (timer >= _currentFrame->ArriveTime) { if (!_triggeredArrivalEvent) { DoEventIfAny(*_currentFrame, false); _triggeredArrivalEvent = true; } if (timer < _currentFrame->DepartureTime) { SetMoving(false); justStopped = true; if (_pendingStop && GetGoState() != GO_STATE_READY) { SetGoState(GO_STATE_READY); m_goValue.Transport.PathProgress = (m_goValue.Transport.PathProgress / GetTransportPeriod()); m_goValue.Transport.PathProgress *= GetTransportPeriod(); m_goValue.Transport.PathProgress += _currentFrame->ArriveTime; } break; // its a stop frame and we are waiting } } if (timer >= _currentFrame->DepartureTime && !_triggeredDepartureEvent) { DoEventIfAny(*_currentFrame, true); // departure event _triggeredDepartureEvent = true; } // not waiting anymore SetMoving(true); // Enable movement if (GetGOInfo()->moTransport.allowstopping) SetGoState(GO_STATE_ACTIVE); if (timer >= _currentFrame->DepartureTime && timer < _currentFrame->NextArriveTime) break; // found current waypoint MoveToNextWaypoint(); sScriptMgr->OnRelocate(this, _currentFrame->Node->NodeIndex, _currentFrame->Node->ContinentID, _currentFrame->Node->Loc.X, _currentFrame->Node->Loc.Y, _currentFrame->Node->Loc.Z); TC_LOG_DEBUG("entities.transport", "Transport %u (%s) moved to node %u %u %f %f %f", GetEntry(), GetName().c_str(), _currentFrame->Node->NodeIndex, _currentFrame->Node->ContinentID, _currentFrame->Node->Loc.X, _currentFrame->Node->Loc.Y, _currentFrame->Node->Loc.Z); // Departure event if (_currentFrame->IsTeleportFrame()) if (TeleportTransport(_nextFrame->Node->ContinentID, _nextFrame->Node->Loc.X, _nextFrame->Node->Loc.Y, _nextFrame->Node->Loc.Z, _nextFrame->InitialOrientation)) return; // Update more in new map thread } // Add model to map after we are fully done with moving maps if (_delayedAddModel) { _delayedAddModel = false; if (m_model) GetMap()->InsertGameObjectModel(*m_model); } // Set position _positionChangeTimer.Update(diff); if (_positionChangeTimer.Passed()) { _positionChangeTimer.Reset(positionUpdateDelay); if (IsMoving()) { float t = !justStopped ? CalculateSegmentPos(float(timer) * 0.001f) : 1.0f; G3D::Vector3 pos, dir; _currentFrame->Spline->evaluate_percent(_currentFrame->Index, t, pos); _currentFrame->Spline->evaluate_derivative(_currentFrame->Index, t, dir); UpdatePosition(pos.x, pos.y, pos.z, std::atan2(dir.y, dir.x) + float(M_PI)); } else if (justStopped) UpdatePosition(_currentFrame->Node->Loc.X, _currentFrame->Node->Loc.Y, _currentFrame->Node->Loc.Z, _currentFrame->InitialOrientation); else { /* There are four possible scenarios that trigger loading/unloading passengers: 1. transport moves from inactive to active grid 2. the grid that transport is currently in becomes active 3. transport moves from active to inactive grid 4. the grid that transport is currently in unloads */ bool gridActive = GetMap()->IsGridLoaded(GetPositionX(), GetPositionY()); if (_staticPassengers.empty() && gridActive) // 2. LoadStaticPassengers(); else if (!_staticPassengers.empty() && !gridActive) // 4. - if transports stopped on grid edge, some passengers can remain in active grids // unload all static passengers otherwise passengers won't load correctly when the grid that transport is currently in becomes active UnloadStaticPassengers(); } } sScriptMgr->OnTransportUpdate(this, diff); }
void Transport::Update(uint32 diff) { uint32 const positionUpdateDelay = 200; if (AI()) AI()->UpdateAI(diff); else if (!AIM_Initialize()) TC_LOG_ERROR("entities.transport", "Could not initialize GameObjectAI for Transport"); if (GetKeyFrames().size() <= 1) return; if (IsMoving() || !_pendingStop) m_goValue.Transport.PathProgress += diff; uint32 timer = m_goValue.Transport.PathProgress % GetPeriod(); // Set current waypoint // Desired outcome: _currentFrame->DepartureTime < timer < _nextFrame->ArriveTime // ... arrive | ... delay ... | departure // event / event / for (;;) { if (timer >= _currentFrame->ArriveTime) { if (!_triggeredArrivalEvent) { DoEventIfAny(*_currentFrame, false); _triggeredArrivalEvent = true; } if (timer < _currentFrame->DepartureTime) { SetMoving(false); if (_pendingStop && GetGoState() != GO_STATE_READY) { SetGoState(GO_STATE_READY); m_goValue.Transport.PathProgress = (m_goValue.Transport.PathProgress / GetPeriod()); m_goValue.Transport.PathProgress *= GetPeriod(); m_goValue.Transport.PathProgress += _currentFrame->ArriveTime; } break; // its a stop frame and we are waiting } } if (timer >= _currentFrame->DepartureTime && !_triggeredDepartureEvent) { DoEventIfAny(*_currentFrame, true); // departure event _triggeredDepartureEvent = true; } // not waiting anymore SetMoving(true); // Enable movement if (GetGOInfo()->moTransport.canBeStopped) SetGoState(GO_STATE_ACTIVE); if (timer >= _currentFrame->DepartureTime && timer < _currentFrame->NextArriveTime) break; // found current waypoint MoveToNextWaypoint(); sScriptMgr->OnRelocate(this, _currentFrame->Node->index, _currentFrame->Node->mapid, _currentFrame->Node->x, _currentFrame->Node->y, _currentFrame->Node->z); TC_LOG_DEBUG("entities.transport", "Transport %u (%s) moved to node %u %u %f %f %f", GetEntry(), GetName().c_str(), _currentFrame->Node->index, _currentFrame->Node->mapid, _currentFrame->Node->x, _currentFrame->Node->y, _currentFrame->Node->z); // Departure event if (_currentFrame->IsTeleportFrame()) if (TeleportTransport(_nextFrame->Node->mapid, _nextFrame->Node->x, _nextFrame->Node->y, _nextFrame->Node->z, _nextFrame->InitialOrientation)) return; // Update more in new map thread } // Set position _positionChangeTimer.Update(diff); if (_positionChangeTimer.Passed()) { _positionChangeTimer.Reset(positionUpdateDelay); if (IsMoving()) { float t = CalculateSegmentPos(float(timer) * 0.001f); G3D::Vector3 pos, dir; _currentFrame->Spline->evaluate_percent(_currentFrame->Index, t, pos); _currentFrame->Spline->evaluate_derivative(_currentFrame->Index, t, dir); UpdatePosition(pos.x, pos.y, pos.z, atan2(dir.y, dir.x) + M_PI); } else { /* There are four possible scenarios that trigger loading/unloading passengers: 1. transport moves from inactive to active grid 2. the grid that transport is currently in becomes active 3. transport moves from active to inactive grid 4. the grid that transport is currently in unloads */ if (_staticPassengers.empty() && GetMap()->IsGridLoaded(GetPositionX(), GetPositionY())) // 2. LoadStaticPassengers(); } } sScriptMgr->OnTransportUpdate(this, diff); }
//Finish later GameResult UI::PlayGame() { //create two grids: Player & enemy Channel<MoveResult> *mr = new Channel<MoveResult>(); Channel<Coordinate> *cs = new Channel<Coordinate>(); UserPlayer cup = UserPlayer(mr, cs); CurrentGame.SetP1(&cup); cup.setPlayerBoard(CurrentGame.GetP1Board()); AI ccai = AI(CAI); ccai.setPlayerBoard(CurrentGame.GetP2Board()); ccai.PlacePieces(); CurrentGame.SetP2(&ccai); initscr(); WINDOW *PlayerBoard = newwin(23, 24, 1, 1); WINDOW *AIBoard = newwin(23, 24, 1, 50); WINDOW *EntryArea = newwin(7, 20, 8, 26); SetColor(PlayerBoard, 1, COLOR_WHITE, COLOR_BLACK); SetColor(AIBoard, 1, COLOR_WHITE, COLOR_BLACK); SetColor(PlayerBoard, 2, COLOR_RED, COLOR_BLACK); SetColor(AIBoard, 2, COLOR_RED, COLOR_BLACK); noecho(); //cbreak(); curs_set(0); UserPlayer up; keypad(stdscr, TRUE); std::thread cg(&Game::PlayGame, &CurrentGame); while (true) { MoveResult tmp; mr->get(tmp,false); clear(); wclear(PlayerBoard); wclear(AIBoard); wclear(EntryArea); mvwprintw(EntryArea, 3, 1, " <-P:E->"); wborder(PlayerBoard, '|', '|', '-', '-', '+', '+', '+', '+'); wborder(AIBoard, '|', '|', '-', '-', '+', '+', '+', '+'); wborder(EntryArea, '|', '|', '-', '-', '+', '+', '+', '+'); //render playerboard mvwprintw(PlayerBoard, 1, 4, "A B C D E F G H I J"); for (int i = 0; i < 22; i += 2) { SetColor(PlayerBoard, 2); string gletter = std::to_string(i / 2); SetColor(PlayerBoard, 2); mvwprintw(PlayerBoard, i + 3, 4, "0 0 0 0 0 0 0 0 0 0"); SetColor(PlayerBoard, 1); if (i % 2 == 0) { SetColor(PlayerBoard, 1); mvwprintw(PlayerBoard, i + 3, 1, gletter.c_str()); } } //render ai board mvwprintw(AIBoard, 1, 4, "A B C D E F G H I J"); for (int i = 0; i < 22; i += 2) { SetColor(AIBoard, 2); string gletter = std::to_string(i / 2); SetColor(AIBoard, 2); mvwprintw(AIBoard, i + 3, 4, "0 0 0 0 0 0 0 0 0 0"); SetColor(AIBoard, 1); if (i % 2 == 0) { SetColor(AIBoard, 1); mvwprintw(AIBoard, i + 3, 1, gletter.c_str()); } } RenderToGrid(PlayerBoard, CurrentGame.GetP1Board()->Hits); RenderToGrid(AIBoard, CurrentGame.GetP2Board()->Hits); // refresh(); wrefresh(PlayerBoard); wrefresh(AIBoard); wrefresh(EntryArea); MoveResult cmr; while (true) { char ychar = getchar(); while (ychar < 'a' || ychar > 'j') { ychar = getchar(); } mvwprintw(EntryArea, 1, 2, &ychar); wrefresh(EntryArea); int y = ychar - 'a'; char xchar = getchar(); while (xchar < '0' || xchar > '9') { xchar = getchar(); } mvwprintw(EntryArea, 1, 3, &xchar); wrefresh(EntryArea); int x = xchar - '0'; cs->put(Coordinate{ x,y }); mr->get(cmr); if (cmr == InvalidMove) { mvwprintw(EntryArea, 1, 2, "IM"); continue; } if (cmr == Hit) { mvwprintw(EntryArea, 2, 2, "HIT"); } else if (cmr == Miss) { mvwprintw(EntryArea, 2, 2, "MISS"); } wrefresh(EntryArea); getch(); break; } if (cmr == Quit) { break; } } cg.join(); return Win; }
void Player::Go(Player *P, int numplayers, const Boundary &Path, const Boundary &BLL,const Boundary &BL,const Boundary &BR,const Boundary &BRR, const Button &B, Hook h[],int numHooks) { if(B.reset) { Reset(); } if(caught) { Hook myHookobj = *myHook; y = myHookobj.getY(); caught = myHookobj.caughtOrNot(); if(!caught) { y = .5; z += myHookobj.getRadius()+2; } } else { //Does everything for the player //Works for every type of player. no specifications need to be given, just a lot of objects get passed in Input(B);//Keyboard input for all players //Player-Player interaction if(!finish)//The player hasn't finished { Race(Path);//Follow the path AI(P,numplayers);//Act } else Finished(); //Act finished Bounce(P,numplayers); //Check for bounces between each player //Player-Env. Interaction DetectBoundary(BLL,BL); //Check left boundary DetectBoundary(BR,BRR); //Check right boundary DetectEndCond(Path); //Check end line&beginning if(usedtobeinabound==1||inabound==1) MoveBound(); else//if not in a boundary MoveDamp(); //Combine all Move(); //Check to see that the Players have not exicted the outer boundary Check(BLL, BL,Path,BR, BRR); CheckFinished(Path);//Check to see if the player is passed the ifinish line if(pt == 0) { CheckCollision(h, numHooks); } } }
/*Using minimax with alpha-beta pruning on this one,not sure if I've understood alphabeta pruning correctly but it seems to be working(same results,less time)*/ int AI(char n,int diff,int turn,char ***b,char ***c,int *pi,int *pj,int depth,char caller,char enemy,int alphabeta,int swap){ if(turn==1){ /*In the computer plays first then it chooses the move at the center */ *pi=n/2; *pj=n/2; return 0; } /*If the computer plays second it steals the player's move using swap(as the one playing first always has an advantage in hex. */ if((turn==2)&&(swap==1)){ return 1; } /*Declaring counters,max(starting at -1001 as the worst possible outcome is -1000),min(same)*/ /*gab starts at -1200 and when it changes(see later) it gives the next calling of AI alpha/beta for pruning.*/ int i=0,j=0,ci=0,cj=0,max=-100001,min=100001,gab=-1200; /*Temporary score of each node and a secondary score used if 2 nodes have the same tscore==max*/ int tscore=0,secscore=0; /*Allocating a 3D board :c[0]-c[diff-1](c[depth-1]), 2D boards are used as a base for c[depth] for each calling/iteration*/ if(depth==1){ c=malloc((diff+1)*sizeof(char **)); if(c==NULL){ perror("Malloc"); return 0; } for(i=0;i<diff +1;i++){ c[i]=malloc((n)*sizeof(char *)); if(c[i]==NULL){ perror("Malloc"); return 0; } for(j=0;j<n;j++){ c[i][j]=malloc((n)*sizeof(char)); if(c[i][j]==NULL){ perror("Malloc"); return 0; } } } /*Copying the current status of the game to c[0]*/ for(i=0;i<n;i++) for(j=0;j<n;j++) c[0][i][j]=b[turn][i][j]; } /*Copying c[depth-1] to c[depth]*/ for(i=0;i<n;i++) for(j=0;j<n;j++) c[depth][i][j]=c[depth-1][i][j]; for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(c[depth][i][j]==' '){ /*If the cell isn't occupied */ /*Will be using depth%2 condition to determine if its a condition in which one calling the function(1,3,5...)/his enemy(2,4,6...) would move max/min would be selected etc*/ if(depth%2){ c[depth][i][j]=caller; } else{ c[depth][i][j]=enemy; } if((max!=-1001)||(min!=1001)){ /*If either min or max has been altered this isn't the first node of this subtree. */ if(depth%2) gab=max; else gab=min; } /*If at the the "bottom" of the tree uses score function to determine the worth of this move else calls AI for depth+1*/ if(depth==diff){ tscore=score(c[depth],n,diff,turn,caller,enemy); } else{ tscore=AI(n,diff,turn,b,c,pi,pj,depth+1,caller,enemy,gab,swap); } if(alphabeta!=-1200){ /*If its not on the first depth level and the parent node already has a value(min/max) set(other than the default one). */ if(depth%2){ /*If its a level in which max is selected and the current max is bigger than min of the previous level */ if(alphabeta<max) /*There is no point in continuing on this sub tree as max can only get bigger and can't change min. */ return max; } else{ /*Same logic*/ if(alphabeta>min) return min; } } if (depth%2){ if(tscore>=max){ if(tscore==max){ /*If 2 nodes at the first depth have the same score(same outcome in time) picks the one with the best direct outcome */ if(depth==1) if(score(c[1],n,diff,turn,caller,enemy)>secscore){ secscore=score(c[1],n,diff,turn,caller,enemy); *pi=i; *pj=j; } } else{ /*Change max and if on the first level the coordinates to be returned */ max=tscore; if(depth==1){ *pi=i; *pj=j; } } } }else{ if(tscore<min) min=tscore; } /*c[depth] becomes c[depth-1] again as it prepares for the next nod*/ for(ci=0;ci<n;ci++) for(cj=0;cj<n;cj++) c[depth][ci][cj]=c[depth-1][ci][cj]; } } } /* If the iterations are over (for the first calling of AI) it frees the board and returns 0*/ if(depth==1){ for(i=0;i<diff+1;i++){ for(j=0;j<n;j++){ free(c[i][j]); } free(c[i]); } free(c); return 0; /*Returns 0 if it has finished calculating the move(already returned one if its a swap move).*/ } /*Return the result to the previous calling of AI().*/ if(depth%2) return max; else return min; }
*err = check_persistent_connection(c, status); if( *err != YRMCDS_OK || *status != YRMCDS_STATUS_OK ) { size_t refcount = c->reference_count; on_broken_connection_detected(c, *err, *status); return refcount == 0 ? UEPC_BROKEN : UEPC_BROKEN_AND_OCCUPIED; } } c->reference_count += 1; if( c->reference_count > 1 ) php_log_err("yrmcds: clients share the same persistent connection."); *res = c; return UEPC_OK; } // \yrmcds\Client::__construct ZEND_BEGIN_ARG_INFO_EX(AI(Client, __construct), 0, ZEND_RETURN_VALUE, 1) ZEND_ARG_INFO(0, "node") ZEND_ARG_INFO(0, "port") ZEND_ARG_INFO(0, "persistent_id") ZEND_ARG_INFO(0, "prefix") ZEND_END_ARG_INFO() YRMCDS_METHOD(Client, __construct) { char* node; size_t node_len; long port = 11211; char* persist_id = NULL; size_t persist_id_len = 0; char* prefix = NULL; size_t prefix_len = 0;
void Ghost::UpdateAI(double call_prob, bool call_type) { if (RANDOM <= call_prob) { switch (objType) { case GOT_BLUE_GHOST: if (pGame->IsBlackFlagSet()) { // set the nearest object as an objective WORD nearest_x, nearest_y; pGame->cGhostList().cbegin()->Get_xy(nearest_x, nearest_y); for (auto it = ++pGame->cItemList().cbegin(); it != pGame->cItemList().cend(); ++it) { if (it->GetType() == GOT_SCORE) { WORD it_x, it_y; it->Get_xy(it_x, it_y); if ((x - it_x)*(x - it_x) + (y - it_y)*(y - it_y) < (x - nearest_x)*(x - nearest_x) + (y - nearest_y)*(y - nearest_y)) { nearest_x = it_x; nearest_y = it_y; } } } pGame->GetNearest()->Set_xy(nearest_x, nearest_y); AI(*pGame->GetNearest(), call_type); } else AI(*pGame->cGhostList().cbegin(), call_type); break; case GOT_RED_GHOST: case GOT_OLIVE_GHOST: AI(*pGame->cGhostList().cbegin(), call_type); break; case GOT_PURPLE_GHOST: AI(*pGame->cItemList().cbegin(), call_type); break; default: bool flag = false; for (auto it = ++pGame->cItemList().cbegin(); it != pGame->cItemList().cend(); ++it) { switch (objType) { case GOT_GREEN_GHOST: if (it->GetType() == GOT_BIG_SCORE) { AI(*it, call_type); flag = true; } break; case GOT_AQUA_GHOST: if (it->GetType() == GOT_HELP_SCORE) { AI(*it, call_type); flag = true; } break; case GOT_TEAL_GHOST: if (it->GetType() == GOT_HELP_SCORE) { for (auto i = ++pGame->cItemList().cbegin(); i != pGame->cItemList().cend(); ++i) { if (i->GetType() == GOT_BIG_SCORE) { AI(*it, call_type); flag = true; } } } } } if (!flag) AI(*pGame->cGhostList().cbegin(), call_type); } } }
void Transport::Update(uint32 diff) { if (!AI()) { if (!AIM_Initialize()) sLog->outError("Could not initialize GameObjectAI for Transport"); } else AI()->UpdateAI(diff); if (_isStopped) return; if (GetKeyFrames().size() <= 1) return; //_moveTimer = getMSTime() % _transportInfo->pathTime; _moveTimer += diff; _moveTimer %= _transportInfo->pathTime; // need restart path from beginning /* if (m_timer < m_curr->pathTime) { m_curr = keyFrames.begin(); m_next = m_curr + 1; } */ while (_moveTimer > _nextFrame->pathTime || _moveTimer < _currentFrame->departureTime) { // arrived at next stop point if (_transportInfo->pathTime > _nextFrame->pathTime && _moveTimer < _nextFrame->departureTime) { if (IsMoving()) { SetMoving(false); DoEventIfAny(*_currentFrame, false); } break; } MoveToNextWayPoint(); SetMoving(true); DoEventIfAny(*_currentFrame, true); // first check help in case client-server transport coordinates de-synchronization if (_currentFrame->IsTeleportFrame()) TeleportTransport(_nextFrame->node->mapid, _nextFrame->node->x, _nextFrame->node->y, _nextFrame->node->z); ASSERT(_nextFrame != GetKeyFrames().begin()); sScriptMgr->OnRelocate(this, _currentFrame->node->index, _currentFrame->node->mapid, _currentFrame->node->x, _currentFrame->node->y, _currentFrame->node->z); sLog->outDebug(LOG_FILTER_TRANSPORTS, "%s moved to %f %f %f %d", GetName(), GetPositionX(), GetPositionY(), GetPositionZ(), _currentFrame->node->mapid); } if (IsMoving()) { if (_moveTimer < _currentFrame->departureTime || _moveTimer > _nextFrame->pathTime) sLog->outError("strange times, c.dep:%u, n.pt:%u (%s, %u)", _currentFrame->departureTime, _nextFrame->pathTime, GetName(), m_goInfo->moTransport.mapID); float t = CalculateSegmentPos((float)_moveTimer/(float)IN_MILLISECONDS); //if (t < -0.01f || t > 1.01f) // sLog.outError("strange t=%f (%s, %u)", t, GetName(), m_goInfo->moTransport.mapID); //G3D::Vector3 pos; //m_spline->Evaluate(m_curr->node->index - 1, t, pos); //G3D::Vector3 dir; //m_spline->EvaluateDerivative(m_curr->node->index - 1, t, dir); //dir.z = 0.0f; //dir = -dir.direction(); //Relocate(pos.x, pos.y, pos.z); float x = _currentFrame->node->x * (1.0f - t) + _nextFrame->node->x * t; float y = _currentFrame->node->y * (1.0f - t) + _nextFrame->node->y * t; float z = _currentFrame->node->z * (1.0f - t) + _nextFrame->node->z * t; float o = GetAngle(_nextFrame->node->x, _nextFrame->node->y) + float(M_PI); Relocate(x, y, z, o); UpdatePassengerPositions(); } sScriptMgr->OnTransportUpdate(this, diff); }
int main() { int x = 0, y = 0; init_board(); //盤面の初期化 show(); //表示 while (1) { switch (teban) { case 5: //黒番 if (pass(teban)) { cout << "打てる場所がないのでパスします。" << endl; pass_count++; teban = 6; break; } pass_count = 0; cout << "黒番です > " << endl; do { //AI(x, y, teban); cin >> x >> y; cout << x << "," << y << endl; } while ((x < 1 || x > 8) || (y < 1 || y > 8)); teban = input(x, y, teban); break; case 6: //白番 if (pass(teban)) { cout << "打てる場所がないのでパスします。" << endl; pass_count++; teban = 5; break; } pass_count = 0; cout << "白番です > " << endl; clock_t start = clock(); do { AI(x, y, teban); //cin >> x >> y; cout << x << "," << y << endl; } while ((x < 1 || x > 8) || (y < 1 || y > 8)); teban = input(x, y, teban); clock_t end = clock(); cout << end - start << endl; break; } //二回連続でパスしたら終局の処理 if (pass_count >= 2) { int white_kazu = 0; int black_kazu = 0; int kekka = kanzyo(white_kazu, black_kazu); if (kekka == 5) { cout << "黒の" << black_kazu - white_kazu << "石差勝ちです。" << endl; } else if (kekka == 6) { cout << "白の" << white_kazu - black_kazu << "石差勝ちです。" << endl; } else { cout << "引き分けです。" << endl; } break; } show(); } return 0; }
vector <Coord> AI::getSolution(int cavity, PLAYER player) { if (player = P_BLACK) { reverse(); } clearMovements(); movements(); // Jeœli jest tylko jeden mozliwy ruch, zwraca natychmiast, pomijaj¹c przeszukiwanie. if (_coord.size() == 1) { displayCoord(); Board::Display(); for (int i = 0; i < _coord[0].size(); i++) { _coord[0][i].reverse(); } return _coord[0]; } // Nadanie wartoœci, ka¿demu ruchowi. for (auto & it : _coord) { nodeValue.push_back(AI(*this).treeMinMax(it, cavity - 1)); } // Znalezienie najlepiej punktowanego ruchu int best = INT32_MIN; int iBest = 0; for (int i = 0; i < nodeValue.size(); i++) { if (best < nodeValue[i]) { best = nodeValue[i]; iBest = i; } } // Wyœwietlenie wszystkich mo¿liwych ruchów displayCoord(); Board::Display(); // W przypadku gdy kilka ruchów ma t¹ sam¹ maksymaln¹ wartoœæ, to tworzymy wektor najlepszych ruchów. vector<vector<Coord>> bestResultCoord; for (int i = 0; i < nodeValue.size(); i++) { if (nodeValue[i] == best) { bestResultCoord.push_back(_coord[i]); } } if (player = P_BLACK) { reverse(); } // Losowanie z puli najlepszych ruchow i zwrócenie ruchu if (bestResultCoord.empty()) { if (player == P_BLACK) { for (int i = 0; i < _coord[0].size(); i++) { _coord[0][i].reverse(); } return _coord[0]; } else { return _coord[0]; } } else { if (player == P_BLACK) { for (int i = 0; i < bestResultCoord[0].size(); i++) { bestResultCoord[0][i].reverse(); } return bestResultCoord[0]; } else { return bestResultCoord[0]; } } }
void cbal(int nm, int n, double *ar, double *ai, int *low, int *igh, double *scale) { int i,j,k,l,m,jj,iexc; /* double ar(nm,n),ai(nm,n),scale(n)*/ double c,f,g,r,s,b2,radix; int noconv; radix = 16.0; b2 = radix * radix; k = 1; l = n; goto L100; /* * .......... in-line procedure for row and * column exchange .......... */ L20: SCALE(m) = j; if (j != m) { for (i = 1;i<= l;i++) { f = AR(i,j); AR(i,j) = AR(i,m); AR(i,m) = f; f = AI(i,j); AI(i,j) = AI(i,m); AI(i,m) = f; } for (i = k;i<= n;i++) { f = AR(j,i); AR(j,i) = AR(m,i); AR(m,i) = f; f = AI(j,i); AI(j,i) = AI(m,i); AI(m,i) = f; } } if (iexc == 2) { k++; goto L130; } /* * .......... search for rows isolating an eigenvalue * and push them down .......... */ if (l == 1) goto L280; l--; /* * .......... for j=l step -1 until 1 do -- .......... */ L100: for (jj = 1;jj<= l; jj++) { int test = FALSE; j = l + 1 - jj; for (i = 1;i<= l;i++) { if (i == j) continue; if (AR(j,i) != 0.0 || AI(j,i) != 0.0) { test = TRUE; break; } } if (!test) { m = l; iexc = 1; goto L20; } } /* * .......... search for columns isolating an eigenvalue * and push them left .......... */ L130: for (j = k;j<= l;j++) { int test = FALSE; for ( i = k; i <= l; i++) { if (i == j) continue; if (AR(i,j) != 0.0 || AI(i,j) != 0.0) { test = TRUE; break; } } if (!test) { m = k; iexc = 2; goto L20; } } /* * .......... now balance the submatrix in rows k to l .......... */ for ( i = k;i<= l;i++) SCALE(i) = 1.0; /* * .......... iterative loop for norm reduction .......... */ do { noconv = FALSE; for (i = k;i<= l;i++) { c = 0.0; r = 0.0; for (j = k;j<= l;j++) { if (j == i) continue; c += fabs(AR(j,i)) + fabs(AI(j,i)); r += fabs(AR(i,j)) + fabs(AI(i,j)); } /* * guard against zero c or r due to underflow .......... */ if (c == 0.0 || r == 0.0) continue; g = r / radix; f = 1.0; s = c + r; while (c < g) { f *= radix; c *= b2; } g = r * radix; while (c >= g) { f /= radix; c /= b2; } /* * .......... now balance .......... */ if ((c + r) / f >= 0.95 * s) continue; g = 1.0 / f; SCALE(i) *= f; noconv = TRUE; for (j = k;j<= n;j++) { AR(i,j) *= g; AI(i,j) *= g; } for (j = 1; j<= l; j++) { AR(j,i) *= f; AI(j,i) *= f; } } } while (noconv); L280 : *low = k; *igh = l; }
void Transport::Update(uint32 diff) { uint32 const positionUpdateDelay = 200; if (AI()) AI()->UpdateAI(diff); else if (!AIM_Initialize()) TC_LOG_ERROR("entities.transport", "Could not initialize GameObjectAI for Transport"); if (GetKeyFrames().size() <= 1) return; m_goValue.Transport.PathProgress += diff; uint32 timer = m_goValue.Transport.PathProgress % GetPeriod(); // Set current waypoint // Desired outcome: _currentFrame->DepartureTime < timer < _nextFrame->ArriveTime // ... arrive | ... delay ... | departure // event / event / for (;;) { if (timer >= _currentFrame->ArriveTime) { if (!_triggeredArrivalEvent) { DoEventIfAny(*_currentFrame, false); _triggeredArrivalEvent = true; } if (timer < _currentFrame->DepartureTime) { SetMoving(false); if (_pendingStop) SetGoState(GO_STATE_READY); break; // its a stop frame and we are waiting } } if (_pendingStop && timer >= _currentFrame->DepartureTime && GetGoState() == GO_STATE_READY) { m_goValue.Transport.PathProgress = (m_goValue.Transport.PathProgress / GetPeriod()); m_goValue.Transport.PathProgress *= GetPeriod(); m_goValue.Transport.PathProgress += _currentFrame->ArriveTime; break; } if (timer >= _currentFrame->DepartureTime && !_triggeredDepartureEvent) { DoEventIfAny(*_currentFrame, true); // departure event _triggeredDepartureEvent = true; } if (timer >= _currentFrame->DepartureTime && timer < _currentFrame->NextArriveTime) break; // found current waypoint MoveToNextWaypoint(); // not waiting anymore SetMoving(true); // Enable movement if (GetGOInfo()->moTransport.canBeStopped) SetGoState(GO_STATE_ACTIVE); sScriptMgr->OnRelocate(this, _currentFrame->Node->index, _currentFrame->Node->mapid, _currentFrame->Node->x, _currentFrame->Node->y, _currentFrame->Node->z); TC_LOG_DEBUG("entities.transport", "Transport %u (%s) moved to node %u %u %f %f %f", GetEntry(), GetName().c_str(), _currentFrame->Node->index, _currentFrame->Node->mapid, _currentFrame->Node->x, _currentFrame->Node->y, _currentFrame->Node->z); // Departure event if (_currentFrame->IsTeleportFrame()) if (TeleportTransport(_nextFrame->Node->mapid, _nextFrame->Node->x, _nextFrame->Node->y, _nextFrame->Node->z)) return; // Update more in new map thread } // Add model to map after we are fully done with moving maps if (_delayedAddModel) { _delayedAddModel = false; if (m_model) GetMap()->InsertGameObjectModel(*m_model); } // Set position _positionChangeTimer.Update(diff); if (_positionChangeTimer.Passed()) { _positionChangeTimer.Reset(positionUpdateDelay); if (IsMoving()) { float t = CalculateSegmentPos(float(timer) * 0.001f); G3D::Vector3 pos, dir; _currentFrame->Spline->evaluate_percent(_currentFrame->Index, t, pos); _currentFrame->Spline->evaluate_derivative(_currentFrame->Index, t, dir); UpdatePosition(pos.x, pos.y, pos.z, atan2(dir.x, dir.y)); } } sScriptMgr->OnTransportUpdate(this, diff); }
void TempSummon::Update(uint32 diff) { Creature::Update(diff); if (m_deathState == DEAD) { UnSummon(); return; } switch (m_type) { case TEMPSUMMON_MANUAL_DESPAWN: break; case TEMPSUMMON_TIMED_DESPAWN: { if (m_timer <= diff) { if (IsAIEnabled) AI()->JustDespawned(); UnSummon(); return; } m_timer -= diff; break; } case TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT: { if (!isInCombat()) { if (m_timer <= diff) { UnSummon(); return; } m_timer -= diff; } else if (m_timer != m_lifetime) m_timer = m_lifetime; break; } case TEMPSUMMON_CORPSE_TIMED_DESPAWN: { if (m_deathState == CORPSE) { if (m_timer <= diff) { UnSummon(); return; } m_timer -= diff; } break; } case TEMPSUMMON_CORPSE_DESPAWN: { // if m_deathState is DEAD, CORPSE was skipped if (m_deathState == CORPSE || m_deathState == DEAD) { UnSummon(); return; } break; } case TEMPSUMMON_DEAD_DESPAWN: { if (m_deathState == DEAD) { UnSummon(); return; } break; } case TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN: { // if m_deathState is DEAD, CORPSE was skipped if (m_deathState == CORPSE || m_deathState == DEAD) { UnSummon(); return; } if (!isInCombat()) { if (m_timer <= diff) { UnSummon(); return; } else m_timer -= diff; } else if (m_timer != m_lifetime) m_timer = m_lifetime; break; } case TEMPSUMMON_TIMED_OR_DEAD_DESPAWN: { // if m_deathState is DEAD, CORPSE was skipped if (m_deathState == DEAD) { UnSummon(); return; } if (!isInCombat() && isAlive()) { if (m_timer <= diff) { UnSummon(); return; } else m_timer -= diff; } else if (m_timer != m_lifetime) m_timer = m_lifetime; break; } default: UnSummon(); sLog->outError(LOG_FILTER_UNITS, "Temporary summoned creature (entry: %u) have unknown type %u of ", GetEntry(), m_type); break; } }
void playchoice() { void AI(); int t=0; char i; one: while(!kbhit()) { i=getch(); if (i==up||i==down||i==left||i==right||i==ok) break; } while(kbhit()) { i=getch(); } switch(i) { case left: /*第一个if防止光标和黑白子交换,第二个if防止当前坐标变成黑白子,跟着走*/ nextx=x; if (y==4) goto one; else nexty=y-1; if (map[x][y]==1||map[x][y]==0) { if (map[nextx][nexty]==1||map[nextx][nexty]==0) ; else map[nextx][nexty]=3; x=nextx,y=nexty; break; } if (map[nextx][nexty]==1||map[nextx][nexty]==0) { map[x][y]=4; x=nextx,y=nexty; break; } swap();break; case right: nextx=x; if (y==H-5) goto one; else nexty=y+1; if (map[x][y]==1||map[x][y]==0) { if (map[nextx][nexty]==1||map[nextx][nexty]==0) ; else map[nextx][nexty]=3; x=nextx,y=nexty; break; } if (map[nextx][nexty]==1||map[nextx][nexty]==0) { map[x][y]=4; x=nextx,y=nexty; break; } swap();break; case up: if (x==4) goto one; else nextx=x-1; nexty=y; if (map[x][y]==1||map[x][y]==0) { if (map[nextx][nexty]==1||map[nextx][nexty]==0) ; else map[nextx][nexty]=3; x=nextx,y=nexty; break; } if (map[nextx][nexty]==1||map[nextx][nexty]==0) { map[x][y]=4; x=nextx,y=nexty; break; } swap();break; case down: if (x==H-5) goto one; else nextx=x+1; nexty=y; if (map[x][y]==1||map[x][y]==0) { if (map[nextx][nexty]==1||map[nextx][nexty]==0) ; else map[nextx][nexty]=3; x=nextx,y=nexty; break; } if (map[nextx][nexty]==1||map[nextx][nexty]==0) { map[x][y]=4; x=nextx,y=nexty; break; } swap(); break; case ok: if (map[x][y]==0||map[x][y]==1) goto one; else { map[x][y]=1; clrscr(); drawMap(); usleep(800000); AI(); clrscr(); drawMap(); goto end; } break; default:break; } clrscr(); drawMap(); end:; }
int AI::treeMinMax(vector<Coord>actCoord, int cavity) { for (auto & it : actCoord) { if (!moveTo(it.x, it.y, it.x_, it.y_)) { //cout << "MoveTo: error " << endl; //displayCoord(); //Board::Display(); //cout << endl << endl; } } clearMovements(); reverse(); movements(); if (cavity > 0) { nodeValue.clear(); //Rekurencyjne Tworzenie nowych wêz³ów // Zwraca rozwi¹zanie z liœcia for (auto &it : _coord) { nodeValue.push_back(AI(*this).treeMinMax(it, cavity - 1)); } int best = 0; // cavity & 1 -> cavity % 2 == 1 if (cavity & 1) { if (!nodeValue.empty()) { best = nodeValue[0]; for (auto &it : nodeValue) { if (best < it) { best = it; } } return best; } else { return 1000000 - cavity; } } else { if (!nodeValue.empty()) { best = nodeValue[0]; for (auto &it : nodeValue) { if (best > it) { best = it; } } return best; } else { return -1000000 + cavity; } } } else { rating(P_WHITE); return value; } }