static void method(Best best) { var _best = best; best.num = 100; Debug.Assert(_best.num == 10); }
private void OnTriggerExit2D(Collider2D triggerObj) { if (triggerObj.gameObject.CompareTag("Talkable")) { talk.enabled = false; } else if (triggerObj.gameObject.CompareTag("Untalkable")) { talk.enabled = false; } else if (triggerObj.gameObject.CompareTag("MiniGame")) { MiniGame1.SetBool("isOpen", false); MiniGame2.SetBool("isOpen", false); MiniGame3.SetBool("isOpen", false); MiniGame4.SetBool("isOpen", false); MiniGame5.SetBool("isOpen", false); } else if (triggerObj.gameObject.CompareTag("Suspect")) { Antique.SetActive(!true); Husband.SetActive(!true); Sister.SetActive(!true); Best.SetActive(!true); } }
List <Individual> torneioSelection(List <Individual> oldpop, int num) { List <Individual> selectedInds = new List <Individual>(); List <Individual> listaTorneio = new List <Individual>(); int popsize = oldpop.Count; // Repete o numero de individuos que há na população for (int i = 0; i < num; i++) { // Limpa a lista do torneio, pois cada um é independente listaTorneio.Clear(); for (int j = 0; j < tam; j++) { // Escolhe individuo aleatório Individual ind = oldpop[Random.Range(0, popsize)]; listaTorneio.Add(ind); } // Compara os individuos selecionados em relação à sua aptidão IComparer <Individual> aptidao = new Best(); // Ordenação da aptidão por ordem crescente listaTorneio.Sort(aptidao); // Vai buscar melhor individuo Individual bestIndividuo = listaTorneio[0]; selectedInds.Add(bestIndividuo.Clone()); //we return copys of the selected individuals*/ } return(selectedInds); }
private void ComputerTurn() { Best best = new Best(); best.x = best.y = 0; best.max = -1; for (int x = 0; x != boardSize; x++) { for (int y = 0; y != boardSize; y++) { if (chessField [x, y] == 0) { int attackScore = getScore(x, y, 2, 0); int guardScore = getScore(x, y, 1, 1); int score = attackScore + guardScore; if (score > best.max) { best.x = x; best.y = y; best.max = score; } } } } MoveChess(best.x, best.y); }
public override int GetHashCode() { int hash = 1; if (WeatherId != 0) { hash ^= WeatherId.GetHashCode(); } if (Name.Length != 0) { hash ^= Name.GetHashCode(); } if (VisitingNum != 0) { hash ^= VisitingNum.GetHashCode(); } if (Best != 0) { hash ^= Best.GetHashCode(); } if (Better != 0) { hash ^= Better.GetHashCode(); } if (Same != 0) { hash ^= Same.GetHashCode(); } return(hash); }
public static void Main(string[] args) { Console.WriteLine("==== InKeyWord ====\n"); var iobj = new Best <object>(); IContravariant <string> istr; istr = iobj; }
private void OnTriggerEnter2D(Collider2D triggerObj) { if (triggerObj.gameObject.CompareTag("Talkable")) { talk.enabled = true; buttons.SetActive(true); Dial = triggerObj.gameObject.GetComponent <DialogDisplay>(); PlayerData.Dial = Dial; PlayerData.speakerUILeft = Dial.speakerLeft.GetComponent <SpeakerUI>(); PlayerData.speakerUIRight = Dial.speakerRight.GetComponent <SpeakerUI>(); PlayerData.speakerUILeft.Speaker = Dial.conversation.speakerLeft; PlayerData.speakerUIRight.Speaker = Dial.conversation.speakerRight; } if (triggerObj.gameObject.CompareTag("MiniGame")) { if (triggerObj.gameObject.name == "Minigame1") { MiniGame1.SetBool("isOpen", true); } else if (triggerObj.gameObject.name == "Minigame2") { MiniGame2.SetBool("isOpen", true); } else if (triggerObj.gameObject.name == "Minigame3") { MiniGame3.SetBool("isOpen", true); } else if (triggerObj.gameObject.name == "Minigame4") { MiniGame4.SetBool("isOpen", true); } else if (triggerObj.gameObject.name == "Minigame5") { MiniGame5.SetBool("isOpen", true); } } if (triggerObj.gameObject.CompareTag("Suspect")) { if (triggerObj.gameObject.name == "Antique") { Antique.SetActive(true); } else if (triggerObj.gameObject.name == "Husband") { Husband.SetActive(true); } else if (triggerObj.gameObject.name == "Sissy") { Sister.SetActive(true); } else if (triggerObj.gameObject.name == "Besty") { Best.SetActive(true); } } }
public static void Main(string[] args) { Console.WriteLine("==== PassStruct ====\n"); var best = new Best() { num = 10 }; method(best); }
private Best FindBest(List <SearchNode> nodes) { var best = new Best(_width); foreach (var node in nodes) { var value = _heuristic.Evaluate(node.State); best.Add(node, value); } return(best); }
public override Solucion ejecutar() { int i = 0; do { Solucion R = tweak(Best.copy()); if (fx.getCalidad(R) > fx.getCalidad(Best)) { Best = R.copy(); } i++; } while (i < numIteraciones); return(Best); }
// Use this for initialization void Start() { path = Application.persistentDataPath + "\\"; StreamReader sr = null; try{ sr = File.OpenText(path + "game.dat"); }catch { Debug.Log("cant open file"); } tmpDES = sr.ReadLine(); sr.Close(); sr.Dispose(); tmp = Best.DecryptDES(tmpDES, "asdasfsfa"); bestText.text = tmp; }
void SetBestValue() { /* 2. evaluate current population */ for (int i = 0; i < population.Count; i++) { values[i] = Evaluate(population[i].ToArray()); } currentBest = GetCurrentBest(); if (bestValue == 0 || bestValue > currentBest.BestValue) { best = population[currentBest.BestPosition].Clone(); bestValue = currentBest.BestValue; unchangedGenerations = 0; } else { unchangedGenerations += 1; } }
public void DoCompMove(bool thinkAboutIt) { Best compMove; if (thinkAboutIt) { compMove = t.ChooseMove(TicTacToe.COMPUTER); } else { compMove = new Best(0, gameNum % 3, gameNum / 3); gameNum = (gameNum + 1) % 9; } MessageBox.Show(" ROW = " + compMove.row + " COL = " + compMove.column); squares[compMove.row, compMove.column].Text = computerSide; squares[compMove.row, compMove.column].Enabled = true; t.PlayMove(TicTacToe.COMPUTER, compMove.row, compMove.column); }
void InitData() { running = false; POPULATION_SIZE = 30; // 30 CROSSOVER_PROBABILITY = 0.9; // 0.9 or 0.7 MUTATION_PROBABILITY = 0.01; // 0.01 or 0.05 unchangedGenerations = 0; mutationTimes = 0; bestValue = 0; best = new List <int>(); currentGeneration = 0; currentBest = null; population = new List <List <int> >(); values = new int[POPULATION_SIZE]; fitnessValues = new double[POPULATION_SIZE]; roulette = new double[POPULATION_SIZE]; }
/// <summary> /// Randamas potimalesnis budas pastatyti sandelius /// </summary> /// <param name="distances">distances listas</param> /// <param name="flows">flows listas</param> /// <param name="newWarehouses">nauji sandeliai</param> /// <param name="Price">sandeliu kastu</param> private static void WarehouseOptimization(List <Distance> distances, List <Flow> flows, out string[] newWarehouses, out double Price) { //Visu skirtinu miestu listas List <String> cities = distances.GroupBy(x => x.getDestination()) .Select(y => y.First().getDestination()).ToList(); //Geriausiu miestu masyvas List <String> Best = new List <string>(); Random rnd = new Random(); Price = Double.MaxValue; newWarehouses = new string[5]; //Optimalesniu miestu ieskojimas for (int i = 0; i < 200; i++) { for (int j = 0; j < 5; j++) { int randomNumber = rnd.Next(0, cities.Count); newWarehouses[j] = cities[randomNumber]; } //Skaiciuojami kastai su naujai atrinkaitais miestais double temp = CountPriceWithWarehouses(distances, flows, newWarehouses); //Tikrinama ar kaina yra mazesne if (temp < Price) { Price = temp; Best = new List <string>(); for (int j = 0; j < 5; j++) { Best.Add(newWarehouses[j]); } Array.Clear(newWarehouses, 0, newWarehouses.Length); } Console.WriteLine(Price); for (int k = 0; k < Best.Count; k++) { Console.WriteLine(Best[k]); } Best.Clear(); } }
public static void Main(string[] args) { Console.WriteLine("==== SwitchNullable ====\n"); // var hi = new Best(); Best hi = null; foreach (var i in new [] { 1, 2 }) { switch (hi?.day) { case DayOfWeek.Thursday: { Console.WriteLine("thursday"); break; } default: Console.WriteLine("default"); break; } } }
public override string ToString() { var builder = new StringBuilder(); builder.AppendFormat("\nRank: {0}\n", Rank); builder.AppendFormat("Best: {0}\n", Best != null ? Best.ToString() : string.Empty); builder.Append("Context: ["); if (Context != null) { Context.Each((leader, index) => { builder.Append(leader); if (index < (Context.Count - 1)) { builder.Append(", "); } }); } builder.Append("]\n"); return(builder.ToString()); }
protected override void OnNavigatedTo(NavigationEventArgs e) { string friendName; NavigationContext.QueryString.TryGetValue("friend-name", out friendName); if (friendName == null) { NavigationService.GoBack(); return; } Friend friend = App.IsolatedStorage.UserAccount.Friends.First(f => f.Name == friendName); if (friend == null || App.IsolatedStorage.FriendsBests == null) { NavigationService.GoBack(); return; } _friend = friend; LabelUserName.DataContext = App.IsolatedStorage.UserAccount.Friends.First(f => f.Name == friendName); LabelDisplayName.DataContext = App.IsolatedStorage.UserAccount.Friends.First(f => f.Name == friendName); Best usersBests; App.IsolatedStorage.FriendsBests.TryGetValue(friend.Name, out usersBests); if (usersBests == null) { usersBests = new Best { BestFriends = new string[] {}, Score = 0 }; } DataContext = usersBests; base.OnNavigatedTo(e); }
public void Start() { if (_BeginningSide == Side.Computer) { Best best = this.ChooseMove(Side.Computer, -1, 1); _Grid[best.move.Row, best.move.Column] = Side.Computer; if (OnGridStatusChanged != null) { OnGridStatusChanged(best.move.Row, best.move.Column); } bool isEnd; Side WinnerSide = IsEnd(out isEnd); if (isEnd && OnGameOver != null) { OnGameOver(WinnerSide); } } else { _BeginningSide = Side.Computer; } }
List <Individual> BreedPopulation() { List <Individual> newpop = new List <Individual>(); // Sem elitismo if (elitismo == 0) { //breed individuals and place them on new population. We'll apply crossover and mutation later while (newpop.Count < populationSize) { List <Individual> selectedInds = selection.selectIndividuals(population, 2); //we should propably always select pairs of individuals for (int i = 0; i < selectedInds.Count; i++) { if (newpop.Count < populationSize) { newpop.Add(selectedInds[i]); //added individuals are already copys, so we can apply crossover and mutation directly } else //discard any excess individuals { selectedInds.RemoveAt(i); } } //apply crossover between pairs of individuals and mutation to each one while (selectedInds.Count > 1) { selectedInds[0].Crossover(selectedInds[1], crossoverProbability); selectedInds[0].Mutate(mutationProbability); selectedInds[1].Mutate(mutationProbability); selectedInds.RemoveRange(0, 2); } if (selectedInds.Count == 1) { selectedInds[0].Mutate(mutationProbability); selectedInds.RemoveAt(0); } } } // Com elitismo else { List <Individual> elite = new List <Individual>(); //breed individuals and place them on new population. We'll apply crossover and mutation later while (newpop.Count < populationSize) { List <Individual> selectedInds = selection.selectIndividuals(population, 2); //we should propably always select pairs of individuals elite.Add(selectedInds[0]); elite.Add(selectedInds[1]); //newpop = selectedInds.GetRange(0, indElitismo); for (int i = 0; i < selectedInds.Count; i++) { if (newpop.Count < populationSize) { newpop.Add(selectedInds[i]); //added individuals are already copys, so we can apply crossover and mutation directly } else //discard any excess individuals { selectedInds.RemoveAt(i); } } //apply crossover between pairs of individuals and mutation to each one while (selectedInds.Count > 1) { selectedInds[0].Crossover(selectedInds[1], crossoverProbability); selectedInds[0].Mutate(mutationProbability); selectedInds[1].Mutate(mutationProbability); selectedInds.RemoveRange(0, 2); } if (selectedInds.Count == 1) { selectedInds[0].Mutate(mutationProbability); selectedInds.RemoveAt(0); } } // Compara os individuos selecionados em relação à sua aptidão IComparer <Individual> aptidao = new Best(); // Ordenação da aptidão por ordem crescente // Ordenação da lista para depois escolher sempre os melhores dos melhores elite.Sort(aptidao); for (int i = 0; i < indElitismo; i++) { newpop[i] = elite[i]; } } return(newpop); }
/// <summary> /// Returns a string representation of the <see cref="Particle"/>. /// </summary> public override string ToString() { return(Best.ToString()); }
public Population Breed() { if (indexes == null) { indexes = new List <int>(); for (var i = 0; i < Individuals.Count; i++) { for (var j = 0; j <= i; j++) { indexes.Add(j); } } indexes.Sort(); } var ranked = Rank().Individuals.ToList(); var bitmap = new System.Drawing.Bitmap(32, 32); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap); foreach (var chromosome in ranked.First().Chromosomes) { var argb = (chromosome.Color.A << 24) | (chromosome.Color.R << 16) | (chromosome.Color.G << 8) | chromosome.Color.B; var brush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(argb)); graphics.FillRectangle(brush, chromosome.X, chromosome.Y, chromosome.Radius, chromosome.Radius); } FittestFile = Path.GetTempFileName() + ".ga.png"; bitmap.Save(FittestFile, System.Drawing.Imaging.ImageFormat.Png); Best = ((int)Math.Abs(ranked[0].Fitness)).ToString("n0"); Worst = ((int)Math.Abs(ranked[ranked.Count - 1].Fitness)).ToString("n0"); Total = ranked.Sum(x => Math.Abs((long)x.Fitness)).ToString("n0"); Average = (((long)ranked.Average(x => Math.Abs((long)x.Fitness)))).ToString("n0"); Console.WriteLine($"{Utility.Generation.ToString().PadRight(6)}Best/Worst/Total/Average: {Best.PadLeft(15)}{Worst.PadLeft(15)}{Total.PadLeft(15)}{Average.PadLeft(15)}"); var nextGeneration = new List <Individual>(); while (nextGeneration.Count < Individuals.Count) { var twoRandoms = new[] { indexes[Utility.Random.Next(indexes.Count)], indexes[Utility.Random.Next(indexes.Count)] }; var momIndex = (twoRandoms[0] * twoRandoms[0]) / ranked.Count; var popIndex = (twoRandoms[1] * twoRandoms[1]) / ranked.Count; var mom = ranked[momIndex]; var pop = ranked[popIndex]; var child = Individual.Breed(mom, pop); nextGeneration.Add(child); } return(new Population(nextGeneration.ToArray())); }
public override string ToString() { return("[" + Generations + "] Evolution with " + PopulationSize + " breeding pools. Best: " + Best.ToString()); }
static void Main(string[] args) { CardDataBase DataBase = new CardDataBase(); GameDataBase GameBase = new GameDataBase(); GameState State; Best BestPlays = new Best(); Rate(DataBase); // GameLoop while (true) { State = new GameState(new PlayerStats(Console.ReadLine().Split(' ')), new PlayerStats(Console.ReadLine().Split(' '))); State.opponent.setHand(int.Parse(Console.ReadLine())); Globals.startTime = new Stopwatch(); Globals.startTime.Start(); int CardCount = int.Parse(Console.ReadLine()); // Draft if (State.player.Mana == 0) { GameBase.DraftPicks.Add(new Pick(GameBase, new Card(Console.ReadLine().Split(' ')), new Card(Console.ReadLine().Split(' ')), new Card(Console.ReadLine().Split(' ')))); } // Battle else { for (int i = 0; i < CardCount; i++) { Card card = new Card(Console.ReadLine().Split(' ')); switch (card.Location) { case -1: State.EnemyBoard.Add(new Unit(card, true)); break; case 0: State.MyHand.Add(card); break; case 1: State.MyBoard.Add(new Unit(card, true)); break; default: Console.Error.WriteLine("Data loading error ##########1"); break; } } BestPlays.Clear(); State.EvalState(); SearchAll(State, BestPlays); BestPlays.GetBestState(); } } }
static void SearchAll(GameState State, Best BestPlays) { BestPlays.AddPlay(State); if (Globals.actMillis != Globals.startTime.ElapsedMilliseconds) { Globals.actMillis = (int)Globals.startTime.ElapsedMilliseconds; #if DEBUG if (Globals.actMillis % 10 == 0) { Console.Error.WriteLine("Millis:" + Globals.actMillis); } #endif } if (Globals.actMillis < Globals.maxTurnTime) { List <Action> PotencialActions = new List <Action> (); List <Action> Actions = new List <Action> (); foreach (Unit unit in State.MyBoard) { foreach (Unit enemy in State.EnemyBoard) { PotencialActions.Add(new Action(2, unit.Id, enemy.Id, unit, null, enemy)); } PotencialActions.Add(new Action(2, unit.Id, -1, unit, null, null)); } foreach (Card card in State.MyHand) { if (card.Type == 0) { PotencialActions.Add(new Action(1, card.Id, 0, null, card, null)); } else if (card.Type == 1) { foreach (Unit unit in State.MyBoard) { PotencialActions.Add(new Action(3, card.Id, unit.Id, null, card, unit)); } } else if (card.Type == 2) { foreach (Unit enemy in State.EnemyBoard) { PotencialActions.Add(new Action(3, card.Id, enemy.Id, null, card, enemy)); } } else if (card.Type == 3) { if (card.Defense != 0) { foreach (Unit enemy in State.EnemyBoard) { PotencialActions.Add(new Action(3, card.Id, enemy.Id, null, card, enemy)); } } PotencialActions.Add(new Action(3, card.Id, -1, null, card, null)); } } foreach (Action action in PotencialActions) { ValidAction(action, State); if (action.IsValid) { action.Resolve(); Actions.Add(action); } } #if DEBUG // Console.Error.WriteLine ("Commands: " + State.Commands); // Console.Error.WriteLine ("State.Rating: " + State.Rating); // Console.Error.WriteLine ("ValidA.Count: " + Actions.Count); // Console.Error.WriteLine ("+++++"); #endif foreach (Action action in Actions) { GameState NewState = new GameState(State); PerformAction(action, NewState); NewState.EvalState(); bool value = false; foreach (GameState item in BestPlays.Plays) { if (item.Equals(NewState)) { value = true; } } if (value) { break; } SearchAll(NewState, BestPlays); } } else { Console.Error.WriteLine("Excaping timelimit !!!!!"); } }
private void UpdateStats() { if (Stats.Count > 0) { Last.SolveTime = Stats[Stats.Count - 1].SolveTime; Last.Info = Stats[Stats.Count - 1].Info; if (Best.Ticks == 0 || Best > Last.SolveTime) { Best = ((Best.Subtract(Best)).Add(Last.SolveTime)); } if (Worst < Last.SolveTime) { Worst = ((Worst.Subtract(Worst)).Add(Last.SolveTime)); } Average = ((Average.Subtract(Average)).Add(new TimeSpan(((Average.Ticks * (Stats.Count - 1)) + Last.SolveTime.Ticks) / Stats.Count))); List <Statistic> temp = new List <Statistic>(); temp.AddRange(Stats); temp = temp.OrderBy(s => s.SolveTime).ToList(); Median = ((Median.Subtract(Median)).Add((temp.Count % 2 == 1) ? (temp[(temp.Count - 1) / 2].SolveTime) : (new TimeSpan((((temp[(temp.Count / 2) - 1]).SolveTime.Ticks) + ((temp[temp.Count / 2]).SolveTime.Ticks)) / 2)))); temp.Clear(); Statistic b = null, w = null; long a = 0; if (Stats.Count >= 5) { temp.AddRange(Stats.Where((s) => { return((Stats.IndexOf(s) + 5) >= Stats.Count); })); temp.ForEach((s) => { a += s.SolveTime.Ticks; if (b == null || b > s) { b = s; } if (w == null || w < s) { w = s; } }); AvgLastFive = ((AvgLastFive.Subtract(AvgLastFive)).Add(new TimeSpan(a / 5))); if (AvgBestFive.Ticks == 0 || AvgBestFive > AvgLastFive) { AvgBestFive = ((AvgBestFive.Subtract(AvgBestFive)).Add(AvgLastFive)); } temp.Remove(b); temp.Remove(w); a = 0; temp.ForEach((s) => { a += s.SolveTime.Ticks; }); AvgLastThreeFive = ((AvgLastThreeFive.Subtract(AvgLastThreeFive)).Add(new TimeSpan(a / 3))); if (AvgBestThreeFive.Ticks == 0 || AvgBestThreeFive > AvgLastThreeFive) { AvgBestThreeFive = ((AvgBestThreeFive.Subtract(AvgBestThreeFive)).Add(AvgLastThreeFive)); } temp.Clear(); a = 0; b = null; w = null; if (Stats.Count >= 10) { temp.AddRange(Stats.Where((s) => { return((Stats.IndexOf(s) + 10) >= Stats.Count); })); temp.ForEach((s) => { a += s.SolveTime.Ticks; }); AvgLastTen = ((AvgLastTen.Subtract(AvgLastTen)).Add(new TimeSpan(a / 10))); if (AvgBestTen.Ticks == 0 || AvgBestTen > AvgLastFive) { AvgBestTen = ((AvgBestTen.Subtract(AvgBestTen)).Add(AvgLastTen)); } temp.Clear(); a = 0; if (Stats.Count >= 12) { temp.AddRange(Stats.Where((s) => { return((Stats.IndexOf(s) + 12) >= Stats.Count); })); temp.ForEach((s) => { if (b == null || b > s) { b = s; } if (w == null || w < s) { w = s; } }); temp.Remove(b); temp.Remove(w); temp.ForEach((s) => { a += s.SolveTime.Ticks; }); AvgLastTenTwelve = ((AvgLastTenTwelve.Subtract(AvgLastTenTwelve)).Add(new TimeSpan(a / 10))); if (AvgBestTenTwelve.Ticks == 0 || AvgBestTenTwelve > AvgLastTenTwelve) { AvgBestTenTwelve = ((AvgBestTenTwelve.Subtract(AvgBestTenTwelve)).Add(AvgLastTenTwelve)); } temp.Clear(); a = 0; b = null; w = null; } #region Resets else { ResetTwelves(); } } else { ResetTens(); ResetTwelves(); } } else { ResetFives(); ResetTens(); ResetTwelves(); } #endregion } else { ResetStats(); } #region UpdateProperty() calls UpdateProperty("Last"); UpdateProperty("Best"); UpdateProperty("Worst"); UpdateProperty("Average"); UpdateProperty("Median"); UpdateProperty("AvgLastFive"); UpdateProperty("AvgBestFive"); UpdateProperty("AvgLastTen"); UpdateProperty("AvgBestTen"); UpdateProperty("AvgLastThreeFive"); UpdateProperty("AvgBestThreeFive"); UpdateProperty("AvgLastTenTwelve"); UpdateProperty("AvgBestTenTwelve"); #endregion }
private Best ChooseMove(Side side, int alpha, int beta) { if (side == Side.None) { throw new Exception(); } Best myBest = new Best(); if (side == Side.Computer) { myBest.Score = alpha; } else { myBest.Score = beta; } Best reply; bool isEnd; Side WinnerSide = IsEnd(out isEnd); if (isEnd) { if (WinnerSide == Side.None) { myBest.Score = 0; } else if (WinnerSide == Side.Computer) { myBest.Score = 1; } else { myBest.Score = -1; } return(myBest); } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (_Grid[i, j] == Side.None) { _Grid[i, j] = side; Side TheOtherSide; if (side == Side.Computer) { TheOtherSide = Side.Player; } else { TheOtherSide = Side.Computer; } reply = ChooseMove(TheOtherSide, alpha, beta); _Grid[i, j] = Side.None; if (side == Side.Computer && reply.Score > myBest.Score) { myBest.move.Row = i; myBest.move.Column = j; myBest.Score = reply.Score; alpha = reply.Score; } else if (side == Side.Player && reply.Score < myBest.Score) { myBest.move.Row = i; myBest.move.Column = j; myBest.Score = reply.Score; beta = reply.Score; } if (alpha > beta) { return(myBest); } } } } return(myBest); }
public BuildResult GenBuilds(string prefix = "") { if (Type == BuildType.Lock) { Best = new Monster(Mon, true); return BuildResult.Success; } else if (Type == BuildType.Link) { if (LinkBuild == null) { for (int i = 0; i < 6; i++) runes[i] = new Rune[0]; return BuildResult.Failure; } else { CopyFrom(LinkBuild); } } if (runes.Any(r => r == null)) { BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Null rune")); return BuildResult.BadRune; } if (!BuildSaveStats) BuildGoodRunes = false; if (!BuildGoodRunes) { RuneUsage = new RuneUsage(); BuildUsage = new BuildUsage(); } try { // if to get awakened if (DownloadAwake && !Mon.downloaded) { BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Downloading Awake def")); var mref = MonsterStat.FindMon(Mon); if (mref != null) { // download the current (unawakened monster) var mstat = mref.Download(); BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Reading stats")); // if the retrieved mon is unawakened, get the awakened if (!mstat.Awakened && mstat.AwakenTo != null) { BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Awakening")); Mon = mstat.AwakenTo.Download().GetMon(Mon); } } BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Downloaded")); } // getting awakened also gets level 40, so... // only get lvl 40 stats if the monster isn't 40, wants to download AND isn't already downloaded (first and last are about the same) else if (Mon.level < 40 && DownloadStats && !Mon.downloaded) { BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Downloading 40 def")); var mref = MonsterStat.FindMon(Mon); if (mref != null) Mon = mref.Download().GetMon(Mon); } } catch (Exception e) { BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Failed downloading def: " + e.Message + Environment.NewLine + e.StackTrace)); } if (!getRunningHandle()) throw new InvalidOperationException("The build is locked with another action."); Loads.Clear(); if (!Sort[Attr.Speed].EqualTo(0) && Sort[Attr.Speed] <= 1 // 1 SPD is too good to pass || Mon.Current.Runes.Any(r => r == null) || !Mon.Current.Runes.All(r => runes[r.Slot - 1].Contains(r)) // only IgnoreLess5 if I have my own runes || Sort.NonZeroStats.HasCount(1)) // if there is only 1 sorting, must be too important to drop??? IgnoreLess5 = false; Thread timeThread = null; if (!string.IsNullOrWhiteSpace(BuildStrategy)) { var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(asm => asm.GetTypes().Where(t => typeof(IBuildStrategyDefinition).IsAssignableFrom(t))); var type = types.FirstOrDefault(t => t.AssemblyQualifiedName.Contains(BuildStrategy)); if (type != null) { RunStrategy(); } } tcs.TrySetResult(null); try { Best = null; Stats bstats = null; count = 0; actual = 0; total = runes[0].Length; total *= runes[1].Length; total *= runes[2].Length; total *= runes[3].Length; total *= runes[4].Length; total *= runes[5].Length; complete = total; Mon.ExtraCritRate = extraCritRate; Mon.GetStats(); Mon.DamageFormula?.Invoke(Mon); int?[] slotFakesTemp = new int?[6]; bool[] slotPred = new bool[6]; getPrediction(slotFakesTemp, slotPred); int[] slotFakes = slotFakesTemp.Select(i => i ?? 0).ToArray(); var currentLoad = new Monster(Mon, true); currentLoad.Current.TempLoad = true; currentLoad.Current.Buffs = Buffs; currentLoad.Current.Shrines = Shrines; currentLoad.Current.Leader = Leader; currentLoad.Current.FakeLevel = slotFakes; currentLoad.Current.PredictSubs = slotPred; double currentScore = CalcScore(currentLoad.GetStats(true)); BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "cooking")); if (total == 0) { BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "0 perms")); RuneLog.Info("Zero permuations"); return BuildResult.NoPermutations; } bool hasSort = Sort.IsNonZero; if (BuildTake == 0 && !hasSort) { BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "No sort")); RuneLog.Info("No method of determining best"); return BuildResult.NoSorting; } DateTime begin = DateTime.Now; RuneLog.Debug(count + "/" + total + " " + string.Format("{0:P2}", (count + complete - total) / (double)complete)); // set to running IsRunning = true; #if BUILD_PRECHECK_BUILDS_DEBUG SynchronizedCollection<string> outstrs = new SynchronizedCollection<string>(); #endif BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "...")); List<Monster> tests = new List<Monster>(); timeThread = new Thread(() => { while (IsRunning) { if (RunesOnlyFillEmpty) Thread.Sleep(30 / ((Mon?.Current?.RuneCount ?? 1) + 1)); else Thread.Sleep(400); // every second, give a bit of feedback to those watching RuneLog.Debug(count + "/" + total + " " + string.Format("{0:P2}", (count + complete - total) / (double)complete)); if (tests != null) BuildProgTo?.Invoke(this, ProgToEventArgs.GetEvent(this, (count + complete - total) / (double)complete, tests.Count)); if (BuildTimeout > 0 && DateTime.Now > begin.AddSeconds(BuildTimeout)) { RuneLog.Info("Timeout"); BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "Timeout")); BuildProgTo?.Invoke(this, ProgToEventArgs.GetEvent(this, 1, tests.Count)); IsRunning = false; } } }); timeThread.Start(); double bestScore = double.MinValue; var opts = new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount - 1 }; var mmm = Maximum.NonZeroCached; // Parallel the outer loop // TODO: setup the begin/finish Actions with syncList. void body (Rune r0, ParallelLoopState loopState) { var tempReq = RequiredSets.ToList(); var tempMax = Maximum == null || !Maximum.IsNonZero ? null : new Stats(Maximum, true); int tempCheck = 0; Monster myBest = null; List<Monster> syncList = new List<Monster>(); void syncMyList() { lock (bestLock) { #if DEBUG_SYNC_BUILDS foreach (var s in syncList) { if (s.Current.Runes.All(r => r.Assigned == mon)) { Console.WriteLine("!"); } } #endif tests.AddRange(syncList); } //syncList.ForEach(_ => tests.Add(_)); syncList.Clear(); if (tests.Count > Math.Max(BuildGenerate, 250000)) { #if DEBUG_SYNC_BUILDS var rems = tests.OrderByDescending(b => b.score).Skip(75000).ToList(); foreach (var bbb in rems) { if (bbb.Current.Runes.All(r => r.Assigned == mon)) { Console.WriteLine("!"); } } #endif lock (bestLock) { tests = tests.OrderByDescending(b => b.score).Take(75000).ToList(); } } if (tests.Count > MaxBuilds32) IsRunning = false; } if (!IsRunning_Unsafe) { syncMyList(); loopState.Break(); } // number of builds ruled out since last sync int kill = 0; // number of builds added since last sync int plus = 0; // number of builds skipped int skip = 0; bool isBad; double myBestScore = double.MinValue, curScore, lastBest = double.MinValue; Stats cstats, myStats; Monster test = new Monster(Mon); test.Current.TempLoad = true; test.Current.Buffs = Buffs; test.Current.Shrines = Shrines; test.Current.Leader = Leader; test.Current.FakeLevel = slotFakes; test.Current.PredictSubs = slotPred; test.ApplyRune(r0, 7); RuneSet set4 = r0.SetIs4 ? r0.Set : RuneSet.Null; RuneSet set2 = r0.SetIs4 ? RuneSet.Null : r0.Set; int pop4 = 0; int pop2 = 0; foreach (Rune r1 in runes[1]) { // TODO: refactor to local method if (!IsRunning_Unsafe) // Can't break to a label, don't want to goto break; // TODO: break into multiple implementations that have less branching #if BUILD_PRECHECK_BUILDS if (!AllowBroken && !RunesOnlyFillEmpty) { if (r1.SetIs4) { if (pop2 == 2) pop2 = 7; if (set4 == RuneSet.Null || pop4 >= 2) { set4 = r1.Set; pop4 = 2; } else if (set4 != r1.Set) { #if BUILD_PRECHECK_BUILDS_DEBUG outstrs.Add($"bad4@2 {set4} {set2} | {r0.Set} {r1.Set}"); #endif skip += runes[2].Length * runes[3].Length * runes[4].Length * runes[5].Length; continue; } } else { if (pop4 == 2) pop4 = 7; if (set2 == RuneSet.Null || pop2 >= 2) { set2 = r1.Set; pop2 = 2; } } } #endif test.ApplyRune(r1, 7); foreach (Rune r2 in runes[2]) { if (!IsRunning_Unsafe) break; #if BUILD_PRECHECK_BUILDS if (!AllowBroken && !RunesOnlyFillEmpty) { if (r2.SetIs4) { if (pop2 == 3) pop2 = 7; if (set4 == RuneSet.Null || pop4 >= 3) { set4 = r2.Set; pop4 = 3; } else if (set4 != r2.Set) { #if BUILD_PRECHECK_BUILDS_DEBUG outstrs.Add($"bad4@3 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set}"); #endif skip += runes[3].Length * runes[4].Length * runes[5].Length; continue; } } else { if (pop4 == 3) pop4 = 7; if (set2 == RuneSet.Null || pop2 >= 3) { set2 = r2.Set; pop2 = 3; } else if (set4 != RuneSet.Null && set2 != r2.Set) { #if BUILD_PRECHECK_BUILDS_DEBUG outstrs.Add($"bad2@3 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set}"); #endif skip += runes[3].Length * runes[4].Length * runes[5].Length; continue; } } } #endif test.ApplyRune(r2, 7); foreach (Rune r3 in runes[3]) { if (!IsRunning_Unsafe) break; #if BUILD_PRECHECK_BUILDS if (!AllowBroken && !RunesOnlyFillEmpty) { if (r3.SetIs4) { if (pop2 == 4) pop2 = 7; if (set4 == RuneSet.Null || pop4 >= 4) { set4 = r3.Set; pop4 = 4; } else if (set4 != r3.Set) { #if BUILD_PRECHECK_BUILDS_DEBUG outstrs.Add($"bad4@4 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set}"); #endif skip += runes[4].Length * runes[5].Length; continue; } } else { if (pop4 == 4) pop4 = 7; if (set2 == RuneSet.Null || pop2 >= 4) { set2 = r3.Set; pop2 = 4; } else if (set4 != RuneSet.Null && set2 != r3.Set) { #if BUILD_PRECHECK_BUILDS_DEBUG outstrs.Add($"bad2@4 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set}"); #endif skip += runes[4].Length * runes[5].Length; continue; } } } #endif test.ApplyRune(r3, 7); foreach (Rune r4 in runes[4]) { if (!IsRunning_Unsafe) { break; } #if BUILD_PRECHECK_BUILDS if (!AllowBroken && !RunesOnlyFillEmpty) { if (r4.SetIs4) { if (pop2 == 5) pop2 = 7; if (set4 == RuneSet.Null || pop4 >= 5) { set4 = r4.Set; pop4 = 5; } else if (set4 != r4.Set) { #if BUILD_PRECHECK_BUILDS_DEBUG outstrs.Add($"bad4@5 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set} {r4.Set}"); #endif skip += runes[5].Length; continue; } } else { if (pop4 == 5) pop4 = 7; if (set2 == RuneSet.Null || pop2 >= 5) { set2 = r4.Set; pop2 = 5; } else if (set4 != RuneSet.Null && set2 != r4.Set) { #if BUILD_PRECHECK_BUILDS_DEBUG outstrs.Add($"bad2@5 {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set} {r4.Set}"); #endif skip += runes[5].Length; continue; } } } #endif test.ApplyRune(r4, 7); foreach (Rune r5 in runes[5]) { if (!IsRunning_Unsafe) break; test.ApplyRune(r5, 7); test.Current.CheckSets(); #if BUILD_PRECHECK_BUILDS_DEBUG outstrs.Add($"fine {set4} {set2} | {r0.Set} {r1.Set} {r2.Set} {r3.Set} {r4.Set} {r5.Set}"); #endif isBad = false; cstats = test.GetStats(); // check if build meets minimum isBad |= !RunesOnlyFillEmpty && !AllowBroken && !test.Current.SetsFull; isBad |= tempMax != null && cstats.AnyExceedCached(tempMax); if (!isBad && GrindLoads) { var mahGrinds = grinds.ToList(); for (int rg = 0; rg < 6; rg++) { var lgrinds = test.Runes[rg].FilterGrinds(mahGrinds); foreach (var g in lgrinds) { var tr = test.Runes[rg].Grind(g); } // TODO: } } isBad |= !RunesOnlyFillEmpty && Minimum != null && !cstats.GreaterEqual(Minimum, true); // if no broken sets, check for broken sets // if there are required sets, ensure we have them /*isBad |= (tempReq != null && tempReq.Count > 0 // this Linq adds no overhead compared to GetStats() and ApplyRune() //&& !tempReq.All(s => test.Current.Sets.Count(q => q == s) >= tempReq.Count(q => q == s)) //&& !tempReq.GroupBy(s => s).All(s => test.Current.Sets.Count(q => q == s.Key) >= s.Count()) );*/ // TODO: recheck this code is correct if (tempReq != null && tempReq.Count > 0) { tempCheck = 0; foreach (var r in tempReq) { int i; for (i = 0; i < 3; i++) { if (test.Current.Sets[i] == r && (tempCheck & 1 << i) != 1 << i) { tempCheck |= 1 << i; break; } } if (i >= 3) { isBad |= true; break; } } } if (isBad) { kill++; curScore = 0; } else { // try to reduce CalcScore hits curScore = CalcScore(cstats); isBad |= IgnoreLess5 && curScore < currentScore * 1.05; if (isBad) kill++; } if (!isBad) { // we found an okay build! plus++; test.score = curScore; if (BuildSaveStats) { foreach (Rune r in test.Current.Runes) { if (!BuildGoodRunes) { r.manageStats.AddOrUpdate("LoadFilt", 1, (s, d) => { return d + 1; }); RuneUsage.runesGood.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot); r.manageStats.AddOrUpdate("currentBuildPoints", curScore, (k, v) => Math.Max(v, curScore)); r.manageStats.AddOrUpdate("cbp" + ID, curScore, (k, v) => Math.Max(v, curScore)); } else { r.manageStats.AddOrUpdate("LoadFilt", 0.001, (s, d) => { return d + 0.001; }); RuneUsage.runesOkay.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot); r.manageStats.AddOrUpdate("cbp" + ID, curScore, (k, v) => Math.Max(v, curScore * 0.9)); } } } if (syncList.Count >= 500) { syncMyList(); } // if we are to track all good builds, keep it if (!BuildDumpBads) { syncList.Add(new Monster(test, true)); // locally track my best if (myBest == null || curScore > myBestScore) { myBest = new Monster(test, true); myStats = myBest.GetStats(); myBestScore = CalcScore(myStats); myBest.score = myBestScore; } // if mine is better than what I last saw if (myBestScore > lastBest) { lock (bestLock) { if (Best == null) { Best = new Monster(myBest, true); bstats = Best.GetStats(); bestScore = CalcScore(bstats); Best.score = bestScore; } else { // sync best score lastBest = bestScore; // double check if (myBestScore > lastBest) { Best = new Monster(myBest, true); bestScore = CalcScore(bstats); Best.score = bestScore; bstats = Best.GetStats(); } } } } } // if we only want to track really good builds else { // if there are currently no good builds, keep it // or if this build is better than the best, keep it // locally track my best if (myBest == null || curScore > myBestScore) { myBest = new Monster(test, true); myStats = myBest.GetStats(); myBestScore = CalcScore(myStats); myBest.score = myBestScore; syncList.Add(myBest); } else if (BuildSaveStats) { // keep it for spreadsheeting syncList.Add(new Monster(test, true) { score = curScore }); } } } } // sum up what work we've done Interlocked.Add(ref count, kill); Interlocked.Add(ref count, skip); Interlocked.Add(ref skipped, skip); Interlocked.Add(ref actual, kill); Interlocked.Add(ref BuildUsage.failed, kill); kill = 0; skip = 0; Interlocked.Add(ref count, plus); Interlocked.Add(ref actual, plus); Interlocked.Add(ref BuildUsage.passed, plus); plus = 0; // if we've got enough, stop if (BuildGenerate > 0 && BuildUsage.passed >= BuildGenerate) { IsRunning = false; break; } } } } } // just before dying syncMyList(); } Parallel.ForEach(runes[0], opts, body); BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "finalizing...")); BuildProgTo?.Invoke(this, ProgToEventArgs.GetEvent(this, 0.99, -1)); #if BUILD_PRECHECK_BUILDS_DEBUG System.IO.File.WriteAllLines("_into_the_bridge.txt", outstrs.ToArray()); #endif if (BuildSaveStats) { foreach (var ra in runes) { foreach (var r in ra) { if (!BuildGoodRunes) { r.manageStats.AddOrUpdate("buildScoreTotal", CalcScore(Best), (k, v) => v + CalcScore(Best)); RuneUsage.runesUsed.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot); r.manageStats.AddOrUpdate("LoadGen", total, (s, d) => { return d + total; }); } else { RuneUsage.runesBetter.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot); r.manageStats.AddOrUpdate("LoadGen", total * 0.001, (s, d) => { return d + total * 0.001; }); } } } } // write out completion RuneLog.Debug(IsRunning + " " + count + "/" + total + " " + string.Format("{0:P2}", (count + complete - total) / (double)complete)); BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + " completed")); BuildProgTo?.Invoke(this, ProgToEventArgs.GetEvent(this, 1, tests.Count)); // sort *all* the builds int takeAmount = 1; if (BuildSaveStats) takeAmount = 10; if (BuildTake > 0) takeAmount = BuildTake; if (IgnoreLess5) tests.Add(new Monster(Mon, true)); foreach (var ll in tests.Where(t => t != null).OrderByDescending(r => CalcScore(r.GetStats())).Take(takeAmount)) Loads.Add(ll); BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, "Found a load " + Loads.Count())); if (!BuildGoodRunes) BuildUsage.loads = tests.ToList(); // dump everything to console, if nothing to print to if (BuildPrintTo == null) foreach (var l in Loads) { RuneLog.Debug(l.GetStats().Health + " " + l.GetStats().Attack + " " + l.GetStats().Defense + " " + l.GetStats().Speed + " " + l.GetStats().CritRate + "%" + " " + l.GetStats().CritDamage + "%" + " " + l.GetStats().Resistance + "%" + " " + l.GetStats().Accuracy + "%"); } // sadface if no builds if (!Loads.Any()) { RuneLog.Info("No builds :("); BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "Zero :(")); } else { // remember the good one Best = Loads.First(); Best.Current.TempLoad = false; Best.score = CalcScore(Best.GetStats()); BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "best " + (Best?.score ?? -1))); Best.Current.ActualTests = actual; foreach (var bb in Loads) { foreach (Rune r in bb.Current.Runes) { double val = Best.score; if (BuildGoodRunes) { val *= 0.25; if (bb == Best) RuneUsage.runesSecond.AddOrUpdate(r, (byte)r.Slot, (key, ov) => (byte)r.Slot); } if (bb != Best) val *= 0.1; else r.manageStats.AddOrUpdate("In", BuildGoodRunes ? 2 : 1, (s, e) => BuildGoodRunes ? 2 : 1); r.manageStats.AddOrUpdate("buildScoreIn", val, (k, v) => v + val); } } for (int i = 0; i < 6; i++) { if (!BuildGoodRunes && Mon.Current.Runes[i] != null && Mon.Current.Runes[i].Id != Best.Current.Runes[i].Id) Mon.Current.Runes[i].Swapped = true; } foreach (var ra in runes) { foreach (var r in ra) { var cbp = r.manageStats.GetOrAdd("currentBuildPoints", 0); if (cbp / Best.score < 1) r.manageStats.AddOrUpdate("bestBuildPercent", cbp / Best.score, (k, v) => Math.Max(v, cbp / Best.score)); } } } tests.Clear(); tests = null; BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + "Test cleared")); return BuildResult.Success; } catch (Exception e) { RuneLog.Error("Error " + e); BuildPrintTo?.Invoke(this, PrintToEventArgs.GetEvent(this, prefix + e.ToString())); return BuildResult.Failure; } finally { tcs = new TaskCompletionSource<IBuildRunner>(); IsRunning = false; if (timeThread != null) timeThread.Join(); } }
// Update is called once per frame void Update() { frame++; //Debug.Log (1.0f/Time.deltaTime); if (BLockControl.lineTag) { for (float i = -7.5f; i <= 11.5f; i++) { bool tag = true; for (float j = -4.5f; j <= 4.5f; j++) { if (!Physics.Raycast(new Vector3(j, i, 5.0f), new Vector3(0.0f, 0.0f, -1.0f), 20.0f, 1 << LayerMask.NameToLayer("Block"))) { tag = false; } } if (tag) { RaycastHit rayHit; for (float j = -4.5f; j <= 4.5f; j++) { if (Physics.Raycast(new Vector3(j, i, 5.0f), new Vector3(0.0f, 0.0f, -1.0f), out rayHit, 20.0f, 1 << LayerMask.NameToLayer("Block"))) { foreach (Transform child in rayHit.transform) { child.gameObject.AddComponent <Rigidbody> (); child.GetComponent <Rigidbody> ().collisionDetectionMode = CollisionDetectionMode.Continuous; } if (rayHit.transform.parent) //需要判断父物体是否存在,不判断可能导致重复操作。 { Transform parent = rayHit.transform.parent; parent.DetachChildren(); Destroy(parent.gameObject); } Destroy(rayHit.transform.gameObject); } } scoreNum++; scoreText.text = scoreNum.ToString("000"); } } } RaycastHit hit; if (!BLockControl.endTag && Physics.Raycast(new Vector3(-6.0f, 14.0f, 1.0f), new Vector3(1.0f, 0.0f, 0.0f), out hit, 30.0f, 1 << LayerMask.NameToLayer("Block")) && !hit.transform.GetComponent <BLockControl>()) { Tetris.isTouched = false; BLockControl.endTag = true; Debug.Log("Game Over"); } if (isTouched && !BLockControl.endTag) { int ran = (int)Random.Range(0.0f, 7.0f); Vector3 pos = new Vector3(-1.0f, 14f, 1.0f); Instantiate(BlockPfb[ran], pos, BlockPfb[ran].transform.rotation); isTouched = false; } if (BLockControl.endTag) { if (scoreNum > int.Parse(tmp)) { //create record StreamWriter sw; FileInfo t = new FileInfo(path + "game.dat"); if (!t.Exists) //if file exits,read and display; { sw = t.CreateText(); tmpDES = Best.EncryptDES(tmp, "asdasfsfa"); sw.WriteLine(tmpDES); sw.Close(); sw.Dispose(); } else { t.Delete(); sw = t.CreateText(); tmpDES = Best.EncryptDES(scoreNum.ToString("000"), "asdasfsfa"); sw.WriteLine(tmpDES); sw.Close(); sw.Dispose(); } newRecord.SetActive(true); newRecord.transform.FindChild("num").GetComponent <Text> ().text = scoreNum.ToString(); } else { end.SetActive(true); } } }
static void updatedata(RootObject root, string data) { //Console.WriteLine("MESSAGE RECEIVED {0}", data); var tempobj = JObject.Parse(data); string res = ApplyPatch(tempobj["A"].ToString()); var obj = JObject.Parse(res); var name = obj.Properties().Select(p => p.Name).FirstOrDefault(); switch (name) { case "opt": Opt opt = root.SPFeed.opt; if (obj["opt"]["data"]["DR"] != null) { IList <JToken> DR = JObject.Parse(obj["opt"]["data"]["DR"].ToString()); var DRindex = Convert.ToInt32(((JProperty)DR[0]).Name); var O = ((JProperty)DR[0]).Value; JToken Otemp = JToken.Parse(O.ToString()); if (Otemp["O"] != null) { var Oindex = Otemp["O"]; foreach (JToken item in Oindex) { int index = Convert.ToInt32(((JProperty)item).Name); string value = ((JProperty)item).Value.ToString(); //Console.WriteLine("Index {0} Value {1}", index, value); root.SPFeed.opt.data.DR[DRindex].O[index] = value; } } } ; RenderFreeData(root); break; case "best": Best best = root.SPFeed.best; if (obj["best"]["data"]["DR"] != null) { IList <JToken> DR = JObject.Parse(obj["best"]["data"]["DR"].ToString()); var DRindex = Convert.ToInt32(((JProperty)DR[0]).Name); var B = ((JProperty)DR[0]).Value; JToken Btemp = JToken.Parse(B.ToString()); if (Btemp["B"] != null) { var Bindex = Btemp["B"]; foreach (JToken item in Bindex) { int index = Convert.ToInt32(((JProperty)item).Name); string value = ((JProperty)item).Value.ToString(); //Console.WriteLine("Index {0} Value {1}", index, value); root.SPFeed.best.data.DR[DRindex].B[index] = value; } } } ; RenderFreeData(root); break; case "sq": break; case "Weather": break; } ; }