void Start() { BlockManager.StartRound(); Grid.StartRound(); Creep.StartRound(); State = RoundState.Countdown; }
protected Base(FightEngine engine, RoundState state) : base(engine) { if (state == RoundState.None) throw new ArgumentOutOfRangeException("state"); m_tickcount = -1; m_state = state; m_element = null; m_text = null; }
public void init(TournamentRound serverRound, RoundType type) { this.serverRound = serverRound; this.type = type; id = serverRound.getGameID(); players = serverRound.getPlayers(); state = serverRound.getState(); preGameRoomID = serverRound.preGameRoomID; initPlayerSlotTypes(); setPlayerSlots(); initClicks(); initPlayerSlots(); }
protected Base(FightEngine engine, RoundState state) : base(engine) { if (state == RoundState.None) { throw new ArgumentOutOfRangeException("state"); } m_tickcount = -1; m_state = state; m_element = null; m_text = null; }
public async Task <RoundStateResponse> GetStatusAsync(RoundStateRequest request, CancellationToken cancellationToken) { using (await AsyncLock.LockAsync(cancellationToken).ConfigureAwait(false)) { var roundStates = Rounds.Select(x => { var checkPoint = request.RoundCheckpoints.FirstOrDefault(y => y.RoundId == x.Id); return(RoundState.FromRound(x, checkPoint == default ? 0 : checkPoint.StateId)); }).ToArray(); return(new RoundStateResponse(roundStates, Array.Empty <CoinJoinFeeRateAverage>())); } }
// Use this for initialization void Start() { State = RoundState.Player; turnState = TurnState.Character; if (SceneManager.GetActiveScene().name == "Dungeon_Level1") { player.curLevel = 1; } else { player.curLevel = 2; } }
public static string StateString(this RoundState state) { switch (state) { case RoundState.ROUND_READY_TO_START: return("Read to start"); case RoundState.ROUND_IN_PROGRESS: return("Round in progress"); case RoundState.ROUND_COMPLETE: return("Round complete"); default: return("Unknown"); } }
public async Task AliceTimesoutAsync() { // Alice times out when its deadline is reached. WabiSabiConfig cfg = new(); var round = WabiSabiFactory.CreateRound(cfg); var km = ServiceFactory.CreateKeyManager(""); var key = BitcoinFactory.CreateHdPubKey(km); var smartCoin = BitcoinFactory.CreateSmartCoin(key, 10m); var rpc = WabiSabiFactory.CreatePreconfiguredRpcClient(smartCoin.Coin); using Arena arena = await ArenaBuilder.From(cfg).With(rpc).CreateAndStartAsync(round); var arenaClient = WabiSabiFactory.CreateArenaClient(arena); using RoundStateUpdater roundStateUpdater = new(TimeSpan.FromSeconds(2), arena); await roundStateUpdater.StartAsync(CancellationToken.None); // Register Alices. var keyChain = new KeyChain(km, new Kitchen("")); using CancellationTokenSource cancellationTokenSource = new(); var task = AliceClient.CreateRegisterAndConfirmInputAsync(RoundState.FromRound(round), arenaClient, smartCoin, keyChain, roundStateUpdater, cancellationTokenSource.Token); while (round.Alices.Count == 0) { await Task.Delay(10); } var alice = Assert.Single(round.Alices); alice.Deadline = DateTimeOffset.UtcNow - TimeSpan.FromMilliseconds(1); await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); Assert.Empty(round.Alices); cancellationTokenSource.Cancel(); try { await task; throw new InvalidOperationException("The operation should throw!"); } catch (Exception exc) { Assert.True(exc is OperationCanceledException or WabiSabiProtocolException); } await roundStateUpdater.StopAsync(CancellationToken.None); await arena.StopAsync(CancellationToken.None); }
public RoundState create(string id) { RoundState proto = states[id]; if (proto != null) { return(proto.Clone()); } else { Debug.Fail("Not a valid id: " + id); return(null); } }
void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); } else { Debug.Log("init"); Instance = this; states = RoundState.WAITING; StartCoroutine(SetupRound()); } }
private void Update() { if (!NetworkServer.active) { return; } if (clients.Count > 1 && roundState == RoundState.Waiting) { StartRound(); } else if (roundState == RoundState.Waiting && roundInfo != "Waiting for Players...") { roundInfo = "Waiting for Players..."; } if (clients.Count <= 0 && roundState == RoundState.Active) { roundState = RoundState.Waiting; roundInfo = "Waiting for Players..."; } if (countdownTimer > 0f && roundState == RoundState.Active) { countdownTimer = Mathf.Max(0f, countdownTimer - Time.deltaTime); roundInfo = Mathf.Ceil(countdownTimer).ToString(); if (countdownTimer == 0f) { roundInfo = "Go!"; stopPlayerInput = false; Invoke("ClearInfo", 1.5f); } } else if (roundState == RoundState.Active) { roundTimer += Time.deltaTime; if (roundInfo != "Go!") { roundInfo = roundTimer.ToString("F1"); } } else if (roundState == RoundState.Finished) { winTimer = Mathf.Max(0f, winTimer - Time.deltaTime); if (winTimer == 0f) { LoadMapRealtime(); } } }
public void GameStart() { mChessboardData = Model.Model.GetChessboard(BOARD_SIZE); m_ChessboardView.ShowCheckerboard(mChessboardData, this); mCurrentRound = Round.Black; mRoundState = RoundState.Opening; mCurrentVacancyBlackNodes.Clear(); mCurrentVacancyWhiteNodes.Clear(); mActableNodes.Clear(); mSelectNodeIndex = -1; CheckRoundAndState(); }
CreateRoundWithOutputsReadyToSignAsync(Arena arena, Key key1, SmartCoin coin1, Key key2, SmartCoin coin2) { // Create the round. await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); var round = Assert.Single(arena.Rounds); round.MaxVsizeAllocationPerAlice = 11 + 31 + MultipartyTransactionParameters.SharedOverhead; var arenaClient = WabiSabiFactory.CreateArenaClient(arena); // Register Alices. using RoundStateUpdater roundStateUpdater = new(TimeSpan.FromSeconds(2), arena); await roundStateUpdater.StartAsync(CancellationToken.None); using var identificationKey = new Key(); var task1 = AliceClient.CreateRegisterAndConfirmInputAsync(RoundState.FromRound(round), arenaClient, coin1, key1.GetBitcoinSecret(round.Network), identificationKey, roundStateUpdater, CancellationToken.None); var task2 = AliceClient.CreateRegisterAndConfirmInputAsync(RoundState.FromRound(round), arenaClient, coin2, key2.GetBitcoinSecret(round.Network), identificationKey, roundStateUpdater, CancellationToken.None); while (Phase.OutputRegistration != round.Phase) { await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); } await Task.WhenAll(task1, task2); var aliceClient1 = task1.Result; var aliceClient2 = task2.Result; // Register outputs. var bobClient = new BobClient(round.Id, arenaClient); using var destKey1 = new Key(); using var destKey2 = new Key(); await bobClient.RegisterOutputAsync( destKey1.PubKey.WitHash.ScriptPubKey, aliceClient1.IssuedAmountCredentials.Take(ProtocolConstants.CredentialNumber), aliceClient1.IssuedVsizeCredentials.Take(ProtocolConstants.CredentialNumber), CancellationToken.None).ConfigureAwait(false); await bobClient.RegisterOutputAsync( destKey1.PubKey.WitHash.ScriptPubKey, aliceClient2.IssuedAmountCredentials.Take(ProtocolConstants.CredentialNumber), aliceClient2.IssuedVsizeCredentials.Take(ProtocolConstants.CredentialNumber), CancellationToken.None).ConfigureAwait(false); await roundStateUpdater.StopAsync(CancellationToken.None); return(round, aliceClient1, aliceClient2); }
public async Task <RoundState[]> GetGameState(string gameId) { var record = (await _client.GetAsync <GameRecord>(gameId)).Source; var result = new RoundState[_settings.RoundsCount]; for (var i = 0; i < _settings.RoundsCount; i++) { var player1Play = i < record.Player1Plays.Count ? record.Player1Plays[i] : default(Play?); var player2Play = i < record.Player2Plays.Count ? record.Player2Plays[i] : default(Play?); result[i] = GetRoundState(player1Play, player2Play); } return(result); }
public void MoveBack(int amount) { playerOneUnit.newPos = playerOneUnit.oldPos - amount; StartCoroutine( LerpForward ( playerOne.transform, tilesPrefab.tiles[playerOneUnit.oldPos].position, tilesPrefab.tiles[playerOneUnit.newPos].position, 2f ) ); states = RoundState.WAITING; }
public void Add(RoundState roundState) { try { using (var context = new dezbateriEntities()) { context.RoundStates.Add(roundState); context.SaveChanges(); } } catch (Exception ex) { throw new RoundStateException("Add", ex); } }
public void PresidentDown() { if (state != RoundState.Playing) { return; } state = RoundState.PresidentDown; presidentDownParticles.Play(); presidentDownTitle.gameObject.SetActive(true); presidentDownTitle.SetTrigger("Go"); presidentDownColor.enabled = true; presidentDownSound.Play(); musicSource.volume = 0.5f; StartCoroutine(EPresidentDown()); }
public static Color DebugColor(this RoundState thisRound) { switch (thisRound) { case RoundState.Completed: return(Color.GreenYellow); case RoundState.InProgress: return(Color.GhostWhite); case RoundState.NotStarted: return(Color.IndianRed); case RoundState.WaitingForBallServe: return(Color.LightGoldenrodYellow); default: return(Color.DarkGray); } }
//waits for countdown to finish, //then displays the word randomly IEnumerator PlayRound() { state = RoundState.PLAYING; yield return(StartCoroutine(StartCountdown())); yield return(new WaitForSeconds(Random.Range(0.5f, 2f))); if (canPlay) { countdownGUI.text = "Go!"; } goDisplayed = true; startTime = Time.time; }
public int RoundValue(int f26d6, RoundState roundState) { if (roundState == RoundState.Off) { // Round Off return(f26d6); } switch (roundState) { case RoundState.HalfGrid: f26d6 &= 0x7FFFFFC0; f26d6 |= 0x20; break; case RoundState.Grid: if ((f26d6 & 0x20) > 0) { f26d6 &= 0x7FFFFFC0; f26d6 += 0x40; } else { f26d6 &= 0x7FFFFFC0; } break; case RoundState.DoubleGrid: f26d6 &= 0x7FFFFFE0; break; case RoundState.DownToGrid: f26d6 &= 0x7FFFFFC0; break; case RoundState.UpToGrid: if ((f26d6 & 0x3F) > 0) { f26d6 &= 0x7FFFFFC0; f26d6 += 0x40; } else { f26d6 &= 0x7FFFFFC0; } break; } return(f26d6); }
private void SwitchRoundState(RoundState roundStateFocused) { switch (roundStateFocused) { case RoundState.ChoosingAction: break; case RoundState.MakingAction: break; case RoundState.ResolvingRound: break; } roundState = roundStateFocused; print(roundState); }
protected override void OnButtonPressEvent(ButtonPressEvent e) { if (e.screen == this && e.id == "Next") { RoundState round = state as RoundState; if (round.RoundNumber < 3) { ScreenElements.Get <ButtonElement> ("next").Content = "Wait"; MessageMatcher.instance.SetMessage(name + " next", "next screen"); } else { GotoScreen("Final Scoreboard", "End"); } } }
public void StateChanged(IMachineStateComponent <RoundState> component, RoundState previousState) { if (!(component is IRound round)) { return; } Visible = !round.State.Equals(RoundState.NotStarted); Enabled = round.State.Equals(RoundState.InProgress); if (round.State.Equals(RoundState.WaitingForBallServe)) { Transform.Scale = 1f; Visible = true; } }
public RoundResponse Create(Round round, RoundState roundState) { if(round == null) throw new ArgumentNullException("round"); return new RoundResponse( number: round.Number, started: roundState >= RoundState.Committed, completed: roundState >= RoundState.Completed, final: roundState >= RoundState.Final, matches: round .Matches .OrderBy(match => match.Number) .Select(match => MatchResponseProvider.Create(match)) ); }
public void StartEnemyTurn() { roundState = RoundState.StartEnemyTurn; if (!startEnemyTurnData.startedProcessingGlyphs) { GameManager.Instance.glyphManager.startProcessingGlyphs(false); startEnemyTurnData.startedProcessingGlyphs = true; } else if (!GameManager.Instance.glyphManager.processGlyphsData.isProcessing) { GameManager.Instance.enemyManager.ProcessDeadEnemies(); StartCoroutine(GameManager.Instance.enemyManager.ProcessEnemies()); roundState = RoundState.None; startEnemyTurnData.startedProcessingGlyphs = false; } }
public void EndEnemyTurn() { roundState = RoundState.EndEnemyTurn; if (!endEnemyTurnData.startedProcessingGlyphs) { GameManager.Instance.glyphManager.startProcessingGlyphs(true); endEnemyTurnData.startedProcessingGlyphs = true; } else if (!GameManager.Instance.glyphManager.processGlyphsData.isProcessing) { GameManager.Instance.enemyManager.ProcessDeadEnemies(); StartPlayerTurn(); endEnemyTurnData.startedProcessingGlyphs = false; } }
public override void Execute(Game game) { RoundState state = game.State as RoundState; if (state == null) { throw new CommandException(); } Player sender = game.GetPlayerByUserId(SenderUserId); Player opponent = game.GetOpponentPlayerByUserId(SenderUserId); if (sender == null || opponent == null) { throw new CommandException(); } if (sender.IsTurn == false) { throw new CommandException(); } PlayerCard card = sender.HandCards.FirstOrDefault(c => c.Card.Id == CardId); if (card == null) { throw new CommandException(); } if (!ValidateSlot(card, Slot)) { throw new CommandException(); } PlayCard(card, sender, opponent, Slot, TargetCardId); // TODO: Calculate the effective power of each card, of each row and of each player sender.IsTurn = false; opponent.IsTurn = true; var turnEvents = game.Players.Select(player => new TurnEvent(player.User.Id) { Game = game.ToPersonalizedDto(player.User.Id) }); Events.AddRange(turnEvents); }
public async Task CreateNewAsync() { var config = new WabiSabiConfig { MaxInputCountByRound = 1 }; var round = WabiSabiFactory.CreateRound(config); var km = ServiceFactory.CreateKeyManager(""); var key = BitcoinFactory.CreateHdPubKey(km); SmartCoin coin1 = BitcoinFactory.CreateSmartCoin(key, Money.Coins(1m)); var mockRpc = WabiSabiFactory.CreatePreconfiguredRpcClient(coin1.Coin); using Arena arena = await WabiSabiFactory.CreateAndStartArenaAsync(config, mockRpc, round); await arena.TriggerAndWaitRoundAsync(TimeSpan.FromMinutes(1)); await using var coordinator = new ArenaRequestHandler(config, new Prison(), arena, mockRpc.Object); var wabiSabiApi = new WabiSabiController(coordinator); var insecureRandom = new InsecureRandom(); var roundState = RoundState.FromRound(round); var arenaClient = new ArenaClient( roundState.CreateAmountCredentialClient(insecureRandom), roundState.CreateVsizeCredentialClient(insecureRandom), wabiSabiApi); Assert.Equal(Phase.InputRegistration, arena.Rounds.First().Phase); var bitcoinSecret = km.GetSecrets("", coin1.ScriptPubKey).Single().PrivateKey.GetBitcoinSecret(Network.Main); var aliceClient = new AliceClient(round.Id, arenaClient, coin1.Coin, round.FeeRate, bitcoinSecret); await aliceClient.RegisterInputAsync(CancellationToken.None); using RoundStateUpdater roundStateUpdater = new(TimeSpan.FromSeconds(2), wabiSabiApi); Task confirmationTask = aliceClient.ConfirmConnectionAsync( TimeSpan.FromSeconds(1), new long[] { coin1.EffectiveValue(round.FeeRate) }, new long[] { roundState.MaxVsizeAllocationPerAlice - coin1.ScriptPubKey.EstimateInputVsize() }, roundStateUpdater, CancellationToken.None); await arena.TriggerAndWaitRoundAsync(TimeSpan.FromMinutes(1)); await confirmationTask; Assert.Equal(Phase.ConnectionConfirmation, arena.Rounds.First().Phase); }
public void setToTournamentDTO(TournamentRoundDTO dto) { players = dto.players.Select(p => new TournamentPlayer() { info = p.info, isReady = p.isReady, slotIndex = p.slotIndex }).ToList(); if (dto.state == RoundState.Over) { try { players.Find(p => p.info.username == dto.winner).isWinning = true; } catch { } } score = dto.score; state = dto.state; preGameRoomID = dto.preGameID; }
/** * Démarrage */ void Start() { state = RoundState.WarmUp; machineSound = gameObject.AddComponent <AudioSource> (); resisSound = gameObject.AddComponent <AudioSource> (); resisSound.clip = resisTick; clockArm = GameObject.Find("ClockArm"); cinders = GameObject.Find("Cendres"); cinders.transform.position = new Vector3(252, -170, 0); cindersPos = cinders.transform.position; cindersParticles = GameObject.Find("CendresParticules"); cindersParticles.GetComponent <ParticleSystem>().enableEmission = false; //Debug.Log(cindersParticles.GetComponent<ParticleSystem>().isPlaying); }
public override void Execute(Game game) { RedrawState state = game.State as RedrawState; if (state == null) { throw new CommandException(); } Player sender = game.GetPlayerByUserId(SenderUserId); Player opponent = game.GetOpponentPlayerByUserId(SenderUserId); if (sender == null || opponent == null) { throw new CommandException(); } var substate = state.Substates.FirstOrDefault(s => s.UserId == sender.User.Id); var opponentSubstate = state.Substates.FirstOrDefault(s => s.UserId == opponent.User.Id); if (substate == null || opponentSubstate == null || substate.RedrawCardCount == 0) { throw new CommandException(); } if (sender.HandCards.All(c => c.Card.Id != CardId)) { throw new CommandException(); } RedrawCard(sender); substate.RedrawCardCount -= 1; sender.IsTurn = substate.RedrawCardCount > 0; Events.Add(new HandChangedEvent(sender.User.Id) { HandCards = sender.HandCards.Select(c => c.Card.Id).ToList() }); if (substate.RedrawCardCount != 0 || opponentSubstate.RedrawCardCount != 0) { return; } NextState = new RoundState(); }
IEnumerator StartHideMainTitle() { while (mainTitle.GetCurrentAnimatorStateInfo(0).normalizedTime < 1) { yield return(null); } mainTitle.gameObject.SetActive(false); disableAssassin.enabled = true; //disableAssassinTakedown.enabled = true; disableBodyguard.enabled = true; musicSource.Play(); // UI asking assassin to select spawn point should show at this point state = RoundState.SpawnSelect; }
IEnumerator MovePlayer() { if (states == RoundState.MOVING) { diceRoll = Random.Range(1, 7); playerOneUnit.newPos = playerOneUnit.oldPos + diceRoll; diceText.text = "Rolled : " + diceRoll.ToString(); if (playerOneUnit.newPos >= tilesPrefab.tiles.Count) { playerOneUnit.newPos = 0; lap++; trophiesText.gameObject.SetActive(true); PlayerInstance.instance.isVictory = true; trophiesText.text = "VICTORY"; diceButton.GetComponent <Button>().interactable = false; } if (animator) { animator.SetBool("IsMoving", true); } StartCoroutine( LerpPosition ( playerOne.transform, tilesPrefab.tiles[playerOneUnit.oldPos].position, tilesPrefab.tiles[playerOneUnit.newPos].position, 2f ) ); states = RoundState.WAITING; yield return(null); } else { if (animator) { animator.SetBool("IsMoving", false); } } }
/** * Démarrage */ void Start() { state = RoundState.WarmUp; machineSound = gameObject.AddComponent<AudioSource> (); resisSound = gameObject.AddComponent<AudioSource> (); resisSound.clip = resisTick; clockArm = GameObject.Find("ClockArm"); cinders = GameObject.Find("Cendres"); cinders.transform.position = new Vector3 (252, -170, 0); cindersPos = cinders.transform.position; cindersParticles = GameObject.Find ("CendresParticules"); cindersParticles.GetComponent<ParticleSystem>().enableEmission = false; //Debug.Log(cindersParticles.GetComponent<ParticleSystem>().isPlaying); }
public void Progress(KakuhenMachine kakuhenMachine) { if( State == RoundState.EndRound) { State = RoundState.EnsyutuSyuryo; Logger.Info($"[INFO]EnsyutuSyuryo"); } else if( State == RoundState.EnsyutuSyuryo) { State = RoundState.Kaitentai; Logger.Info($"[INFO]Kaitentai"); } else if ( State == RoundState.Kaitentai) { State = RoundState.Turip; Logger.Info($"[INFO]Turip Open"); } else if( State == RoundState.Turip) { if( Round>= 15) { // 最終ラウンド終了 State = RoundState.EndRound; Logger.Info($"[INFO]End round"); Round = 0; kakuhenMachine.Syoka(); return; } State = RoundState.Kaitentai; Round++; Logger.Info($"[INFO]Round Start:{Round}"); } }
public void Lose() { State = RoundState.Loss; }
public bool ApplyPressureToTrigger (){ if(pressure_on_trigger == PressureState.NONE){ pressure_on_trigger = PressureState.INITIAL; fired_once_this_pull = false; } else { pressure_on_trigger = PressureState.CONTINUING; } if(yolk_stage != YolkStage.CLOSED){ return false; } if((pressure_on_trigger == PressureState.INITIAL || action_type == ActionType.DOUBLE) && !slide_lock && thumb_on_hammer == Thumb.OFF_HAMMER && hammer_cocked == 1.0f && safety_off == 1.0f && (auto_mod_stage == AutoModStage.ENABLED || !fired_once_this_pull)){ trigger_pressed = 1.0f; if(gun_type == GunType.AUTOMATIC && slide_amount == 0.0f){ hammer_cocked = 0.0f; if(round_in_chamber && round_in_chamber_state == RoundState.READY){ fired_once_this_pull = true; PlaySoundFromGroup(sound_gunshot_smallroom, 1.0f); round_in_chamber_state = RoundState.FIRED; GameObject.Destroy(round_in_chamber); round_in_chamber = Instantiate(shell_casing, transform.FindChild("point_chambered_round").position, transform.rotation) as GameObject; round_in_chamber.transform.parent = transform; var renderers= round_in_chamber.GetComponentsInChildren<Renderer>(); foreach(Renderer renderer in renderers){ renderer.shadowCastingMode = ShadowCastingMode.Off; } Instantiate(muzzle_flash, transform.FindChild("point_muzzleflash").position, transform.FindChild("point_muzzleflash").rotation); var bullet= Instantiate(bullet_obj, transform.FindChild("point_muzzle").position, transform.FindChild("point_muzzle").rotation) as GameObject; bullet.GetComponent<BulletScript>().SetVelocity(transform.forward * 251.0f); PullSlideBack(); rotation_transfer_y += Random.Range(1.0f,2.0f); rotation_transfer_x += Random.Range(-1.0f,1.0f); recoil_transfer_x -= Random.Range(150.0f,300.0f); recoil_transfer_y += Random.Range(-200.0f,200.0f); add_head_recoil = true; return true; } else { PlaySoundFromGroup(sound_mag_eject_button, 0.5f); } } else if(gun_type == GunType.REVOLVER){ hammer_cocked = 0.0f; var which_chamber= active_cylinder % cylinder_capacity; if(which_chamber < 0){ which_chamber += cylinder_capacity; } var round= cylinders[which_chamber]._object; if(round && cylinders[which_chamber].can_fire){ PlaySoundFromGroup(sound_gunshot_smallroom, 1.0f); round_in_chamber_state = RoundState.FIRED; cylinders[which_chamber].can_fire = false; cylinders[which_chamber].seated += Random.Range(0.0f,0.5f); cylinders[which_chamber]._object = Instantiate(shell_casing, round.transform.position, round.transform.rotation) as GameObject; GameObject.Destroy(round); var renderers = cylinders[which_chamber]._object.GetComponentsInChildren<Renderer>(); foreach(Renderer renderer in renderers){ renderer.shadowCastingMode = ShadowCastingMode.Off; } Instantiate(muzzle_flash, transform.FindChild("point_muzzleflash").position, transform.FindChild("point_muzzleflash").rotation); var bullet = Instantiate(bullet_obj, transform.FindChild("point_muzzle").position, transform.FindChild("point_muzzle").rotation) as GameObject; bullet.GetComponent<BulletScript>().SetVelocity(transform.forward * 251.0f); rotation_transfer_y += Random.Range(1.0f,2.0f); rotation_transfer_x += Random.Range(-1.0f,1.0f); recoil_transfer_x -= Random.Range(150.0f,300.0f); recoil_transfer_y += Random.Range(-200.0f,200.0f); add_head_recoil = true; return true; } else { PlaySoundFromGroup(sound_mag_eject_button, 0.5f); } } } if(action_type == ActionType.DOUBLE && trigger_pressed < 1.0f && thumb_on_hammer == Thumb.OFF_HAMMER){ CockHammer(); CockHammer(); } return false; }
//Round ended stuff public override void OnRoundOverTeamScores(List<TeamScore> teamScores) { _currentRoundState = RoundState.Ended; }
public override void OnRunNextLevel() { _currentRoundState = RoundState.Ended; }
public bool ChamberRoundFromMag (){ if(gun_type != GunType.AUTOMATIC){ return false; } if(magazine_instance_in_gun && MagScript().NumRounds() > 0 && mag_stage == MagStage.IN){ if(!round_in_chamber){ MagScript().RemoveRound(); round_in_chamber = Instantiate(casing_with_bullet, transform.FindChild("point_load_round").position, transform.FindChild("point_load_round").rotation) as GameObject; var renderers= round_in_chamber.GetComponentsInChildren<Renderer>(); foreach(Renderer renderer in renderers){ renderer.shadowCastingMode = ShadowCastingMode.Off; } round_in_chamber.transform.parent = transform; round_in_chamber.transform.localScale = new Vector3(1.0f,1.0f,1.0f); round_in_chamber_state = RoundState.LOADING; } return true; } else { return false; } }
public static void StageRoundUpdate(Client client, Muid stageId, Int32 curRound, RoundState roundState, Int32 winner = 0) { using (var packet = new PacketWriter(Operation.StageRoundState, CryptFlags.Encrypt)) { packet.Write(stageId); packet.Write(curRound); packet.Write((Int32)roundState); packet.Write(winner); client.Send(packet); } }
public void removeUnit(Unit u) { activeUnits.Remove(u); if (activeUnits.Count <= 0) { state = game.stateFactory.create("round-waiting"); } }
void Update (){ if(gun_type == GunType.AUTOMATIC){ if(magazine_instance_in_gun){ var mag_pos= transform.FindChild("point_mag_inserted").position; var mag_rot= transform.rotation; var mag_seated_display= mag_seated; if(disable_springs){ mag_seated_display = Mathf.Floor(mag_seated_display + 0.5f); } mag_pos += (transform.FindChild("point_mag_to_insert").position - transform.FindChild("point_mag_inserted").position) * (1.0f - mag_seated_display); magazine_instance_in_gun.transform.position = mag_pos; magazine_instance_in_gun.transform.rotation = mag_rot; } if(mag_stage == MagStage.INSERTING){ mag_seated += Time.deltaTime * 5.0f; if(mag_seated >= 1.0f){ mag_seated = 1.0f; mag_stage = MagStage.IN; if(slide_amount > 0.7f){ ChamberRoundFromMag(); } recoil_transfer_y += Random.Range(-40.0f,40.0f); recoil_transfer_x += Random.Range(50.0f,300.0f); rotation_transfer_x += Random.Range(-0.4f,0.4f); rotation_transfer_y += Random.Range(0.0f,1.0f); } } if(mag_stage == MagStage.REMOVING){ mag_seated -= Time.deltaTime * 5.0f; if(mag_seated <= 0.0f){ mag_seated = 0.0f; ready_to_remove_mag = true; mag_stage = MagStage.OUT; } } } if(has_safety){ if(safety == Safety.OFF){ safety_off = Mathf.Min(1.0f, safety_off + Time.deltaTime * 10.0f); } else if(safety == Safety.ON){ safety_off = Mathf.Max(0.0f, safety_off - Time.deltaTime * 10.0f); } } if(has_auto_mod){ if(auto_mod_stage == AutoModStage.ENABLED){ auto_mod_amount = Mathf.Min(1.0f, auto_mod_amount + Time.deltaTime * 10.0f); } else if(auto_mod_stage == AutoModStage.DISABLED){ auto_mod_amount = Mathf.Max(0.0f, auto_mod_amount - Time.deltaTime * 10.0f); } } if(thumb_on_hammer == Thumb.SLOW_LOWERING){ hammer_cocked -= Time.deltaTime * 10.0f; if(hammer_cocked <= 0.0f){ hammer_cocked = 0.0f; thumb_on_hammer = Thumb.OFF_HAMMER; PlaySoundFromGroup(sound_hammer_decock, kGunMechanicVolume); //PlaySoundFromGroup(sound_mag_eject_button, kGunMechanicVolume); } } if(has_slide){ if(slide_stage == SlideStage.PULLBACK || slide_stage == SlideStage.HOLD){ if(slide_stage == SlideStage.PULLBACK){ slide_amount += Time.deltaTime * 10.0f; if(slide_amount >= kSlideLockPosition && slide_lock){ slide_amount = kSlideLockPosition; slide_stage = SlideStage.HOLD; PlaySoundFromGroup(sound_slide_back, kGunMechanicVolume); } if(slide_amount >= kPressCheckPosition && slide_lock){ slide_amount = kPressCheckPosition; slide_stage = SlideStage.HOLD; slide_lock = false; PlaySoundFromGroup(sound_slide_back, kGunMechanicVolume); } if(slide_amount >= 1.0f){ PullSlideBack(); slide_amount = 1.0f; slide_stage = SlideStage.HOLD; PlaySoundFromGroup(sound_slide_back, kGunMechanicVolume); } } } var slide_amount_display= slide_amount; if(disable_springs){ slide_amount_display = Mathf.Floor(slide_amount_display + 0.5f); if(slide_amount == kPressCheckPosition){ slide_amount_display = kPressCheckPosition; } } transform.FindChild("slide").localPosition = slide_rel_pos + (transform.FindChild("point_slide_end").localPosition - transform.FindChild("point_slide_start").localPosition) * slide_amount_display; } if(has_hammer){ var hammer= GetHammer(); var point_hammer_cocked= transform.FindChild("point_hammer_cocked"); var hammer_cocked_display= hammer_cocked; if(disable_springs){ hammer_cocked_display = Mathf.Floor(hammer_cocked_display + 0.5f); } hammer.localPosition = Vector3.Lerp(hammer_rel_pos, point_hammer_cocked.localPosition, hammer_cocked_display); hammer.localRotation = Quaternion.Slerp(hammer_rel_rot, point_hammer_cocked.localRotation, hammer_cocked_display); } if(has_safety){ var safety_off_display= safety_off; if(disable_springs){ safety_off_display = Mathf.Floor(safety_off_display + 0.5f); } transform.FindChild("safety").localPosition = Vector3.Lerp(safety_rel_pos, transform.FindChild("point_safety_off").localPosition, safety_off_display); transform.FindChild("safety").localRotation = Quaternion.Slerp(safety_rel_rot, transform.FindChild("point_safety_off").localRotation, safety_off_display); } if(has_auto_mod){ var auto_mod_amount_display= auto_mod_amount; if(disable_springs){ auto_mod_amount_display = Mathf.Floor(auto_mod_amount_display + 0.5f); } var slide= transform.FindChild("slide"); slide.FindChild("auto mod toggle").localPosition = Vector3.Lerp(auto_mod_rel_pos, slide.FindChild("point_auto_mod_enabled").localPosition, auto_mod_amount_display); } if(gun_type == GunType.AUTOMATIC){ hammer_cocked = Mathf.Max(hammer_cocked, slide_amount); if(hammer_cocked != 1.0f && thumb_on_hammer == Thumb.OFF_HAMMER && (pressure_on_trigger == PressureState.NONE || action_type == ActionType.SINGLE)){ hammer_cocked = Mathf.Min(hammer_cocked, slide_amount); } } else { if(hammer_cocked != 1.0f && thumb_on_hammer == Thumb.OFF_HAMMER && (pressure_on_trigger == PressureState.NONE || action_type == ActionType.SINGLE)){ hammer_cocked = 0.0f; } } if(has_slide){ if(slide_stage == SlideStage.NOTHING){ var old_slide_amount= slide_amount; slide_amount = Mathf.Max(0.0f, slide_amount - Time.deltaTime * kSlideLockSpeed); if(!slide_lock && slide_amount == 0.0f && old_slide_amount != 0.0f){ PlaySoundFromGroup(sound_slide_front, kGunMechanicVolume*1.5f); if(round_in_chamber){ round_in_chamber.transform.position = transform.FindChild("point_chambered_round").position; round_in_chamber.transform.rotation = transform.FindChild("point_chambered_round").rotation; } } if(slide_amount == 0.0f && round_in_chamber_state == RoundState.LOADING){ round_in_chamber_state = RoundState.READY; } if(slide_lock && old_slide_amount >= kSlideLockPosition){ slide_amount = Mathf.Max(kSlideLockPosition, slide_amount); if(old_slide_amount != kSlideLockPosition && slide_amount == kSlideLockPosition){ PlaySoundFromGroup(sound_slide_front, kGunMechanicVolume); } } } } if(gun_type == GunType.REVOLVER){ if(yolk_stage == YolkStage.CLOSED && hammer_cocked == 1.0f){ target_cylinder_offset = 0; } if(target_cylinder_offset != 0){ var target_cylinder_rotation= ((active_cylinder + target_cylinder_offset) * 360.0f / cylinder_capacity); cylinder_rotation = Mathf.Lerp(target_cylinder_rotation, cylinder_rotation, Mathf.Pow(0.2f,Time.deltaTime)); if(cylinder_rotation > (active_cylinder + 0.5f) * 360.0f / cylinder_capacity){ ++active_cylinder; --target_cylinder_offset; if(yolk_stage == YolkStage.CLOSED){ PlaySoundFromGroup(sound_cylinder_rotate, kGunMechanicVolume); } } if(cylinder_rotation < (active_cylinder - 0.5f) * 360.0f / cylinder_capacity){ --active_cylinder; ++target_cylinder_offset; if(yolk_stage == YolkStage.CLOSED){ PlaySoundFromGroup(sound_cylinder_rotate, kGunMechanicVolume); } } } if(yolk_stage == YolkStage.CLOSING){ yolk_open -= Time.deltaTime * 5.0f; if(yolk_open <= 0.0f){ yolk_open = 0.0f; yolk_stage = YolkStage.CLOSED; PlaySoundFromGroup(sound_cylinder_close, kGunMechanicVolume * 2.0f); target_cylinder_offset = 0; } } if(yolk_stage == YolkStage.OPENING){ yolk_open += Time.deltaTime * 5.0f; if(yolk_open >= 1.0f){ yolk_open = 1.0f; yolk_stage = YolkStage.OPEN; PlaySoundFromGroup(sound_cylinder_open, kGunMechanicVolume * 2.0f); } } if(extractor_rod_stage == ExtractorRodStage.CLOSING){ extractor_rod_amount -= Time.deltaTime * 10.0f; if(extractor_rod_amount <= 0.0f){ extractor_rod_amount = 0.0f; extractor_rod_stage = ExtractorRodStage.CLOSED; PlaySoundFromGroup(sound_extractor_rod_close, kGunMechanicVolume); } for(var i=0; i<cylinder_capacity; ++i){ if(cylinders[i]._object){ cylinders[i].falling = false; } } } if(extractor_rod_stage == ExtractorRodStage.OPENING){ var old_extractor_rod_amount= extractor_rod_amount; extractor_rod_amount += Time.deltaTime * 10.0f; if(extractor_rod_amount >= 1.0f){ if(!extracted){ for(var i=0; i<cylinder_capacity; ++i){ if(cylinders[i]._object){ if(Random.Range(0.0f,3.0f) > cylinders[i].seated){ cylinders[i].falling = true; cylinders[i].seated -= Random.Range(0.0f,0.5f); } else { cylinders[i].falling = false; } } } extracted = true; } for(var i=0; i<cylinder_capacity; ++i){ if(cylinders[i]._object && cylinders[i].falling){ cylinders[i].seated -= Time.deltaTime * 5.0f; if(cylinders[i].seated <= 0.0f){ var bullet= cylinders[i]._object; var rbody = bullet.AddComponent<Rigidbody>(); bullet.transform.parent = null; rbody.interpolation = RigidbodyInterpolation.Interpolate; rbody.velocity = velocity; rbody.angularVelocity = new Vector3(Random.Range(-40.0f,40.0f),Random.Range(-40.0f,40.0f),Random.Range(-40.0f,40.0f)); cylinders[i]._object = null; cylinders[i].can_fire = false; } } } extractor_rod_amount = 1.0f; extractor_rod_stage = ExtractorRodStage.OPEN; if(old_extractor_rod_amount < 1.0f){ PlaySoundFromGroup(sound_extractor_rod_open, kGunMechanicVolume); } } } if(extractor_rod_stage == ExtractorRodStage.OPENING || extractor_rod_stage == ExtractorRodStage.OPEN){ extractor_rod_stage = ExtractorRodStage.CLOSING; } var yolk_open_display= yolk_open; var extractor_rod_amount_display= extractor_rod_amount; if(disable_springs){ yolk_open_display = Mathf.Floor(yolk_open_display + 0.5f); extractor_rod_amount_display = Mathf.Floor(extractor_rod_amount_display + 0.5f); } var yolk_pivot= transform.FindChild("yolk_pivot"); yolk_pivot.localRotation = Quaternion.Slerp(yolk_pivot_rel_rot, transform.FindChild("point_yolk_pivot_open").localRotation, yolk_open_display); var cylinder_assembly= yolk_pivot.FindChild("yolk").FindChild("cylinder_assembly"); var eulerAngles = cylinder_assembly.localEulerAngles; eulerAngles.z = cylinder_rotation; cylinder_assembly.localEulerAngles = eulerAngles; var extractor_rod= cylinder_assembly.FindChild("extractor_rod"); extractor_rod.localPosition = Vector3.Lerp( extractor_rod_rel_pos, cylinder_assembly.FindChild("point_extractor_rod_extended").localPosition, extractor_rod_amount_display); for(var i=0; i<cylinder_capacity; ++i){ if(cylinders[i]._object){ var name= "point_chamber_"+(i+1); var bullet_chamber= extractor_rod.FindChild(name); cylinders[i]._object.transform.position = bullet_chamber.position; cylinders[i]._object.transform.rotation = bullet_chamber.rotation; cylinders[i]._object.transform.localScale = transform.localScale; } } } }
public override void OnLevelLoaded(String strMapFileName, String strMapMode, Int32 roundsPlayed, Int32 roundsTotal) { DebugWrite("Entering OnLevelLoaded", 7); try { if (_pluginEnabled) { _currentRoundState = RoundState.Loaded; //Completely clear all round-specific data _RoundReports.Clear(); _RoundMutedPlayers.Clear(); _ActionConfirmDic.Clear(); _ActOnSpawnDictionary.Clear(); _ActOnIsAliveDictionary.Clear(); _TeamswapOnDeathMoveDic.Clear(); _Team1MoveQueue.Clear(); _Team2MoveQueue.Clear(); _RoundCookers.Clear(); //Update the factions UpdateFactions(); //Enable round timer if (_useRoundTimer) { StartRoundTimer(); } } } catch (Exception e) { HandleException(new AdKatsException("Error while handling level load.", e)); } DebugWrite("Exiting OnLevelLoaded", 7); }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == Microsoft.Xna.Framework.Input.ButtonState.Pressed) this.Exit(); System.Windows.Forms.Cursor.Current = Cursors.Arrow; KeyboardState currentKeyboardState = Keyboard.GetState(); MouseState mouseState = Mouse.GetState(); if (gameStarted) { if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Escape)) { theMenu.PreviousMenuState = theMenu.MenuState; theMenu.MenuState = MenuState.MainMenu; theMenu.PreviousGameState = gameState; GamePaused = true; } if (playerState == PlayerState.WaitingToStateHands) { //SummaryShown = true; if ((HandsStated.Count > 0) && (SummaryShown == false)) { if (HandSummary.Count > 0) { SummaryShown = true; theMenu.MenuState = MenuState.ShowSummary; gameState = GameState.ShowMenu; theMenu.PreviousGameState = GameState.RoundInProgress; } } } if (HandsStated.Count == 4) { //if (SummaryShown == false) //{ if (playerState == PlayerState.StatedHandsAndTrump) { // the summary is only shown if player one has also stated the trump // else the last step will be missed out SummaryShown = true; theMenu.MenuState = MenuState.ShowSummary; gameState = GameState.ShowMenu; theMenu.PreviousGameState = GameState.RoundInProgress; // } HandsStated.Clear(); } } //if (GamePaused) //{ // theMenu.MenuStrings[0] = "Resume"; //} //else //{ // theMenu.MenuStrings[0] = "Start"; //} if (gameState == GameState.RoundStarting) { StartNewRound(); } else if (gameState == GameState.RoundInProgress) { if (roundState == RoundState.HandOver) { gameState = GameState.RoundInProgress; // the round has begun again roundState = RoundState.HandInProgress; // clear the cards on the table cardsOnTable.Clear(); cardsOnTableList.Clear(); roundState = RoundState.HandInProgress; if (deck.Cards.Count == 0) { HandSummary.Clear(); gameState = GameState.ShowMenu; theMenu.MenuState = MenuState.ShowScore; } } else if (roundState == RoundState.HandInProgress) { if (cardsOnTable.Count < 4) { if (playerToPlay == PlayerIndex.One) { // its the human's turn, we dont need to do anything } else { switch (playerToPlay) { case PlayerIndex.Four: PlaceCard(player4); playerToPlay = PlayerIndex.One; break; case PlayerIndex.Two: PlaceCard(player2); playerToPlay = PlayerIndex.Three; break; case PlayerIndex.Three: PlaceCard(player3); playerToPlay = PlayerIndex.Four; break; default: break; } } } else { timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds; if (timeSinceLastFrame >= 1000) { timeSinceLastFrame = 0; roundState = RoundState.CardsPlaced; winningPlayer = FindPlayerToGetTheHand(); playerToPlay = winningPlayer; switch (winningPlayer) { case PlayerIndex.Four: UpdatePlayerHands(player4); break; case PlayerIndex.One: deck.HandsMade++; break; case PlayerIndex.Three: UpdatePlayerHands(player3); break; case PlayerIndex.Two: UpdatePlayerHands(player2); break; default: break; } } } } } else if (gameState == GameState.RoundOver) { HandKeystroke = 0; deck.Trump = Suit.Unspecified; cardsDistributed = false; deck.HandsMade = 0; deck.HandsStated = 0; player2.HandsMade = 0; player2.HandsStated = 0; player3.HandsMade = 0; player3.HandsStated = 0; player4.HandsMade = 0; player4.HandsStated = 0; gameState = GameState.RoundStarting; } else if (gameState == GameState.GameOver) { if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter)) { if (EnterPressed) { return; } EnterPressed = true; gameState = GameState.ShowMenu; theMenu.MenuState = MenuState.ShowAbout; } else { EnterPressed = false; } if (mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed) { if (buttonPressed) { return; } gameState = GameState.ShowMenu; theMenu.MenuState = MenuState.ShowAbout; } else { buttonPressed = false; } } if (gameState == GameState.RoundInProgress) { // only if its the player's turn to play if (playerToPlay == PlayerIndex.One) { MouseState currentMouseState = Mouse.GetState(); if (currentMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed) { // each time this look executes, if a button press is detected, the car flikers // since it is picked up and kept down again. The buttonPressed variable is // used to handle this case. If buttonPressed is true, the card position is not // updated, this takes care of flickering if the button is kept pressed if (!buttonPressed) { Card cardToRemove = null; buttonPressed = true; int posX, posY; // the x position of the placed posX = MidX; posY = MidY + CARD_PLACE_OFFSET; bool cardPresent = false; Card playingCard ; bool isClickOnCard; for (int index = 0; index < deck.Cards.Count; index++) { playingCard = deck.Cards[index]; isClickOnCard = playingCard.IsClickOnCard(currentMouseState.X, currentMouseState.Y, deck.DistanceBetweenCards); if (!isClickOnCard) { // check for the last card if (index == deck.Cards.Count - 1) { // This is the last card (Right Most), we need to check // click on the entire card and not jst the difference // between the cards if (currentMouseState.X >= playingCard.Position.X && currentMouseState.X <= (playingCard.Position.X + CARD_WIDTH)) { if (currentMouseState.Y >= playingCard.Position.Y && currentMouseState.Y <= (playingCard.Position.Y + playingCard.Image.Height)) { isClickOnCard = true; } } else { isClickOnCard = false; } } } if (isClickOnCard) { // Check if the card is of the same suit as the 1st card if (cardsOnTable.Count > 0) { Card card = cardsOnTableList[0]; if (playingCard.CardSuite != card.CardSuite) { // check if no card exists in the player's deck of the suit // with which the hand has started foreach (Card cardToCheck in deck.Cards) { if (card.CardSuite == cardToCheck.CardSuite) { cardPresent = true; break; } } if (cardPresent) { playingCard.IsMarkedBlack = true; playingCard.IsClicked = true; ClickedCard = playingCard; } else { // Place card playingCard.Position = new Vector2(posX, posY); // set the card to remove cardToRemove = playingCard; deck.PlacedCard = cardToRemove; cardsOnTable.Add(cardToRemove, PlayerIndex.One); cardsOnTableList.Add(cardToRemove); playerToPlay = PlayerIndex.Two; } } else { // Place card playingCard.Position = new Vector2(posX, posY); // set the card to remove cardToRemove = playingCard; deck.PlacedCard = cardToRemove; cardsOnTable.Add(cardToRemove, PlayerIndex.One); cardsOnTableList.Add(cardToRemove); playerToPlay = PlayerIndex.Two; } } else { // Place card playingCard.Position = new Vector2(posX, posY); // set the card to remove cardToRemove = playingCard; deck.PlacedCard = cardToRemove; cardsOnTable.Add(cardToRemove, PlayerIndex.One); cardsOnTableList.Add(cardToRemove); playerToPlay = PlayerIndex.Two; } break; } } if (cardToRemove != null) { deck.Cards.Remove(cardToRemove); playerToPlay = PlayerIndex.Two; } } } else { buttonPressed = false; if (ClickedCard != null) { ClickedCard.IsClicked = false; } } } } if (gameState == GameState.ShowMenu) { if (theMenu.MenuState == MenuState.MainMenu) { if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Down)) { if (downKeyPressed) { return; } downKeyPressed = true; optionSelected++; optionAnimationCounter = 0; if (optionSelected > 3) { optionSelected = 0; } } else { downKeyPressed = false; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Up)) { if (upKeyPressed) { return; } upKeyPressed = true; optionSelected--; optionAnimationCounter = 0; if (optionSelected < 0) { optionSelected = 3; } } else { upKeyPressed = false; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter)) { if (EnterPressed) { return; } EnterPressed = true; switch (optionSelected) { case 0: //gameState = GameState.RoundStarting; //if (string.Compare(theMenu.MenuStrings[0],"Resume") == 0) //{ // //resume the game // theMenu.MenuState = theMenu.PreviousMenuState; // gameState = theMenu.PreviousGameState; // GamePaused = false; //} //else //{ // theMenu.MenuState = MenuState.AskName; //} theMenu.MenuState = MenuState.AskName; gameStarted = true; break; case 1: // Instructions theMenu.MenuState = MenuState.ShowInstructions; //optionSelected = 0; break; case 2: // About theMenu.MenuState = MenuState.ShowAbout; //optionSelected = 0; break; case 3: this.Exit(); break; default: break; } } else { EnterPressed = false; } Rectangle rectCoOrdinates; if (mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed) { rectCoOrdinates = theMenu.MenuStringRectangles[optionSelected]; if (rectCoOrdinates.X <= mouseState.X && (rectCoOrdinates.X + rectCoOrdinates.Width) >= (mouseState.X)) { if (rectCoOrdinates.Y <= mouseState.Y && (rectCoOrdinates.Y + rectCoOrdinates.Height) >= (mouseState.Y)) { switch (optionSelected) { case 0: //gameState = GameState.RoundStarting; //if (string.Compare(theMenu.MenuStrings[0],"Resume") == 0) //{ // //resume the game // theMenu.MenuState = theMenu.PreviousMenuState; // gameState = theMenu.PreviousGameState; // GamePaused = false; //} //else //{ // theMenu.MenuState = MenuState.AskName; //} theMenu.MenuState = MenuState.AskName; gameStarted = true; break; case 1: // Instructions theMenu.MenuState = MenuState.ShowInstructions; //optionSelected = 0; break; case 2: // About theMenu.MenuState = MenuState.ShowAbout; //optionSelected = 0; break; case 3: this.Exit(); break; default: break; } } } } // Check for the mouse for (int index = 0; index < theMenu.MenuStringRectangles.Count; index++) { rectCoOrdinates = theMenu.MenuStringRectangles[index]; if (rectCoOrdinates.X <= mouseState.X && (rectCoOrdinates.X + rectCoOrdinates.Width) >= (mouseState.X)) { if (rectCoOrdinates.Y <= mouseState.Y && (rectCoOrdinates.Y + rectCoOrdinates.Height) >= (mouseState.Y)) { optionSelected = index; System.Windows.Forms.Cursor.Current = Cursors.Hand; break; } } } } else if (theMenu.MenuState == MenuState.ShowScore) { // if the count is same as the round number, the scores have already been // calculated if (!AreScoresCalculated) { int score = 0; AreScoresCalculated = true; // Calculate score for player 2 player2.CalculateScore(); // Calculate score for player 3 player3.CalculateScore(); // Calculate score for player 4 player4.CalculateScore(); // // Calculate score for player 1 if (deck.HandsMade == deck.HandsStated) { TotalScore += deck.HandsStated * 10; Scores.Add(deck.HandsStated * 10); } else { //int score; if (deck.HandsStated > deck.HandsMade) { score = deck.HandsMade - deck.HandsStated; score *= 5; } else { score = 0; } TotalScore += (score); Scores.Add(score); } } if (currentKeyboardState.GetPressedKeys().Length != 0) { AreScoresCalculated = false; gameState = GameState.RoundInProgress; // the round has begun again roundState = RoundState.HandInProgress; // clear the cards on the table cardsOnTable.Clear(); cardsOnTableList.Clear(); roundState = RoundState.HandInProgress; if (deck.Cards.Count == 0) { gameState = GameState.RoundOver; } } if (mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed) { if (buttonPressed) { Clicked = false; } AreScoresCalculated = false; gameState = GameState.RoundInProgress; // the round has begun again roundState = RoundState.HandInProgress; // clear the cards on the table cardsOnTable.Clear(); cardsOnTableList.Clear(); roundState = RoundState.HandInProgress; if (deck.Cards.Count == 0) { gameState = GameState.RoundOver; } } else { buttonPressed = false; } } else if (theMenu.MenuState == MenuState.ShowAbout) { if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter)) { if (EnterPressed) { return; } EnterPressed = true; theMenu.MenuState = MenuState.MainMenu; } else { EnterPressed = false; } if (Clicked) { theMenu.MenuState = MenuState.MainMenu; } } else if (theMenu.MenuState == MenuState.ShowInstructions) { int speed = 10; if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter)) { if (EnterPressed) { return; } EnterPressed = true; theMenu.MenuState = MenuState.MainMenu; } else { EnterPressed = false; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Down)) { if (downKeyPressed) { DownKeyPressedCount++; if (DownKeyPressedCount <= speed) { return; } if (DownKeyPressedCount > speed) { DownKeyPressedCount = 0; } } downKeyPressed = true; StartYInstructions -= 20; } else { downKeyPressed = false; DownKeyPressedCount = 0; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Up)) { if (upKeyPressed) { UpKeyPressedCount++; if (UpKeyPressedCount <= speed) { return; } // the count of 20 is to gradually scroll the screen if (UpKeyPressedCount > speed) { UpKeyPressedCount = 0; } } upKeyPressed = true; StartYInstructions += 20; } else { UpKeyPressedCount = 0; upKeyPressed = false; } } else if (theMenu.MenuState == MenuState.AskName) { GetKeyPressesName(currentKeyboardState); if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter)) { if (EnterPressed) { return; } if (name != string.Empty) { EnterPressed = true; CalculateGridForScore(); theMenu.MenuState = MenuState.AskRounds; } } else { EnterPressed = false; } } else if (theMenu.MenuState == MenuState.AskRounds) { GetKeyPressesRounds(currentKeyboardState); if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter)) { if (EnterPressed) { return; } EnterPressed = true; try { int rounds = Convert.ToInt32(Rounds); if (rounds <= 13 && rounds > 0) { gameState = GameState.RoundStarting; gameStarted = true; roundNumber = 13 - rounds; } } catch (Exception) { // do nothing for now } } else { EnterPressed = false; } } else if (theMenu.MenuState == MenuState.AskTrump) { if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Down)) { if (downKeyPressed) { return; } downKeyPressed = true; optionSelected++; if (optionSelected > 3) { optionSelected = 0; } } else { downKeyPressed = false; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Up)) { if (upKeyPressed) { return; } upKeyPressed = true; optionSelected--; if (optionSelected < 0) { optionSelected = 3; } } else { upKeyPressed = false; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.D1) || currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.NumPad1)) { optionSelected = 0; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.D2) || currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.NumPad1)) { optionSelected = 1; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.D3) || currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.NumPad3)) { optionSelected = 2; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.D4) || currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.NumPad4)) { optionSelected = 3; } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter)) { if (EnterPressed) { return; } EnterPressed = true; if (optionSelected != -1) { playerState = PlayerState.StatedHandsAndTrump; gameState = GameState.RoundStarting; switch (optionSelected) { case 0: trump = Suit.Hearts; HandSummary.Add(name + " stated the maximum hands."); HandSummary.Add("Hence, " + name + " chose the trump which is Hearts."); break; case 1: trump = Suit.Diamonds; HandSummary.Add(name + " stated the maximum hands."); HandSummary.Add("Hence, " + name + " chose the trump which is Diamonds."); break; case 2: trump = Suit.Clubs; HandSummary.Add(name + " stated the maximum hands."); HandSummary.Add("Hence, " + name + " chose the trump which is Clubs."); break; case 3: trump = Suit.Spades; HandSummary.Add(name + " stated the maximum hands."); HandSummary.Add("Hence, " + name + " chose the trump which is Spades."); break; default: break; } } } else { EnterPressed = false; } Rectangle rectCoOrdinates; for (int index = 0; index < theMenu.TrumpStringRectangles.Count; index++) { rectCoOrdinates = theMenu.TrumpStringRectangles[index]; if (rectCoOrdinates.X <= mouseState.X && (rectCoOrdinates.X + rectCoOrdinates.Width) >= (mouseState.X)) { if (rectCoOrdinates.Y <= mouseState.Y && (rectCoOrdinates.Y + rectCoOrdinates.Height) >= (mouseState.Y)) { optionSelected = index; System.Windows.Forms.Cursor.Current = Cursors.Hand; break; } } } if (Clicked) { rectCoOrdinates = theMenu.TrumpStringRectangles[optionSelected]; if (rectCoOrdinates.X <= mouseState.X && (rectCoOrdinates.X + rectCoOrdinates.Width) >= (mouseState.X)) { if (rectCoOrdinates.Y <= mouseState.Y && (rectCoOrdinates.Y + rectCoOrdinates.Height) >= (mouseState.Y)) { playerState = PlayerState.StatedHandsAndTrump; gameState = GameState.RoundStarting; switch (optionSelected) { case 0: trump = Suit.Hearts; HandSummary.Add(name + " stated the maximum hands."); HandSummary.Add("Hence, " + name + " chose the trump which is Hearts."); break; case 1: trump = Suit.Diamonds; HandSummary.Add(name + " stated the maximum hands."); HandSummary.Add("Hence, " + name + " chose the trump which is Diamonds."); break; case 2: trump = Suit.Clubs; HandSummary.Add(name + " stated the maximum hands."); HandSummary.Add("Hence, " + name + " chose the trump which is Clubs."); break; case 3: trump = Suit.Spades; HandSummary.Add(name + " stated the maximum hands."); HandSummary.Add("Hence, " + name + " chose the trump which is Spades."); break; default: break; } } } } } else if (theMenu.MenuState == MenuState.AskHands) { if (currentKeyboardState.GetPressedKeys().Length != 0) { switch (currentKeyboardState.GetPressedKeys()[0]) { case Microsoft.Xna.Framework.Input.Keys.NumPad0: case Microsoft.Xna.Framework.Input.Keys.D0: HandKeystroke = 0; break; case Microsoft.Xna.Framework.Input.Keys.NumPad1: case Microsoft.Xna.Framework.Input.Keys.D1: HandKeystroke = 1; break; case Microsoft.Xna.Framework.Input.Keys.NumPad2: case Microsoft.Xna.Framework.Input.Keys.D2: HandKeystroke = 2; break; case Microsoft.Xna.Framework.Input.Keys.NumPad3: case Microsoft.Xna.Framework.Input.Keys.D3: HandKeystroke = 3; break; case Microsoft.Xna.Framework.Input.Keys.NumPad4: case Microsoft.Xna.Framework.Input.Keys.D4: HandKeystroke = 4; break; case Microsoft.Xna.Framework.Input.Keys.NumPad5: case Microsoft.Xna.Framework.Input.Keys.D5: HandKeystroke = 5; break; case Microsoft.Xna.Framework.Input.Keys.NumPad6: case Microsoft.Xna.Framework.Input.Keys.D6: HandKeystroke = 6; break; case Microsoft.Xna.Framework.Input.Keys.NumPad7: case Microsoft.Xna.Framework.Input.Keys.D7: HandKeystroke = 7; break; case Microsoft.Xna.Framework.Input.Keys.NumPad8: case Microsoft.Xna.Framework.Input.Keys.D8: HandKeystroke = 8; break; case Microsoft.Xna.Framework.Input.Keys.NumPad9: case Microsoft.Xna.Framework.Input.Keys.D9: HandKeystroke = 9; break; //case Keys.C: // if (CheckIfEligibleForTrumpChange(HandKeystroke)) // { // theMenu.MenuState = MenuState.AskTrump; // } //break; default: break; } if (playerToStart == PlayerIndex.Two) { // we only need to check for the total hands and number of cards // condition if the player is the last one to state the hands int totalHands = player2.HandsStated + player3.HandsStated + player4.HandsStated + HandKeystroke; if (totalHands == deck.Cards.Count) { AreHandsValid = false; } else { AreHandsValid = true; } } if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter)) { if (EnterPressed) { return; } EnterPressed = true; if (AreHandsValid) { gameState = GameState.RoundStarting; playerState = PlayerState.StatedHands; deck.HandsStated = HandKeystroke; HandSummary.Add(name + " stated " + HandKeystroke + " hands."); HandsStated.Add(HandKeystroke); SummaryShown = false; } } else { EnterPressed = false; } if (Clicked) { if (AreHandsValid) { gameState = GameState.RoundStarting; playerState = PlayerState.StatedHands; deck.HandsStated = HandKeystroke; HandSummary.Add(name + " stated " + HandKeystroke + " hands."); HandsStated.Add(HandKeystroke); SummaryShown = false; } } } } else if (theMenu.MenuState == MenuState.ShowSummary) { if (currentKeyboardState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter)) { if (EnterPressed) { return; } EnterPressed = true; if (theMenu.PreviousGameState == GameState.RoundInProgress) { gameState = GameState.RoundStarting; } else { theMenu.MenuState = theMenu.PreviousMenuState; } } else { EnterPressed = false; } if (mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed) { if (buttonPressed) { Clicked = false; } if (AreHandsValid) { if (theMenu.PreviousGameState == GameState.RoundInProgress) { gameState = GameState.RoundStarting; } else { theMenu.MenuState = theMenu.PreviousMenuState; } } } else { buttonPressed = false; } } } base.Update(gameTime); } }
/// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); // TODO: Add your drawing code here if (gameStarted) { spriteBatch.Begin(); Rectangle destinationRectBkgrnd = new Rectangle(0, 0, BOARD_WIDTH, BOARD_HEIGHT); spriteBatch.Draw(theMenu.BackgroundWood, destinationRectBkgrnd, Color.White); spriteBatch.End(); if (gameState == GameState.RoundStarting) { if (cardsDistributed) { DrawPlayer1Cards(); DrawAllCards(); DrawCardsOnTable(); } } else if (gameState == GameState.RoundOver) { } else if (gameState == GameState.GameOver) { Player playerToWin = GetPlayerWithMaxScore(); string winnerName = string.Empty; string output; int startX = 20; // Draw Hello World Color textColor = Color.Azure; Vector2 FontOrigin; Vector2 FontPos; int startY = 20; //int startX; destinationRectBkgrnd = new Rectangle(0, 0, BOARD_WIDTH, BOARD_HEIGHT); // Draw the string spriteBatch.Begin(); spriteBatch.Draw(theMenu.BackgroundRed, destinationRectBkgrnd, Color.DarkGray); //string output; if (playerToWin == null) { output = "CONGRATULATIONS!!!"; winnerName = "You have "; FontOrigin = InstructionsFont.MeasureString(output) / 2; startX = (int)(BOARD_WIDTH / 2 - FontOrigin.X * 0.5f); FontPos = new Vector2(startX, startY); spriteBatch.DrawString(InstructionsFont, output, FontPos, textColor, 0, Vector2.Zero, 0.5f, SpriteEffects.None, 0.5f); } else { winnerName = playerToWin.Name + " has"; } output = winnerName + "got the maximum score."; FontOrigin = AboutFont.MeasureString(output); startY = (int)((BOARD_HEIGHT / 2 - FontOrigin.Y * 0.6) - 75); FontPos = new Vector2(BOARD_WIDTH / 2 - FontOrigin.X * 0.6f, startY); spriteBatch.DrawString(AboutFont, output, FontPos, textColor, 0, Vector2.Zero, 1, SpriteEffects.None, 0.5f); output = winnerName + "won the game."; FontPos = new Vector2(40, 150); spriteBatch.DrawString(AboutFont, output, FontPos, textColor, 0, Vector2.Zero, 1, SpriteEffects.None, 0.5f); spriteBatch.End(); } else if (gameState == GameState.RoundInProgress) { DrawPlayer1Cards(); DrawAllCards(); DrawCardsOnTable(); if (roundState == RoundState.CardsPlaced) { float prevX = 0, prevY = 0; switch (winningPlayer) { case PlayerIndex.Two: foreach (Card card in cardsOnTable.Keys) { prevX = card.Position.X; prevY = card.Position.Y; if (prevX > BOARD_WIDTH) { roundState = RoundState.HandOver; break; } card.Position = new Vector2(prevX + CARD_SPEED, prevY); card.Draw(spriteBatch); } break; case PlayerIndex.One: foreach (Card card in cardsOnTable.Keys) { prevX = card.Position.X; prevY = card.Position.Y; if (prevY > BOARD_HEIGHT) { roundState = RoundState.HandOver; break; } card.Position = new Vector2(prevX, prevY + CARD_SPEED); card.Draw(spriteBatch); } break; case PlayerIndex.Three: foreach (Card card in cardsOnTable.Keys) { prevX = card.Position.X; prevY = card.Position.Y; if (prevY < 0) { roundState = RoundState.HandOver; break; } card.Position = new Vector2(prevX, prevY - CARD_SPEED); card.Draw(spriteBatch); } break; case PlayerIndex.Four: foreach (Card card in cardsOnTable.Keys) { prevX = card.Position.X; prevY = card.Position.Y; if (prevX < 0) { roundState = RoundState.HandOver; break; } card.Position = new Vector2(prevX - CARD_SPEED, prevY); card.Draw(spriteBatch); } break; default: break; } } } else if (gameState == GameState.ShowMenu) { if (theMenu.MenuState == MenuState.MainMenu) { ShowMenu(); } else if (theMenu.MenuState == MenuState.AskTrump) { AskTrump(); } else if (theMenu.MenuState == MenuState.AskHands) { AskHands(); } else if (theMenu.MenuState == MenuState.ShowScore) { DrawScoreSheet(); } else if (theMenu.MenuState == MenuState.ShowSummary) { DrawSummary(); } else if (theMenu.MenuState == MenuState.ShowInstructions) { ShowInstructions(StartYInstructions); } else if (theMenu.MenuState == MenuState.ShowAbout) { ShowAbout(); } else if (theMenu.MenuState == MenuState.AskName) { AskName(); } else if (theMenu.MenuState == MenuState.AskRounds) { AskRounds(); } } } base.Draw(gameTime); }
public Judgement() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = BOARD_WIDTH; graphics.PreferredBackBufferHeight = BOARD_HEIGHT; graphics.IsFullScreen = false; Clicked = false; trump = Suit.Unspecified; deck = new Deck(); deck.DistanceBetweenCards = 25; // turn on the mouse cursor this.IsMouseVisible = true; Rounds = "13"; name = string.Empty; HandsStated = new List<int>(); HandSummary = new List<string>(); Content.RootDirectory = "Content"; MidX = (BOARD_WIDTH / 2) - (CARD_WIDTH / 2); MidY = (BOARD_HEIGHT / 2) - (CARD_HEIGHT / 2); GamePaused = false; YourTurnDisplayCount = 0; UpKeyPressedCount = 0; DownKeyPressedCount = 0; SummaryLineIndex = 0; ClickedCard = null; cardsOnTableList = new List<Card>(); //cardsOnTable = new Dictionary<Card, PlayerIndex>(); cardsOnTable = new OrderedDictionary(); downKeyPressed = false; gameStarted = true; playerToPlay = PlayerIndex.Two; roundState = RoundState.HandOver; timeSinceLastFrame = 0; AreHandsValid = true; cardsDistributed = false; //playerToStart = PlayerIndex.Four; IsEligibleForTrumpChange = false; SummaryShown = false; StartYInstructions = 20; AreScoresCalculated = false; optionSelected = 0; optionAnimationCounter = 0; PlayerNames = new List<string>(); Scores = new List<int>(); TotalScore = 0; // set the total score to 0 listOfNames = new List<string>(); listOfNames.Add("Ashwani"); listOfNames.Add("Rahul"); listOfNames.Add("Bhakti"); listOfNames.Add("Akshay"); listOfNames.Add("Sanhita"); listOfNames.Add("Nishij"); listOfNames.Add("Amol"); listOfNames.Add("Prajyot"); listOfNames.Add("Prachiti"); listOfNames.Add("Ajit"); listOfNames.Add("Ravi"); listOfNames.Add("Sonia"); listOfNames.Add("Sayli"); listOfNames.Add("Aman"); listOfNames.Add("Sonal"); listOfNames.Add("Anita"); listOfNames.Add("Prasad"); listOfNames.Add("Vikram"); listOfNames.Add("Sagar"); listOfNames.Add("Sachin"); listOfNames.Add("Shweta"); }
public void PlayerListingThreadLoop() { try { DebugWrite("PLIST: Starting Player Listing Thread", 1); Thread.CurrentThread.Name = "playerlisting"; DateTime loopStart; while (true) { loopStart = DateTime.UtcNow; try { DebugWrite("PLIST: Entering Player Listing Thread Loop", 7); if (!_pluginEnabled) { DebugWrite("PLIST: Detected AdKats not enabled. Exiting thread " + Thread.CurrentThread.Name, 6); break; } Boolean playerListFetched = false; //Get all unparsed inbound lists List<CPlayerInfo> inboundPlayerList = null; if (_PlayerListProcessingQueue.Count > 0) { DebugWrite("PLIST: Preparing to lock player list queues to retrive new player lists", 7); if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (_PlayerListProcessingQueue) { DebugWrite("PLIST: Inbound player lists found. Grabbing.", 6); while (_PlayerListProcessingQueue.Any()) { inboundPlayerList = _PlayerListProcessingQueue.Dequeue(); playerListFetched = true; } //Clear the queue for next run _PlayerListProcessingQueue.Clear(); } } else { inboundPlayerList = new List<CPlayerInfo>(); } //Get all unparsed inbound player removals Queue<CPlayerInfo> inboundPlayerRemoval = null; if (_PlayerRemovalProcessingQueue.Count > 0) { DebugWrite("PLIST: Preparing to lock player removal queue to retrive new player removals", 7); if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (_PlayerRemovalProcessingQueue) { DebugWrite("PLIST: Inbound player removals found. Grabbing.", 6); if (_PlayerRemovalProcessingQueue.Any()) { inboundPlayerRemoval = new Queue<CPlayerInfo>(_PlayerRemovalProcessingQueue.ToArray()); } //Clear the queue for next run _PlayerRemovalProcessingQueue.Clear(); } } else { inboundPlayerRemoval = new Queue<CPlayerInfo>(); } if (!inboundPlayerList.Any() && !inboundPlayerRemoval.Any() && !_PlayerRoleRefetch) { DebugWrite("PLIST: No inbound player lists or removals found. Waiting for Input.", 5); //Wait for input if (!_firstPlayerListComplete) { ExecuteCommand("procon.protected.send", "admin.listPlayers", "all"); } _PlayerProcessingWaitHandle.Reset(); _PlayerProcessingWaitHandle.WaitOne(Timeout.Infinite); if (_firstPlayerListComplete) { //Case where all players are gone after first player list _lastSuccessfulPlayerList = DateTime.UtcNow; } continue; } if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); var removedPlayers = new List<string>(); lock (_PlayerDictionary) { //Firstly, go through removal queue, remove all names, and log them. while (inboundPlayerRemoval.Any()) { CPlayerInfo playerInfo = inboundPlayerRemoval.Dequeue(); AdKatsPlayer aPlayer; if (_PlayerDictionary.TryGetValue(playerInfo.SoldierName, out aPlayer)) { if (aPlayer.TargetedRecords.Count > 0 && !aPlayer.TargetedRecords.Any(aRecord => aRecord.command_action.command_key == "player_kick" || aRecord.command_action.command_key == "player_ban_temp" || aRecord.command_action.command_key == "player_ban_perm" || aRecord.command_action.command_key == "banenforcer_enforce" || aRecord.command_action.command_key == "player_changeip" || aRecord.command_action.command_key == "player_changename" || aRecord.command_action.command_key.Contains("self_"))) { OnlineAdminSayMessage("Targeted player " + aPlayer.player_name + " has left the server."); //This terribly needs streamlining but I cant be asked right now... List<AdKatsRecord> reports = aPlayer.TargetedRecords.Where(aRecord => aRecord.command_type.command_key == "player_report" || aRecord.command_type.command_key == "player_calladmin").ToList(); var reporters = new Dictionary<string, AdKatsPlayer>(); foreach (AdKatsRecord report in reports.Where(report => report.source_player != null)) { reporters[report.source_player.player_name] = report.source_player; } foreach (AdKatsPlayer player in reporters.Values) { PlayerSayMessage(player.player_name, "Player " + aPlayer.player_name + " you reported has left the server.", 1); } } //Add player to the left dictionary aPlayer.player_online = false; aPlayer.player_firstSpawned = false; _PlayerLeftDictionary.Add(aPlayer.player_name, aPlayer); } RemovePlayerFromDictionary(playerInfo.SoldierName, false); removedPlayers.Add(playerInfo.SoldierName); } var validPlayers = new List<String>(); if (inboundPlayerList.Count > 0) { DebugWrite("Listing Players", 5); //Reset the player counts of both sides and recount everything //Loop over all players in the list Int32 team1PC = 0; Int32 team2PC = 0; Int32 team3PC = 0; Int32 team4PC = 0; Double index = 0; foreach (CPlayerInfo playerInfo in inboundPlayerList.Where(player => !removedPlayers.Contains(player.SoldierName))) { if (!_pluginEnabled) { break; } validPlayers.Add(playerInfo.SoldierName); //Check if the player is already in the player dictionary AdKatsPlayer aPlayer = null; if (_PlayerDictionary.TryGetValue(playerInfo.SoldierName, out aPlayer)) { //If they are, only update the internal frostbite player info if (aPlayer.frostbitePlayerInfo.Score != playerInfo.Score || aPlayer.frostbitePlayerInfo.Kills != playerInfo.Kills || aPlayer.frostbitePlayerInfo.Deaths != playerInfo.Deaths) { aPlayer.lastAction = DateTime.UtcNow; } aPlayer.frostbitePlayerInfo = playerInfo; } else { //Player is not already online, handle fetching //First check if the player is rejoining aPlayer = _PlayerLeftDictionary.Values.FirstOrDefault(oPlayer => oPlayer.player_guid == playerInfo.GUID); if (aPlayer != null) { DebugWrite("Player " + playerInfo.SoldierName + " rejoined the server.", 3); //Player is re-joining, check for name changes if (!String.IsNullOrEmpty(playerInfo.SoldierName) && playerInfo.SoldierName != aPlayer.player_name) { aPlayer.player_name_previous = aPlayer.player_name; aPlayer.player_name = playerInfo.SoldierName; var record = new AdKatsRecord { record_source = AdKatsRecord.Sources.InternalAutomated, server_id = _serverID, command_type = _CommandKeyDictionary["player_changename"], command_numeric = 0, target_name = aPlayer.player_name, target_player = aPlayer, source_name = "AdKats", record_message = aPlayer.player_name_previous }; QueueRecordForProcessing(record); DebugWrite(aPlayer.player_name_previous + " changed their name to " + playerInfo.SoldierName + ". Updating the database.", 2); UpdatePlayer(aPlayer); } aPlayer.player_online = true; //Remove them from the left dictionary _PlayerLeftDictionary.Remove(playerInfo.SoldierName); //Add the frostbite player info aPlayer.frostbitePlayerInfo = playerInfo; //Set their last death/spawn times aPlayer.lastDeath = DateTime.UtcNow; aPlayer.lastSpawn = DateTime.UtcNow; aPlayer.lastAction = DateTime.UtcNow; //Add them to the dictionary _PlayerDictionary.Add(playerInfo.SoldierName, aPlayer); //Update rep UpdatePlayerReputation(aPlayer); //If using ban enforcer, check the player's ban status if (_UseBanEnforcer) { QueuePlayerForBanCheck(aPlayer); } else if (_UseHackerChecker) { //Queue the player for a hacker check QueuePlayerForHackerCheck(aPlayer); } if (aPlayer.TargetedRecords.Any(aRecord => aRecord.command_action.command_key == "player_kick" && (DateTime.UtcNow - aRecord.record_time).TotalMinutes < 30) && aPlayer.TargetedRecords.All(aRecord => aRecord.command_action.command_key != "banenforcer_enforce")) { OnlineAdminSayMessage("Kicked player " + aPlayer.player_name + " rejoined the server."); } } else { //If they aren't in the list, fetch their profile from the database aPlayer = FetchPlayer(true, false, false, null, -1, playerInfo.SoldierName, playerInfo.GUID, null); if (aPlayer == null) { //Do not handle the player if not returned continue; } //Add the frostbite player info aPlayer.frostbitePlayerInfo = playerInfo; //Set their last death/spawn times aPlayer.lastDeath = DateTime.UtcNow; aPlayer.lastSpawn = DateTime.UtcNow; aPlayer.lastAction = DateTime.UtcNow; //Add them to the dictionary _PlayerDictionary.Add(playerInfo.SoldierName, aPlayer); //Update rep UpdatePlayerReputation(aPlayer); //If using ban enforcer, check the player's ban status if (_UseBanEnforcer) { QueuePlayerForBanCheck(aPlayer); } else if (_UseHackerChecker) { //Queue the player for a hacker check QueuePlayerForHackerCheck(aPlayer); } } } switch (playerInfo.TeamID) { case 0: //Do nothing, team 0 is the joining team break; case 1: team1PC++; break; case 2: team2PC++; break; case 3: team3PC++; break; case 4: team4PC++; break; default: ConsoleError("Team ID " + playerInfo.TeamID + " for player " + playerInfo.SoldierName + " was invalid."); break; } } _teamDictionary[1].UpdatePlayerCount(team1PC); _teamDictionary[2].UpdatePlayerCount(team2PC); _teamDictionary[3].UpdatePlayerCount(team3PC); _teamDictionary[4].UpdatePlayerCount(team4PC); //Make sure the player dictionary is clean of any straglers Int32 straglerCount = 0; Int32 dicCount = _PlayerDictionary.Count; foreach (string playerName in _PlayerDictionary.Keys.Where(playerName => !validPlayers.Contains(playerName)).ToList()) { straglerCount++; DebugWrite("PLIST: Removing " + playerName + " from current player list (VIA CLEANUP).", 4); _PlayerDictionary.Remove(playerName); } if (straglerCount > 1 && straglerCount > (dicCount / 2)) { var record = new AdKatsRecord { record_source = AdKatsRecord.Sources.InternalAutomated, isDebug = true, server_id = _serverID, command_type = _CommandKeyDictionary["player_calladmin"], command_numeric = 0, target_name = "Server", target_player = null, source_name = "AdKats", record_message = "Server Crashed (" + dicCount + " Players Lost)" }; //Process the record QueueRecordForProcessing(record); ConsoleError(record.record_message); //Set round ended _currentRoundState = RoundState.Ended; } if (_PlayerDictionary.Count >= _lowPopulationPlayerCount) { if (_populationStatusLow) { //Switching state from low to high _populationStatusLow = false; _populationTransitionTime = DateTime.UtcNow; _populationDurationLow += (DateTime.UtcNow - _populationUpdateTime); } else { _populationDurationHigh += (DateTime.UtcNow - _populationUpdateTime); } } else { if (!_populationStatusLow) { //Switching state from high to low _populationStatusLow = true; _populationTransitionTime = DateTime.UtcNow; _populationDurationHigh += (DateTime.UtcNow - _populationUpdateTime); } else { _populationDurationLow += (DateTime.UtcNow - _populationUpdateTime); } } _populationUpdateTime = DateTime.UtcNow; } if (_PlayerRoleRefetch) { //Update roles for all online players foreach (AdKatsPlayer aPlayer in _PlayerDictionary.Values) { AssignPlayerRole(aPlayer); } _PlayerRoleRefetch = false; } } //Update last successful player list time _lastSuccessfulPlayerList = DateTime.UtcNow; //Set required handles _PlayerListUpdateWaitHandle.Set(); _TeamswapWaitHandle.Set(); if (!_firstPlayerListComplete && playerListFetched) { _firstPlayerListComplete = true; OnlineAdminSayMessage("Player listing complete. " + _PlayerDictionary.Count + " players in server."); OnlineAdminSayMessage("AdKats startup complete [" + FormatTimeString(DateTime.UtcNow - _AdKatsStartTime, 3) + "]. Commands are now online."); DebugWrite("AdKats startup complete [" + FormatTimeString(DateTime.UtcNow - _AdKatsStartTime, 3) + "]. Commands are now online.", 1); } } catch (Exception e) { if (e is ThreadAbortException) { ConsoleWarn("player listing thread was force aborted. Exiting."); break; } HandleException(new AdKatsException("Error occured in player listing thread. Skipping loop.", e)); } if (AdKats.FullDebug && ((DateTime.UtcNow - loopStart).TotalMilliseconds > 100)) ConsoleWrite(Thread.CurrentThread.Name + " thread loop took " + ((int) ((DateTime.UtcNow - loopStart).TotalMilliseconds))); } DebugWrite("PLIST: Ending Player Listing Thread", 1); LogThreadExit(); } catch (Exception e) { HandleException(new AdKatsException("Error occured in player listing thread.", e)); } }
public void start() { game.currentRound = this; new TimedTextDisplay(270, 150, name, Colors.Yellow, 30, 3); passedTime = 0; state = game.stateFactory.create("round-notactive"); MoveContainer.getInstance().Add(this); }
private void StartNewState(RoundState roundState) { }
private void StartNewState(RoundState roundState, RoundStatus status) { switch (roundState) { case RoundState.Contract: img_trump.Source = new BitmapImage(new Uri(ContractDialog.GetSuitImageUrl(status.Trumpk__BackingField), UriKind.Relative)); img_trump.Visibility = System.Windows.Visibility.Visible; break; case RoundState.Bidding: img_trump.Visibility = System.Windows.Visibility.Collapsed; break; } }
/** * Démarrage de la phase de rythme */ void StartRhythmState() { state = RoundState.Rhythm; gameObject.GetComponent<AudioSource> ().PlayOneShot (machineStart); if (machineStart.length>1) { gameObject.GetComponent<AudioSource> ().clip = machineWork; gameObject.GetComponent<AudioSource> ().Play (); } game.StartMachineAnims(); Sequence seq; rhythmDuration = 0.0f; // Initialisation des scores et séquences for (int i = 0; i < 4; i++) { scores[i] = 0; seq = Sequence.MakeSequence(this, game.players[i]); seq.transform.parent = gameObject.transform.parent; seq.transform.SetParent(gameObject.transform); rhythmDuration = Mathf.Max(rhythmDuration, seq.duration); sequences[i] = seq; } // Initialisation de la position des séquences (valeurs en dur) sequences [0].transform.position = new Vector3(-59, 68, 0); sequences [1].transform.position = new Vector3(37, 68, 0); sequences [2].transform.position = new Vector3(37, -29, 0); sequences [3].transform.position = new Vector3(-59, -29, 0); }
public override void OnPlayerSpawned(String soldierName, Inventory spawnedInventory) { DebugWrite("Entering OnPlayerSpawned", 7); try { AdKatsPlayer aPlayer = null; if (_pluginEnabled && _threadsReady) { if (_currentRoundState == RoundState.Loaded) { _currentRoundState = RoundState.Playing; } if (_CommandNameDictionary.Count > 0) { //Handle TeamSwap notifications String command = _CommandKeyDictionary["self_teamswap"].command_text; if (_PlayerDictionary.TryGetValue(soldierName, out aPlayer)) { aPlayer.lastSpawn = DateTime.UtcNow; aPlayer.lastAction = DateTime.UtcNow; if (aPlayer.player_aa && !aPlayer.player_aa_told) { String adminAssistantMessage = "You are now considered an Admin Assistant. "; if (!_UseAAReportAutoHandler && !_EnableAdminAssistantPerk) { adminAssistantMessage += "Thank you for your consistent reporting."; } else { adminAssistantMessage += "Perks: "; if (_UseAAReportAutoHandler) { adminAssistantMessage += "AutoAdmin can handle some of your reports. "; } if (_EnableAdminAssistantPerk) { adminAssistantMessage += "You can use the @" + command + " command."; } } PlayerSayMessage(soldierName, adminAssistantMessage, 1); aPlayer.player_aa_told = true; } } } //Handle Dev Notifications if (soldierName == "ColColonCleaner" && (!_isTestingAuthorized || !_toldCol)) { PlayerTellMessage("ColColonCleaner", "CONGRATS! This server is running AdKats " + PluginVersion + "!", 1); _toldCol = true; } if (aPlayer != null && !aPlayer.player_firstSpawned) { aPlayer.player_firstSpawned = true; if(_UseFirstSpawnMessage) { //Wait 3 seconds Thread.Sleep(2000); PlayerTellMessage(aPlayer.player_name, _FirstSpawnMessage, 1); } } if (_ActOnSpawnDictionary.Count > 0) { if (_isTestingAuthorized) PushThreadDebug(DateTime.Now.Ticks, (String.IsNullOrEmpty(Thread.CurrentThread.Name) ? ("mainthread") : (Thread.CurrentThread.Name)), Thread.CurrentThread.ManagedThreadId, new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber(), ""); lock (_ActOnSpawnDictionary) { AdKatsRecord record; if (_ActOnSpawnDictionary.TryGetValue(soldierName, out record)) { //Remove it from the dic _ActOnSpawnDictionary.Remove(soldierName); //Wait 1.5 seconds to take action (no "killed by admin" message in BF3 without this wait) Thread.Sleep(1500); //Queue the action QueueRecordForActionHandling(record); } } } } } catch (Exception e) { HandleException(new AdKatsException("Error while handling player spawn.", e)); } DebugWrite("Exiting OnPlayerSpawned", 7); }
/** * Démarrage de la phase de rythme */ public void StartVoteState() { state = RoundState.Vote; VoteState.MakeVoteState (this, game); gameObject.GetComponent<AudioSource> ().clip = machineStop; gameObject.GetComponent<AudioSource> ().Play (); }
public void RoundStart() { State = RoundState.Kaitentai; Round = 1; Logger.Info($"[INFO]Round Start:{Round}"); }