public void EasySuccess() { var players = new List<Player> { new Player(), new Player(), new Player(), new Player(), new Player() }; var round = new Round(players, 0, 3, 1); //to start with we should be waiting for someone to choose the players Assert.AreEqual(Round.State.ProposingPlayers, round.DetermineState()); //select the players for the quest round.AddToTeam(players[0], players[0]); Assert.AreEqual(Round.State.ProposingPlayers, round.DetermineState()); round.AddToTeam(players[0], players[1]); round.AddToTeam(players[0], players[2]); Assert.AreEqual(Round.State.Voting, round.DetermineState()); //do some voting to see if everyone approves round.VoteForTeam(players[0], true); Assert.AreEqual(Round.State.Voting, round.DetermineState()); round.VoteForTeam(players[1], true); round.VoteForTeam(players[2], false); round.VoteForTeam(players[3], false); round.VoteForTeam(players[4], true); //do the quest Assert.AreEqual(Round.State.Questing, round.DetermineState()); round.SubmitQuest(players[0], true); Assert.AreEqual(Round.State.Questing, round.DetermineState()); round.SubmitQuest(players[1], true); round.SubmitQuest(players[2], true); Assert.AreEqual(Round.State.Succeeded, round.DetermineState()); }
private void StartGame(int roundNumber) { Round round; if (roundNumber == 0) { if (CurrentRound != null) { CurrentRound.DestroyAll(); } } if (roundNumber == 0) { round = RoundFactory.FirstRound(); } else { round = RoundFactory.GetRound(CurrentRound); } round.Finish += OnRoundFinish; InvokeStarted(); CurrentRound = round; InvokeNewRound(); }
public Score(Team team, Round round) { this.Team = team; Multiplier = 1.0f; Round = round; team.AddScore(this); }
public ActionResult Round(Guid id) { ScorekeeperDBEntities s = new ScorekeeperDBEntities(); Round r = new Round(); r = s.Rounds.Where(x => x.RoundId == id).FirstOrDefault(); return View("Round", r); }
private Round UpgradeRound(Round round) { round.Number++; int colors = Mathf.Clamp(MinNumberOfColors + round.Number, 1, MaxNumberOfColors); var newCells = new List<Cell>(); foreach (Cell cell in round.Cells) { foreach (Pair neighbour in cell.Neighbours) { if (neighbour.Neigbour == null) { Vector3 newPos = cell.transform.position + neighbour.OffsetRelativeCenter; var cast = Physics2D.OverlapPoint(newPos); if (!cast) { Cell newCell = CellFactory.GetRandomCell(colors, newPos); neighbour.Neigbour = newCell; newCell.Clicked += round.OnClick; newCells.Add(newCell); break; } neighbour.Neigbour = cast.transform.GetComponent<Cell>(); } } } round.Cells.AddRange(newCells); round.TargetType = newCells.ToArray()[Random.Range(0, newCells.Count)].Type; CenterCameraOnField.Instance.CenterCameraOnChuzzles(round.Cells, true); return round; }
public void RevealsTopCardIn(Round round) { if (_Cards.Count > 0) { round.PutCardOnTable(this, _Cards.Pop()); } }
public Wave CreateWave(Round round) { // lookup pool by type Wave wave = new Wave(round.waves.Count); round.waves.Add(wave); return wave; }
public static Round GetRound(Round round) { if (Instance) { return Instance.UpgradeRound(round); } throw new NullReferenceException("Not inited RoundFactory.Instance"); }
public void BeginNextRound() { int nextRoundIndex = _game.Rounds.Ensure() .OrderBy(round => round.Index) .Select(round => round.Index) .FirstOrDefault() + 1; _currentRound = _game.CreateRound(nextRoundIndex); }
public GameState(Game game, Round round, Player priority, ImmutableList<PlayerState> playerStates, ImmutableList<CompanyState> companyStates) { Game = game; Round = round; PlayerWithPriority = priority; PlayerStates = playerStates; CompanyStates = companyStates; }
/** * Créer une séquence * @param <Player> player : joueur associé */ public static Sequence MakeSequence(Round round, Player player) { GameObject go = new GameObject("Player" + player.id + "Sequence"); Sequence seq = go.AddComponent<Sequence>(); seq.round = round; seq.player = player; return seq; }
public void AddRound(Round round) { if (rounds.Contains(round)) { throw new InvalidOperationException("Round already exists in collection"); } rounds.Add(round); }
public static Round FirstRound() { var round = new Round(); Cell randomCell = CellFactory.GetRandomCell(10, Vector3.zero); randomCell.Clicked += round.OnClick; round.TargetType = randomCell.Type; round.Cells.Add(randomCell); return round; }
public Unit Create(String id, Round r) { Unit proto = units[id]; if(proto != null) { return proto.Clone(r); } else { Debug.Fail("Not a valid id: " + id); return null; } }
public Round CreateRound() { var round = new Round(); SetEventHandlers(round, true); if (rounds == null) rounds = new List<Round>(); rounds.Add(round); round.index = rounds.Count - 1; return round; }
public void PerformABidding() { var round = new Round(_Players.Object, _Biddings, new HighestCardCalculator(Trump)); round.PerformBidding(); Assert.That(_Biddings.BidOf(_Player1), Is.TypeOf<int>()); Assert.That(_Biddings.BidOf(_Player2), Is.TypeOf<int>()); Assert.That(_Biddings.BidOf(_Player3), Is.TypeOf<int>()); Assert.That(_Biddings.BidOf(_Player4), Is.TypeOf<int>()); }
public HandAnalysis GetAnalysis(int seatIdx, int opponents, Round round) { switch (round) { case Round.Preflop: return Analysis[0][seatIdx][opponents - 1]; case Round.Flop: return Analysis[1][seatIdx][opponents - 1]; case Round.Turn: return Analysis[2][seatIdx][opponents - 1]; case Round.River: return Analysis[3][seatIdx][opponents - 1]; default: return null; } }
public RoundManager() { Round round1 = new Round(); Round round2 = new Round(); Round round3 = new Round(); rounds.Add(round1); rounds.Add(round2); rounds.Add(round3); rounds[0].changeState(Const.NOTSTARTED); // update state of all rounds to not started rounds[1].changeState(Const.NOTSTARTED); // update state of all rounds to not started rounds[2].changeState(Const.NOTSTARTED); // update state of all rounds to not started }
private void OnRoundFinish(Round round) { round.Finish -= OnRoundFinish; if (round.Win) { RoundNumber++; StartGame(RoundNumber); } else { RoundNumber = 0; InvokeLose(); } }
/** * Créer une voteState */ public static VoteState MakeVoteState(Round round, ExecGame game) { bool voteStarted = false; if (voteStarted == false) { GameObject go = new GameObject ("VoteState"); vs = go.AddComponent<VoteState> (); vs.transform.SetParent (round.transform); vs.round = round; vs.game = game; voteStarted = true; } return vs; }
public static void LastRoundDisplay(Round current, Round next1, Round next2) { Template template = velocity.GetTemplate(@"templates\last_round_scores.vm"); VelocityContext c = new VelocityContext(baseContext); if (current != null) { var scores = from t in current.Teams select new { Name = t.Name, Score = t.GetScore(current), TotalScore = t.TotalScore(current.Type) }; c.Put("current", current); c.Put("scores", scores); } else { List<object> scores = new List<object>(); scores.Add(new object()); scores.Add(scores[0]); scores.Add(scores[0]); scores.Add(scores[0]); c.Put("scores", scores); } System.Collections.ArrayList list = new System.Collections.ArrayList(); if (next1 != null) { list.Add(new { Number = next1.Number, Red = next1.Red.Name, Green = next1.Green.Name, Blue = next1.Blue.Name, Yellow = next1.Yellow.Name }); } else { list.Add(new object()); } if (next2 != null) { list.Add(new { Number = next2.Number, Red = next2.Red.Name, Green = next2.Green.Name, Blue = next2.Blue.Name, Yellow = next2.Yellow.Name }); } else { list.Add(new object()); } c.Put("next", list); StringWriter sw = new StringWriter(); template.Merge(c, sw); string fileName = fileMap[PageId.LastRound]; File.WriteAllText("html\\" + fileName, sw.ToString()); }
// Use this for initialization void Start() { GameObject networkingManagerObject = GameObject.Find("Networking Manager"); if (networkingManagerObject == null) { Debug.LogWarning("Couldn't find the Networking Manager. Proceeding without networking..."); } else { networkingManager = networkingManagerObject.GetComponent<NetworkingManager>(); networkingManager.MessageReceived += networkingManager_MessageReceived; } round = Instantiate(RoundPrefab) as Round; }
static void Main(string[] args) { // Задание 2.1 /* Написать класс Round, задающий круг с указанными координатами центра, * радиусом, а также свойствами, позволяющими узнать длину описанной * окружности и площадь круга. Обеспечить нахождение объекта в заведомо * корректном состоянии. Написать программу, демонстрирующую использование * данного круга.*/ Console.WriteLine("\nЗадание 2.1 \n"); Round newRound = new Round(3, 4, 5); Console.WriteLine("Периметр круга = {0}", Math.Round(newRound.LengthRound(), 2)); Console.WriteLine("Площадь круга = {0}", Math.Round(newRound.AreaRound(), 2)); Console.ReadKey(); }
Round GetRound(int n) { if (roundCache.ContainsKey(n)) return roundCache[n]; var round = new Round(); if (n == 0) { round.KeepRanges.Add (new Range(0, 1)); } else { var prev = GetRound(n - 1); foreach (var r in prev.KeepRanges) { var r1 = new Range(r.Min, r.Min + r.Width / 3); var r2 = new Range(r.Min + r.Width / 3, r.Max - r.Width / 3); var r3 = new Range(r.Max - r.Width / 3, r.Max); round.KeepRanges.Add(r1); round.EliminateRanges.Add(r2); round.KeepRanges.Add(r3); Debug.Assert(r.Contains(r1)); Debug.Assert(r.Contains(r2)); Debug.Assert(r.Contains(r3)); Debug.Assert(!r1.Intersects(r2)); Debug.Assert(!r2.Intersects(r3)); Debug.Assert(!r1.Intersects(r3)); } // Debug.Assert(!prev.KeepRanges.Any(r=>round.EliminateRanges.Any(x=>r.Intersects(x)))); } Debug.Assert(round.KeepRanges.Count == 1 << n); Debug.Assert(round.EliminateRanges.Count == (n>0 ? 1 << (n-1) : 0)); roundCache.Add (n ,round) ; return round; }
public void DetermineTheHighestCard() { var cardCalculator = new Mock<ICardCalculator>(); var round = new Round(_Players.Object, _Biddings, cardCalculator.Object); IList<ICard> cards = new List<ICard> { Queen.Of(Suit.Hearts), King.Of(Suit.Diamonds), Two.Of(Suit.Hearts), Six.Of(Suit.Spades) }; _Player1.Hand().Add(cards[0]); _Player2.Hand().Add(cards[1]); _Player3.Hand().Add(cards[2]); _Player4.Hand().Add(cards[3]); round.DetermineHighestCard(); cardCalculator.Verify(a => a.HighestCard(cards)); }
private void button3_Click(object sender, EventArgs e) { OutputData output = new OutputData("Test Test case name", "221"); Round r1 = new Round("R1", "test des for 1"); CheckPoint cp = new CheckPoint("cp1", "des for cp1"); cp.Inputs.AddParameter("input para1", "v1"); cp.Inputs.AddParameter("input para2", "v2"); cp.Inputs.AddParameter("input para3", "v3"); cp.Inputs.AddParameter("input para4", "v4"); cp.Outpus.AddParameter("output1", "v5"); cp.Outpus.AddParameter("output2", "v6"); cp.Outpus.AddParameter("output3", "v7"); cp.ExpectedValues.AddParameter("E1", "v8"); cp.ExpectedValues.AddParameter("E2", "v9"); cp.ExpectedValues.AddParameter("E3", "v10"); cp.Result = TestResult.Pass; r1.CheckPoints.Add(cp); CheckPoint cp2 = new CheckPoint("cp1", "des for cp1"); cp2.Inputs.AddParameter("input para1", "v1"); cp2.Inputs.AddParameter("input para2", "v2"); cp2.Inputs.AddParameter("input para3", "v3"); cp2.Inputs.AddParameter("input para4", "v4"); cp2.Outpus.AddParameter("output1", "v5"); cp2.Outpus.AddParameter("output2", "v6"); cp2.Outpus.AddParameter("output3", "v7"); cp2.ExpectedValues.AddParameter("E1", "v8"); cp2.ExpectedValues.AddParameter("E2", "v9"); cp2.ExpectedValues.AddParameter("E3", "v10"); cp2.Result = TestResult.Fail; r1.CheckPoints.Add(cp); output.Rounds.Add(r1); output.ConvertToXml("C:/tss.xml"); }
void StartRound(){ gameState = GameState.Flying; var superstitions = GameMetrics.Instance.GetSuperstitions (); if (superstitions.Count == 0) { superstitions.Add (Superstition.CreateChicken (1)); } currentRound = new Round (); /* Example code for adding a supersitition var s = new Superstition (); s.maxValue = 2; s.value = 1; s.score = .5f; s.weight = .5f; currentRound.superstitions.Add (s); */ resultsPanel.generateSuperstitionsList (IntroClosed); SpawnPlayer (); }
// TODO do real implementation :) // Below is a very dummy implementation public void BettingRounds(Round rnd) { var i = 0; switch (rnd) { case Round.PreFlop: break; case Round.Flop: i = 2; break; case Round.Turn: i = 3; break; case Round.River: i = 4; break; } if (i > 0) { throw new NotImplementedException(); } }
public void UpdateFromRound(Round round) { switch (type) { case Type.Chicken: if (metric == SuperMetrics.pickup) { if (maxValue == 1) { value = round.numChickens == 1 ? 1 : 0; } else { value = round.numChickens % 10 == checkValue ? 1 : 0; } } break; case Type.Beer: if (metric == SuperMetrics.pickup) { value = round.numBeers % 10 == checkValue ? 1 : 0; } break; case Type.Baseballs: if (metric == SuperMetrics.pickup) { value = round.numBalls % 10 == checkValue ? 1 : 0; } break; case Type.Cows: if (metric == SuperMetrics.pickup) { value = round.numCows % 10 == checkValue ? 1 : 0; } break; default: value = 0; maxValue = 1; break; } }
public void spawnUnits(Round r, double delta) { r.state = r.game.stateFactory.create("round-active"); if (r.passedTime > 3) { if (r.waves.Count > r.currentWave) { foreach (KeyValuePair<string, int> entry in r.waves[r.currentWave]) { for (int i = 0; i < entry.Value; i++) { Unit unit = r.game.unitFactory.Create(entry.Key, r); unit.subscribe(); } } r.currentWave++; } else { r.endRound(); } } }
public void SubmitAnswer(Round round, PlayerAnswer playerAnswer) { playerAnswer.Player = playerCtr.RetrievePlayer(Thread.CurrentPrincipal.Identity.Name); roundCtr.SubmitAnswer(round, playerAnswer); }
public async Task Create(CreateRoundRequest requset) { Round round = _mapper.Map <Round>(requset); await _roundRepository.CreateAsync(round); }
public bool CheckIfAllPlayersAnswered(Game game, Round round) { return(roundCtr.CheckIfAllPlayersAnswered(game, round)); }
public void Test1(string roundName, int score, int expectedHandicap) { Round round = RoundRegistry.Instance.Rounds[roundName]; Assert.Equal(expectedHandicap, _service.CalculateHandicap(round, score)); }
public Player RetrieveRoundWinner(Round round) { return(roundCtr.RetrieveRoundWinner(round)); }
/// <summary> /// Метод заполнения бд значениями. /// </summary> /// <param name="context">контекст бд.</param> public static void Initialize(ModelContext context) { context.Database.EnsureCreated(); if (context.Decks.Any()) { return; } var users = new User[] { new User { Name = "Alex" }, new User { Name = "Dima" }, new User { Name = "Andrey" }, new User { Name = "Ilia" } }; foreach (User user in users) { context.Users.Add(user); } context.SaveChanges(); var rooms = new Room[] { new Room { Name = "Room1", OwnerID = 1 }, new Room { Name = "Room2", OwnerID = 2 }, new Room { Name = "Room3", OwnerID = 3 }, new Room { Name = "Room4", OwnerID = 4 } }; foreach (Room room in rooms) { context.Rooms.Add(room); } context.SaveChanges(); var cards = new Card[] { new Card { Value = 0, Description = "zero" }, new Card { Value = 1, Description = "one" }, new Card { Value = 2, Description = "two" }, new Card { Value = 4, Description = "four" } }; var deck = new Deck { Name = "1st deck", Description = "this is 1st deck" }; foreach (Card card in cards) { context.Cards.Add(card); deck.Cards.Add(card); } context.Decks.Add(deck); context.SaveChanges(); var round = new Round { Subject = "test round 2", RoomID = 2, DeckID = 1 }; context.Rounds.Add(round); context.SaveChanges(); var roundCards = new RoundCard[] { new RoundCard { CardValue = cards[1].Value, UserID = 1, RoundID = 1 }, new RoundCard { CardValue = cards[2].Value, UserID = 2, RoundID = 1 } }; foreach (RoundCard card in roundCards) { context.RoundCards.Add(card); } context.SaveChanges(); }
void NextRound() { mCurrentRound = mCurrentRound == Round.Circle ? Round.XX : Round.Circle; m_WellView.SetRound(mCurrentRound); }
private void SaveRound(Round r) { this.mOutput.Rounds.Add(r); }
public bool CheckPlayerAnswers(Game game, Round round) { return(roundCtr.CheckPlayerAnswers(game, round)); }
private Round NewRound(string key, string description) { Round r = new Round(key, description); return(r); }
protected override bool AcceptRound(Round round) => base.AcceptRound(round) && round.Type != RoundTypes.Final;
public async Task <bool> EditRound(int id, Round editedRound) { var result = await _httpDataService.PatchAsJsonAsync($"round/{id}", editedRound, await LoginService.Login()); return(result); }
public ActionResult Details(int id) { Round round = _db.Rounds.Find(id); return(View(round)); }
public ActionResult Generate(int leagueID) { var adminInfo = (LoginModel)Session["AdminInfo"]; if (adminInfo == null) { return(RedirectToAction("Login", "Account", new { area = "" })); } try { var infoLeague = LeagueService.GetLeagueByID(leagueID); var allTeam = LeagueService.GetAllTeamByID(leagueID).ToList(); if (allTeam.Count() == infoLeague.l_teamNumber) { int totalRounds = (infoLeague.l_teamNumber - 1) * 2; int halfSeason = totalRounds / 2; int matchesPerRound = infoLeague.l_teamNumber / 2; DateTime RoundstartAt = infoLeague.l_start; int dateStep = (int)(infoLeague.l_end - infoLeague.l_start).TotalDays / totalRounds - 1; for (int round = 0; round < totalRounds; round++) { var rnd = new Round(); rnd.r_name = $"Round{round + 1}"; rnd.r_start = RoundstartAt; rnd.r_end = RoundstartAt.AddDays(dateStep); rnd.r_league = leagueID; //create round return id int idRound = LeagueService.CreateOneRound(rnd); for (int match = 0; match < matchesPerRound; match++) { //set idround for match //add match int home; int guess; home = (round + match) % (infoLeague.l_teamNumber - 1); guess = (infoLeague.l_teamNumber - 1 - match + round) % (infoLeague.l_teamNumber - 1); if (match == 0) { guess = infoLeague.l_teamNumber - 1; } var vs = new Vs(); if (round < halfSeason) { vs.vs_homeX = allTeam[home]; vs.vs_guessX = allTeam[guess]; } else { vs.vs_homeX = allTeam[guess]; vs.vs_guessX = allTeam[home]; } vs.vs_round = idRound; vs.vs_stadium = vs.vs_homeX.t_stadium; vs.vs_date = rnd.r_start.AddDays(match % dateStep).AddMinutes(60 * 17); vs.vs_league = leagueID; //insert..... LeagueService.InsertVS(vs); } RoundstartAt = rnd.r_end.AddDays(1); } return(Json(new { Result = "successfull" })); } else { return(Json(new { Result = "failure", Mess = "Not Enough" })); } } catch (Exception ex) { return(Json(new { Result = "error" })); } }
public BossKilledEvent(Round currentRound) { _currentRound = currentRound; }
/// <summary> /// Builds the full or short coordinates list and attaches it to the aircraft JSON object. /// </summary> /// <param name="shortCoordinates"></param> /// <param name="firstTimeSeen"></param> /// <param name="aircraftJson"></param> /// <param name="aircraftSnapshot"></param> /// <param name="args"></param> /// <param name="sendAltitude"></param> /// <param name="sendSpeed"></param> private void BuildCoordinatesList(bool shortCoordinates, bool firstTimeSeen, AircraftJson aircraftJson, IAircraft aircraftSnapshot, AircraftListJsonBuilderArgs args, bool sendAltitude, bool sendSpeed) { aircraftJson.ResetTrail = firstTimeSeen || args.ResendTrails || aircraftSnapshot.FirstCoordinateChanged > args.PreviousDataVersion; List <double?> list = new List <double?>(); List <Coordinate> coordinates = shortCoordinates ? aircraftSnapshot.ShortCoordinates : aircraftSnapshot.FullCoordinates; Coordinate lastCoordinate = null; Coordinate nextCoordinate = null; for (var i = 0; i < coordinates.Count; ++i) { var coordinate = nextCoordinate ?? coordinates[i]; nextCoordinate = i + 1 == coordinates.Count ? null : coordinates[i + 1]; if (aircraftJson.ResetTrail || coordinate.DataVersion > args.PreviousDataVersion) { // If this is a full coordinate list then entries can be in here that only record a change in altitude or speed, and not a change in track. Those // entries are to be ignored. They can be identified by having a track that is the same as their immediate neighbours in the list. if (!shortCoordinates && lastCoordinate != null && nextCoordinate != null) { var dupeHeading = lastCoordinate.Heading == coordinate.Heading && coordinate.Heading == nextCoordinate.Heading; if (dupeHeading && !sendAltitude && !sendSpeed) { continue; } var dupeAltitude = lastCoordinate.Altitude == coordinate.Altitude && coordinate.Altitude == nextCoordinate.Altitude; if (sendAltitude && dupeHeading && dupeAltitude) { continue; } var dupeSpeed = lastCoordinate.GroundSpeed == coordinate.GroundSpeed && coordinate.GroundSpeed == nextCoordinate.GroundSpeed; if (sendSpeed && dupeHeading && dupeSpeed) { continue; } } list.Add(Round.Coordinate(coordinate.Latitude)); list.Add(Round.Coordinate(coordinate.Longitude)); if (shortCoordinates) { list.Add(JavascriptHelper.ToJavascriptTicks(coordinate.Tick)); } else { list.Add((int?)coordinate.Heading); } if (sendAltitude) { list.Add(coordinate.Altitude); } else if (sendSpeed) { list.Add(coordinate.GroundSpeed); } } lastCoordinate = coordinate; } if (aircraftSnapshot.Latitude != null && aircraftSnapshot.Longitude != null && (lastCoordinate.Latitude != aircraftSnapshot.Latitude || lastCoordinate.Longitude != aircraftSnapshot.Longitude) && aircraftSnapshot.PositionTimeChanged > args.PreviousDataVersion) { list.Add(Round.Coordinate(aircraftSnapshot.Latitude)); list.Add(Round.Coordinate(aircraftSnapshot.Longitude)); if (shortCoordinates) { list.Add(JavascriptHelper.ToJavascriptTicks(aircraftSnapshot.PositionTime.Value)); } else { list.Add((int?)Round.TrackHeading(aircraftSnapshot.Track)); } if (sendAltitude) { list.Add(Round.TrackAltitude(aircraftSnapshot.Altitude)); } else if (sendSpeed) { list.Add(Round.TrackGroundSpeed(aircraftSnapshot.GroundSpeed)); } } if (list.Count != 0) { if (shortCoordinates) { aircraftJson.ShortCoordinates = list; } else { aircraftJson.FullCoordinates = list; } } }
private static bool CanValueBeSeen(Round round, Estimation estimation, string player) { return(round.Consensus.HasValue || player == estimation.Player); }
public void UpdateBoard(Round roundSelected) { _board.Refresh(roundSelected); }
public static void Log(Round round) { instance.strategy.Log(round); }
/// <summary> /// Copies the aircraft from the snapshot to the JSON object. /// </summary> /// <param name="aircraftListJson"></param> /// <param name="aircraftListSnapshot"></param> /// <param name="args"></param> /// <param name="distances"></param> private void CopyAircraft(AircraftListJson aircraftListJson, List <IAircraft> aircraftListSnapshot, AircraftListJsonBuilderArgs args, Dictionary <int, double?> distances) { var now = Provider.UtcNow; var configuration = _SharedConfiguration.Get(); var positionTimeoutThreshold = now.AddSeconds(-(configuration.BaseStationSettings.DisplayTimeoutSeconds + BoostStalePositionSeconds)); HashSet <int> previousAircraftSet = null; List <int> previousAircraft = args.PreviousAircraft; if (previousAircraft.Count > 15) { previousAircraftSet = new HashSet <int>(previousAircraft); previousAircraft = null; } double?distance = null; for (var i = 0; i < aircraftListSnapshot.Count; ++i) { var aircraftSnapshot = aircraftListSnapshot[i]; if (distances != null) { distances.TryGetValue(aircraftSnapshot.UniqueId, out distance); } var aircraftJson = new AircraftJson() { UniqueId = aircraftSnapshot.UniqueId, IsSatcomFeed = aircraftSnapshot.LastSatcomUpdate != DateTime.MinValue, }; if (!args.OnlyIncludeMessageFields) { aircraftJson.BearingFromHere = GreatCircleMaths.Bearing(args.BrowserLatitude, args.BrowserLongitude, aircraftSnapshot.Latitude, aircraftSnapshot.Longitude, null, false, true); aircraftJson.DistanceFromHere = distance == null ? (double?)null : Math.Round(distance.Value, 2); if (aircraftJson.BearingFromHere != null) { aircraftJson.BearingFromHere = Math.Round(aircraftJson.BearingFromHere.Value, 1); } } var firstTimeSeen = previousAircraft != null ? !previousAircraft.Contains(aircraftSnapshot.UniqueId) : !previousAircraftSet.Contains(aircraftSnapshot.UniqueId); if (firstTimeSeen || aircraftSnapshot.AirPressureInHgChanged > args.PreviousDataVersion) { aircraftJson.AirPressureInHg = aircraftSnapshot.AirPressureInHg; } if (firstTimeSeen || aircraftSnapshot.AltitudeChanged > args.PreviousDataVersion) { aircraftJson.Altitude = aircraftSnapshot.Altitude; } if (firstTimeSeen || aircraftSnapshot.AltitudeTypeChanged > args.PreviousDataVersion) { aircraftJson.AltitudeType = (int)aircraftSnapshot.AltitudeType; } if (firstTimeSeen || aircraftSnapshot.CallsignChanged > args.PreviousDataVersion) { aircraftJson.Callsign = aircraftSnapshot.Callsign; } if (firstTimeSeen || aircraftSnapshot.CallsignIsSuspectChanged > args.PreviousDataVersion) { aircraftJson.CallsignIsSuspect = aircraftSnapshot.CallsignIsSuspect; } if (firstTimeSeen || aircraftSnapshot.GroundSpeedChanged > args.PreviousDataVersion) { aircraftJson.GroundSpeed = Round.GroundSpeed(aircraftSnapshot.GroundSpeed); } if (firstTimeSeen || aircraftSnapshot.EmergencyChanged > args.PreviousDataVersion) { aircraftJson.Emergency = aircraftSnapshot.Emergency; } if (firstTimeSeen || aircraftSnapshot.GeometricAltitudeChanged > args.PreviousDataVersion) { aircraftJson.GeometricAltitude = aircraftSnapshot.GeometricAltitude; } if (firstTimeSeen || args.AlwaysShowIcao || aircraftSnapshot.Icao24Changed > args.PreviousDataVersion) { aircraftJson.Icao24 = aircraftSnapshot.Icao24; } if (firstTimeSeen || aircraftSnapshot.IsTisbChanged > args.PreviousDataVersion) { aircraftJson.IsTisb = aircraftSnapshot.IsTisb; } if (firstTimeSeen || aircraftSnapshot.LatitudeChanged > args.PreviousDataVersion) { aircraftJson.Latitude = Round.Coordinate(aircraftSnapshot.Latitude); } if (firstTimeSeen || aircraftSnapshot.LongitudeChanged > args.PreviousDataVersion) { aircraftJson.Longitude = Round.Coordinate(aircraftSnapshot.Longitude); } if (firstTimeSeen || aircraftSnapshot.OnGroundChanged > args.PreviousDataVersion) { aircraftJson.OnGround = aircraftSnapshot.OnGround; } if (firstTimeSeen || aircraftSnapshot.PositionIsMlatChanged > args.PreviousDataVersion) { aircraftJson.PositionIsMlat = aircraftSnapshot.PositionIsMlat; } if (firstTimeSeen || aircraftSnapshot.SignalLevelChanged > args.PreviousDataVersion) { aircraftJson.HasSignalLevel = aircraftSnapshot.SignalLevel != null; aircraftJson.SignalLevel = aircraftSnapshot.SignalLevel; } if (firstTimeSeen || aircraftSnapshot.SpeedTypeChanged > args.PreviousDataVersion) { aircraftJson.SpeedType = (int)aircraftSnapshot.SpeedType; } if (firstTimeSeen || aircraftSnapshot.SquawkChanged > args.PreviousDataVersion) { aircraftJson.Squawk = String.Format("{0:0000}", aircraftSnapshot.Squawk); } if (firstTimeSeen || aircraftSnapshot.TargetAltitudeChanged > args.PreviousDataVersion) { aircraftJson.TargetAltitude = aircraftSnapshot.TargetAltitude; } if (firstTimeSeen || aircraftSnapshot.TargetTrackChanged > args.PreviousDataVersion) { aircraftJson.TargetTrack = aircraftSnapshot.TargetTrack; } if (firstTimeSeen || aircraftSnapshot.TrackChanged > args.PreviousDataVersion) { aircraftJson.Track = Round.Track(aircraftSnapshot.Track); } if (firstTimeSeen || aircraftSnapshot.TrackIsHeadingChanged > args.PreviousDataVersion) { aircraftJson.TrackIsHeading = aircraftSnapshot.TrackIsHeading; } if (firstTimeSeen || aircraftSnapshot.TransponderTypeChanged > args.PreviousDataVersion) { aircraftJson.TransponderType = (int)aircraftSnapshot.TransponderType; } if (firstTimeSeen || aircraftSnapshot.VerticalRateChanged > args.PreviousDataVersion) { aircraftJson.VerticalRate = aircraftSnapshot.VerticalRate; } if (firstTimeSeen || aircraftSnapshot.VerticalRateTypeChanged > args.PreviousDataVersion) { aircraftJson.VerticalRateType = (int)aircraftSnapshot.VerticalRateType; } if (args.OnlyIncludeMessageFields) { if (aircraftJson.Latitude != null || aircraftJson.Longitude != null || aircraftJson.PositionIsMlat != null) { if (aircraftJson.Latitude == null) { aircraftJson.Latitude = Round.Coordinate(aircraftSnapshot.Latitude); } if (aircraftJson.Longitude == null) { aircraftJson.Longitude = Round.Coordinate(aircraftSnapshot.Longitude); } if (aircraftJson.PositionIsMlat == null) { aircraftJson.PositionIsMlat = aircraftSnapshot.PositionIsMlat; } } if (aircraftJson.Altitude != null || aircraftJson.GeometricAltitude != null || aircraftJson.AltitudeType != null) { if (aircraftJson.Altitude == null) { aircraftJson.Altitude = aircraftSnapshot.Altitude; } if (aircraftJson.AltitudeType == null) { aircraftJson.AltitudeType = (int)aircraftSnapshot.AltitudeType; } if (aircraftJson.GeometricAltitude == null) { aircraftJson.GeometricAltitude = aircraftSnapshot.GeometricAltitude; } } } else if (!args.OnlyIncludeMessageFields) { if (firstTimeSeen || aircraftSnapshot.ConstructionNumberChanged > args.PreviousDataVersion) { aircraftJson.ConstructionNumber = aircraftSnapshot.ConstructionNumber; } if (firstTimeSeen || aircraftSnapshot.CountMessagesReceivedChanged > args.PreviousDataVersion) { aircraftJson.CountMessagesReceived = aircraftSnapshot.CountMessagesReceived; } if (firstTimeSeen || aircraftSnapshot.DestinationChanged > args.PreviousDataVersion) { aircraftJson.Destination = aircraftSnapshot.Destination; } if (firstTimeSeen || aircraftSnapshot.EnginePlacementChanged > args.PreviousDataVersion) { aircraftJson.EnginePlacement = (int)aircraftSnapshot.EnginePlacement; } if (firstTimeSeen || aircraftSnapshot.EngineTypeChanged > args.PreviousDataVersion) { aircraftJson.EngineType = (int)aircraftSnapshot.EngineType; } if (firstTimeSeen || aircraftSnapshot.FirstSeenChanged > args.PreviousDataVersion) { aircraftJson.FirstSeen = aircraftSnapshot.FirstSeen; } if (firstTimeSeen || aircraftSnapshot.FlightsCountChanged > args.PreviousDataVersion) { aircraftJson.FlightsCount = aircraftSnapshot.FlightsCount; } if (firstTimeSeen || aircraftSnapshot.Icao24CountryChanged > args.PreviousDataVersion) { aircraftJson.Icao24Country = aircraftSnapshot.Icao24Country; } if (firstTimeSeen || aircraftSnapshot.Icao24InvalidChanged > args.PreviousDataVersion) { aircraftJson.Icao24Invalid = aircraftSnapshot.Icao24Invalid; } if (firstTimeSeen || aircraftSnapshot.IsInterestingChanged > args.PreviousDataVersion) { aircraftJson.IsInteresting = aircraftSnapshot.IsInteresting; } if (firstTimeSeen || aircraftSnapshot.IsMilitaryChanged > args.PreviousDataVersion) { aircraftJson.IsMilitary = aircraftSnapshot.IsMilitary; } if (firstTimeSeen || aircraftSnapshot.ManufacturerChanged > args.PreviousDataVersion) { aircraftJson.Manufacturer = aircraftSnapshot.Manufacturer; } if (firstTimeSeen || aircraftSnapshot.ModelChanged > args.PreviousDataVersion) { aircraftJson.Model = aircraftSnapshot.Model; } if (firstTimeSeen || aircraftSnapshot.NumberOfEnginesChanged > args.PreviousDataVersion) { aircraftJson.NumberOfEngines = aircraftSnapshot.NumberOfEngines; } if (firstTimeSeen || aircraftSnapshot.OperatorChanged > args.PreviousDataVersion) { aircraftJson.Operator = aircraftSnapshot.Operator; } if (firstTimeSeen || aircraftSnapshot.OperatorIcaoChanged > args.PreviousDataVersion) { aircraftJson.OperatorIcao = aircraftSnapshot.OperatorIcao; } if (firstTimeSeen || aircraftSnapshot.OriginChanged > args.PreviousDataVersion) { aircraftJson.Origin = aircraftSnapshot.Origin; } if (firstTimeSeen || aircraftSnapshot.PictureFileNameChanged > args.PreviousDataVersion) { aircraftJson.HasPicture = !String.IsNullOrEmpty(aircraftSnapshot.PictureFileName); } if (firstTimeSeen || aircraftSnapshot.PictureHeightChanged > args.PreviousDataVersion) { aircraftJson.PictureHeight = aircraftSnapshot.PictureHeight == 0 ? (int?)null : aircraftSnapshot.PictureHeight; } if (firstTimeSeen || aircraftSnapshot.PictureWidthChanged > args.PreviousDataVersion) { aircraftJson.PictureWidth = aircraftSnapshot.PictureWidth == 0 ? (int?)null : aircraftSnapshot.PictureWidth; } if (firstTimeSeen || aircraftSnapshot.PositionTimeChanged > args.PreviousDataVersion) { aircraftJson.PositionTime = aircraftSnapshot.PositionTime == null ? (long?)null : JavascriptHelper.ToJavascriptTicks(aircraftSnapshot.PositionTime.Value); } if (firstTimeSeen || aircraftSnapshot.ReceiverIdChanged > args.PreviousDataVersion) { aircraftJson.ReceiverId = aircraftSnapshot.ReceiverId; } if (firstTimeSeen || aircraftSnapshot.RegistrationChanged > args.PreviousDataVersion) { aircraftJson.Registration = aircraftSnapshot.Registration; } if (firstTimeSeen || aircraftSnapshot.SpeciesChanged > args.PreviousDataVersion) { aircraftJson.Species = (int)aircraftSnapshot.Species; } if (firstTimeSeen || aircraftSnapshot.TypeChanged > args.PreviousDataVersion) { aircraftJson.Type = aircraftSnapshot.Type; } if (firstTimeSeen || aircraftSnapshot.UserTagChanged > args.PreviousDataVersion) { aircraftJson.UserTag = aircraftSnapshot.UserTag; } if (firstTimeSeen || aircraftSnapshot.WakeTurbulenceCategoryChanged > args.PreviousDataVersion) { aircraftJson.WakeTurbulenceCategory = (int)aircraftSnapshot.WakeTurbulenceCategory; } if (firstTimeSeen || aircraftSnapshot.YearBuiltChanged > args.PreviousDataVersion) { aircraftJson.YearBuilt = aircraftSnapshot.YearBuilt; } if (aircraftSnapshot.Stopovers.Count > 0 && (firstTimeSeen || aircraftSnapshot.StopoversChanged > args.PreviousDataVersion)) { aircraftJson.Stopovers = new List <string>(); aircraftJson.Stopovers.AddRange(aircraftSnapshot.Stopovers); } aircraftJson.SecondsTracked = (long)((now - aircraftSnapshot.FirstSeen).TotalSeconds); aircraftJson.PositionIsStale = aircraftSnapshot.LastSatcomUpdate == DateTime.MinValue && // Never flag satcom aircraft as having a stale position aircraftSnapshot.PositionTime != null && aircraftSnapshot.PositionTime < positionTimeoutThreshold ? true : (bool?)null; } if (args.TrailType != TrailType.None) { var hasTrail = false; var isShort = false; var showAltitude = false; var showSpeed = false; switch (args.TrailType) { case TrailType.Short: isShort = true; hasTrail = aircraftSnapshot.ShortCoordinates.Count > 0; break; case TrailType.ShortAltitude: showAltitude = true; aircraftJson.TrailType = "a"; goto case TrailType.Short; case TrailType.ShortSpeed: showSpeed = true; aircraftJson.TrailType = "s"; goto case TrailType.Short; case TrailType.Full: hasTrail = aircraftSnapshot.FullCoordinates.Count > 0; break; case TrailType.FullAltitude: showAltitude = true; aircraftJson.TrailType = "a"; goto case TrailType.Full; case TrailType.FullSpeed: showSpeed = true; aircraftJson.TrailType = "s"; goto case TrailType.Full; } if (hasTrail) { BuildCoordinatesList(isShort, firstTimeSeen, aircraftJson, aircraftSnapshot, args, showAltitude, showSpeed); } } aircraftListJson.Aircraft.Add(aircraftJson); } }
public TimeSpan GetInputRegistrationTimeout(Round round) => round.IsBlameRound ? BlameInputRegistrationTimeout : StandardInputRegistrationTimeout;
private void GenerateLeague(Edition edition) { var teamsNumber = edition.Tournement.numberOfTeams; var leagueStage = new LeagueStage(edition); var first = leagueStage.Teams[0]; var queueH = new Queue <Team>(); var queueA = new Queue <Team>(); queueH.Enqueue(first); queueA.Enqueue(leagueStage.Teams[1]); for (var i = 2; i <= teamsNumber / 2; i++) { queueH.Enqueue(leagueStage.Teams[i]); queueA.Enqueue(leagueStage.Teams[i + (teamsNumber / 2) - 1]); } Team TopQueueH; Team TopQueueA; // OK //TODO DELETE leagueStage.Rounds = new List <Round>(); for (var i = 0; i < (teamsNumber - 1); i++) { var rd = new Round(); rd.Stage = leagueStage; leagueStage.Rounds.Add(rd); // TODO DELETE //rd.Games = new List<Game>(); var j = 0; while (j < teamsNumber / 2) { TopQueueH = queueH.Dequeue(); TopQueueA = queueA.Dequeue(); var game = new Game(); game.Round = rd; game.Team1 = TopQueueH; game.Team2 = TopQueueA; rd.Games.Add(game); if (TopQueueH == first) { queueH.Enqueue(TopQueueH); queueH.Enqueue(TopQueueA); } else if (j == ((teamsNumber / 2) - 1)) { queueA.Enqueue(TopQueueA); queueA.Enqueue(TopQueueH); } else { queueH.Enqueue(TopQueueH); queueA.Enqueue(TopQueueA); } j++; } } dbContext.Stages.Add(leagueStage); }
/// <summary> /// bltの回転機能つき。 /// </summary> /// <param name="src"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="srcRect"></param> /// <param name="rad"></param> /// <param name="rate"></param> /// <param name="bx"></param> /// <param name="by"></param> /// <remarks> /// <para> /// 指定のテクスチャを転送先の(x,y)に半径rで描画します。 /// </para> /// <para> /// radの単位は、0~512で一周(2π)となる角度。 /// 回転の方向は、右まわり(時計まわり)。 /// rateは、拡大率。1.0ならば等倍。 /// (bx,by)は転送元の画像の、回転中心。 /// srcRectは転送元矩形。nullならば転送元テクスチャ全体。 /// </para> /// </remarks> public void BltRotate(ITexture src, int x, int y, Rect srcRect, int rad, float rate, int bx, int by) { if (src == null) { return; } int sx, sy; // 転送元サイズ if (srcRect == null) { srcRect = new Rect(0, 0, src.Width, src.Height); } { sx = (int)(srcRect.Right - srcRect.Left); sy = (int)(srcRect.Bottom - srcRect.Top); } if (sx == 0 || sy == 0) { return; } int dx, dy; // 転送先サイズ dx = (int)(sx * rate); dy = (int)(sy * rate); if (dx == 0 || dy == 0) { return; } // 転送元の回転中心 bx = (int)(bx * rate); by = (int)(by * rate); // 転送後の座標を計算する int nSin = SinTable.Instance.Sin(rad); int nCos = SinTable.Instance.Cos(rad); Point[] dstPoints = new Point[4]; // 0.5での丸めのための修正項 → 0x8000 int px = x + bx; int py = y + by; int ax0 = -bx; int ay0 = -by; dstPoints[0].X = Round.RShift((int)(ax0 * nCos - ay0 * nSin), 16) + px; dstPoints[0].Y = Round.RShift((int)(ax0 * nSin + ay0 * nCos), 16) + py; int ax1 = dx - bx; int ay1 = -by; dstPoints[1].X = Round.RShift((int)(ax1 * nCos - ay1 * nSin), 16) + px; dstPoints[1].Y = Round.RShift((int)(ax1 * nSin + ay1 * nCos), 16) + py; int ax2 = dx - bx; int ay2 = dy - by; dstPoints[2].X = Round.RShift((int)(ax2 * nCos - ay2 * nSin), 16) + px; dstPoints[2].Y = Round.RShift((int)(ax2 * nSin + ay2 * nCos), 16) + py; int ax3 = -bx; int ay3 = dy - by; dstPoints[3].X = Round.RShift((int)(ax3 * nCos - ay3 * nSin), 16) + px; dstPoints[3].Y = Round.RShift((int)(ax3 * nSin + ay3 * nCos), 16) + py; // 変数無駄な代入が多いが、最適化されるかなぁ(´Д`) src.Blt(DrawContext, srcRect, dstPoints); }
public void MapChange(string name, GrandTheftMultiplayer.Server.Util.XmlGroup map) { EndRound(); var round = new Round(); #region Objectives foreach (var element in map.getElementsByType("objective")) { var obj = new Objective(); if (element.hasElementData("id")) { obj.Id = element.getElementData <int>("id"); } obj.Position = new Vector3(element.getElementData <float>("posX"), element.getElementData <float>("posY"), element.getElementData <float>("posZ")); if (element.hasElementData("range")) { obj.Range = element.getElementData <float>("range"); } obj.name = element.getElementData <string>("name"); if (element.hasElementData("timer")) { obj.Timer = element.getElementData <int>("timer"); } if (element.hasElementData("required")) { var listStr = element.getElementData <string>("required"); obj.RequiredObjectives = listStr.Split(',').Select(id => int.Parse(id, CultureInfo.InvariantCulture)).ToList(); } round.Objectives.Add(obj); } #endregion #region Spawnpoints foreach (var element in map.getElementsByType("spawnpoint")) { var sp = new Spawnpoint(); sp.Team = element.getElementData <int>("team"); sp.Heading = element.getElementData <float>("heading"); sp.Position = new Vector3(element.getElementData <float>("posX"), element.getElementData <float>("posY"), element.getElementData <float>("posZ")); sp.Skins = element.getElementData <string>("skins") .Split(',') .Select(s => API.pedNameToModel(s)) .ToArray(); var guns = element.getElementData <string>("weapons") .Split(',') .Select(w => API.weaponNameToModel(w)); var ammos = element.getElementData <string>("ammo") .Split(',') .Select(w => int.Parse(w, CultureInfo.InvariantCulture)); sp.Weapons = guns.ToArray(); sp.Ammo = ammos.ToArray(); if (element.hasElementData("objectives")) { var objectives = element.getElementData <string>("objectives") .Split(',') .Select(w => int.Parse(w, CultureInfo.InvariantCulture)); sp.RequiredObjectives = objectives.ToArray(); } round.Spawnpoints.Add(sp); } #endregion StartRound(round); }
public Game PlayAGame() { //instantiate a Player and give a value to the Name all at once. Player computer = new Player() { Name = "Computer" }; //try to find an existing player named "computer" if (_context.Players.Any(x => x.Name == "Computer")) { computer = _context.Players.Where(x => x.Name == "Computer").FirstOrDefault(); } else { computer.Name = "Computer"; _context.Players.Add(computer); //add the computer to List<Player> players _context.SaveChanges(); } Player p1; //the out variable for the player if (!_cache.TryGetValue("loggedInPlayer", out p1)) { _logger.LogInformation("There was no loggedInPlayer in the cache"); throw new NullReferenceException("There was no loggedInPlayer in the cache"); } p1 = _context.Players.Where(x => x.PlayerId == p1.PlayerId).FirstOrDefault(); Game game = new Game(); // create a game //_context.Players.Add(p1); game.Player1 = p1; // game.Computer = computer; // while (game.winner.Name == "null") { Round round = new Round(); //declare a round for this iteration round.player1 = p1; // add user (p1) to this round round.Computer = computer; // add computer to this round //get the choices for the 2 players and insert the players choices directly into the round round.p1Choice = Rps_GameMethods.GetRandomChoice(); //this will give a random number starting at 0 to arg-1; round.ComputerChoice = Rps_GameMethods.GetRandomChoice(); round.Outcome = Rps_GameMethods.GetRoundWinner(round); //check the choices to see who won. _context.Rounds.Add(round); _context.SaveChanges(); game.rounds.Add(round); //add this round to the games' List of rounds int gameWinner = Rps_GameMethods.GetWinner(game); //get a number ot say is p1(1) or computer(2) won //assign the winner to the game and increment wins and losses for both if (gameWinner == 1) { game.winner = p1; p1.Wins++; //increments wins and losses. computer.Losses++; //increments wins and losses. } else if (gameWinner == 2) { game.winner = computer; p1.Losses++; //increments wins and losses. computer.Wins++; //increments wins and losses. } } //end of rounds loop _context.Games.Add(game); //save the game _context.SaveChanges(); return(game); }
public DxStoreStateMachine(Policy policy, DxStoreInstance instance, INodeEndPoints <ServiceEndpoint> nodeEndPoints, IStorage <string, DxStoreCommand> storage, GroupMembersMesh mesh, Counters perfCounter, Round <string>?roundInitial) : base(nodeEndPoints, mesh, storage, policy, null, perfCounter, roundInitial) { this.instance = instance; this.self = nodeEndPoints.Self; this.localDataStore = instance.LocalDataStore; this.Mesh = mesh; this.truncator = new PeriodicPaxosTrancator(instance); }
/// <summary> /// Submits the hand generic. /// </summary> /// <param name="hand">The hand.</param> /// <param name="teamId">The team identifier.</param> /// <param name="game">The game.</param> /// <returns></returns> private OperationOutcome SubmitHandGeneric(Hand hand, Guid teamId, Game game) { System.Threading.Thread.Sleep(Properties.Settings.Default.ThinkTimeInMiliSeconds); var outcome = new OperationOutcome { Result = false, Error = "" }; var gameAdapter = new GameAdapter(); var roundAdapter = new RoundAdapter(); var gameProvider = new GameProvider(); if (game.GameState == GameState.Complete || game.GameState == GameState.WaitingForPlayers) { outcome.Error = "Game not in playable state."; return(outcome); } if (game.GameState == GameState.Player1Hand) { if (game.Team1.Id == teamId) { var round = new Round { GameId = game.Id, Team1Hand = hand, SequenceNumber = roundAdapter.GetNextRoundNumber(game.Id) }; roundAdapter.CreateRound(round); gameAdapter.UpdateGameState(GameState.Player2Hand, game.Id); outcome.Result = true; } else { outcome.Error = "Not team 1's turn."; return(outcome); } } else if (game.GameState == GameState.Player2Hand) { if (game.Team2.Id == teamId) { var round = roundAdapter.GetRoundForPlayerTwo(game.Id); round.Team2Hand = hand; round.Result = DetermineWinner(round.Team1Hand, round.Team2Hand); roundAdapter.UpdateRound(round); gameAdapter.UpdateGameState(GameState.Player1Hand, game.Id); } else { outcome.Error = "Not team 2's turn."; return(outcome); } } roundAdapter.SaveChanges(); gameAdapter.SaveChanges(); gameProvider.CompleteRound(game.Id); outcome.Result = true; return(outcome); }
public async Task <IActionResult> Create([Bind("Id,Name,Date,Location,NumberOfRounds")] Tournament tournament) { //Get players unassigned to games var players = await _context.Players .Include(p => p.MyGames) .Include(p => p.TheirGames).ToListAsync(); var unassignedPlayers = players.Where(p => p.MyGames == null || p.MyGames.Count() == 0 && p.TheirGames == null || p.TheirGames.Count() == 0).ToList(); if (unassignedPlayers.Count < 6) { return(View("NoPlayers")); } if (tournament.NumberOfRounds > (unassignedPlayers.Count() + 1) / 2) { return(View("TooManyRounds")); } var user = await GetCurrentUserAsync(); tournament.userId = user.Id; // Create new tournament and round Round round = null; if (ModelState.IsValid) { _context.Add(tournament); await _context.SaveChangesAsync(); Round newRound = new Round() { Number = 1, TournamentId = tournament.Id }; _context.Add(newRound); await _context.SaveChangesAsync(); round = newRound; } TournamentState.setcurrentTournament(tournament); TournamentState.currentRound.Number = 1; // If number of players is odd, find or generate a 'bye' player if (unassignedPlayers.Count % 2 != 0) { var byePlayerOrNull = players.SingleOrDefault(p => p.LastName == "Bye"); if (byePlayerOrNull == null) { var byePlayer = new Player() { FirstName = " ", LastName = "Bye", }; _context.Add(byePlayer); await _context.SaveChangesAsync(); unassignedPlayers.Add(byePlayer); } else { unassignedPlayers.Add(byePlayerOrNull); } } foreach (var player in unassignedPlayers) { TournamentState.currentPlayers.Add(player); } //Sort players randomly var rand = new Random(); var randomPlayers = unassignedPlayers.OrderBy(p => rand.NextDouble()).ToList(); int numberOfGames = randomPlayers.Count / 2; var bye = randomPlayers.Find(p => p.LastName == "Bye"); //Assign players to games, create tables for (int i = 0; i < numberOfGames; i++) { var newTable = new PhysicalTable(); newTable.Number = i + 1; _context.Add(newTable); await _context.SaveChangesAsync(); var game = new Game(); game.PhysicalTableId = newTable.Id; game.RoundId = round.Id; game.PlayerOneId = randomPlayers[0].Id; randomPlayers.Remove(randomPlayers[0]); game.PlayerTwoId = randomPlayers[0].Id; randomPlayers.Remove(randomPlayers[0]); //The opponent of the bye player automatically wins if (game.PlayerOneId == bye.Id) { game.PlayerTwoScore = 1; } else if (game.PlayerTwoId == bye.Id) { game.PlayerOneScore = 1; } _context.Add(game); } await _context.SaveChangesAsync(); return(RedirectToAction("IndexUncompleted", "Games")); }
public Round GetRoundFromDatabase() { Round currentRound = _context.Rounds.SingleOrDefault(r => r.RoundId == GetRoundIdFromSession()); return(currentRound); }
public BuiltInFunctions() { // Text Functions["len"] = new Len(); Functions["lower"] = new Lower(); Functions["upper"] = new Upper(); Functions["left"] = new Left(); Functions["right"] = new Right(); Functions["mid"] = new Mid(); Functions["replace"] = new Replace(); Functions["rept"] = new Rept(); Functions["substitute"] = new Substitute(); Functions["concatenate"] = new Concatenate(); Functions["char"] = new CharFunction(); Functions["exact"] = new Exact(); Functions["find"] = new Find(); Functions["fixed"] = new Fixed(); Functions["proper"] = new Proper(); Functions["search"] = new Search(); Functions["text"] = new Text.Text(); Functions["t"] = new T(); Functions["hyperlink"] = new Hyperlink(); Functions["value"] = new Value(); // Numbers Functions["int"] = new CInt(); // Math Functions["abs"] = new Abs(); Functions["asin"] = new Asin(); Functions["asinh"] = new Asinh(); Functions["cos"] = new Cos(); Functions["cosh"] = new Cosh(); Functions["power"] = new Power(); Functions["sign"] = new Sign(); Functions["sqrt"] = new Sqrt(); Functions["sqrtpi"] = new SqrtPi(); Functions["pi"] = new Pi(); Functions["product"] = new Product(); Functions["ceiling"] = new Ceiling(); Functions["count"] = new Count(); Functions["counta"] = new CountA(); Functions["countblank"] = new CountBlank(); Functions["countif"] = new CountIf(); Functions["countifs"] = new CountIfs(); Functions["fact"] = new Fact(); Functions["floor"] = new Floor(); Functions["sin"] = new Sin(); Functions["sinh"] = new Sinh(); Functions["sum"] = new Sum(); Functions["sumif"] = new SumIf(); Functions["sumifs"] = new SumIfs(); Functions["sumproduct"] = new SumProduct(); Functions["sumsq"] = new Sumsq(); Functions["stdev"] = new Stdev(); Functions["stdevp"] = new StdevP(); Functions["stdev.s"] = new Stdev(); Functions["stdev.p"] = new StdevP(); Functions["subtotal"] = new Subtotal(); Functions["exp"] = new Exp(); Functions["log"] = new Log(); Functions["log10"] = new Log10(); Functions["ln"] = new Ln(); Functions["max"] = new Max(); Functions["maxa"] = new Maxa(); Functions["median"] = new Median(); Functions["min"] = new Min(); Functions["mina"] = new Mina(); Functions["mod"] = new Mod(); Functions["average"] = new Average(); Functions["averagea"] = new AverageA(); Functions["averageif"] = new AverageIf(); Functions["averageifs"] = new AverageIfs(); Functions["round"] = new Round(); Functions["rounddown"] = new Rounddown(); Functions["roundup"] = new Roundup(); Functions["rand"] = new Rand(); Functions["randbetween"] = new RandBetween(); Functions["rank"] = new Rank(); Functions["rank.eq"] = new Rank(); Functions["rank.avg"] = new Rank(true); Functions["quotient"] = new Quotient(); Functions["trunc"] = new Trunc(); Functions["tan"] = new Tan(); Functions["tanh"] = new Tanh(); Functions["atan"] = new Atan(); Functions["atan2"] = new Atan2(); Functions["atanh"] = new Atanh(); Functions["acos"] = new Acos(); Functions["acosh"] = new Acosh(); Functions["var"] = new Var(); Functions["varp"] = new VarP(); Functions["large"] = new Large(); Functions["small"] = new Small(); Functions["degrees"] = new Degrees(); // Information Functions["isblank"] = new IsBlank(); Functions["isnumber"] = new IsNumber(); Functions["istext"] = new IsText(); Functions["isnontext"] = new IsNonText(); Functions["iserror"] = new IsError(); Functions["iserr"] = new IsErr(); Functions["error.type"] = new ErrorType(); Functions["iseven"] = new IsEven(); Functions["isodd"] = new IsOdd(); Functions["islogical"] = new IsLogical(); Functions["isna"] = new IsNa(); Functions["na"] = new Na(); Functions["n"] = new N(); // Logical Functions["if"] = new If(); Functions["iferror"] = new IfError(); Functions["ifna"] = new IfNa(); Functions["not"] = new Not(); Functions["and"] = new And(); Functions["or"] = new Or(); Functions["true"] = new True(); Functions["false"] = new False(); // Reference and lookup Functions["address"] = new Address(); Functions["hlookup"] = new HLookup(); Functions["vlookup"] = new VLookup(); Functions["lookup"] = new Lookup(); Functions["match"] = new Match(); Functions["row"] = new Row() { SkipArgumentEvaluation = true }; Functions["rows"] = new Rows() { SkipArgumentEvaluation = true }; Functions["column"] = new Column() { SkipArgumentEvaluation = true }; Functions["columns"] = new Columns() { SkipArgumentEvaluation = true }; Functions["choose"] = new Choose(); Functions["index"] = new Index(); Functions["indirect"] = new Indirect(); Functions["offset"] = new Offset() { SkipArgumentEvaluation = true }; // Date Functions["date"] = new Date(); Functions["today"] = new Today(); Functions["now"] = new Now(); Functions["day"] = new Day(); Functions["month"] = new Month(); Functions["year"] = new Year(); Functions["time"] = new Time(); Functions["hour"] = new Hour(); Functions["minute"] = new Minute(); Functions["second"] = new Second(); Functions["weeknum"] = new Weeknum(); Functions["weekday"] = new Weekday(); Functions["days360"] = new Days360(); Functions["yearfrac"] = new Yearfrac(); Functions["edate"] = new Edate(); Functions["eomonth"] = new Eomonth(); Functions["isoweeknum"] = new IsoWeekNum(); Functions["workday"] = new Workday(); Functions["networkdays"] = new Networkdays(); Functions["networkdays.intl"] = new NetworkdaysIntl(); Functions["datevalue"] = new DateValue(); Functions["timevalue"] = new TimeValue(); // Database Functions["dget"] = new Dget(); Functions["dcount"] = new Dcount(); Functions["dcounta"] = new DcountA(); Functions["dmax"] = new Dmax(); Functions["dmin"] = new Dmin(); Functions["dsum"] = new Dsum(); Functions["daverage"] = new Daverage(); Functions["dvar"] = new Dvar(); Functions["dvarp"] = new Dvarp(); }