// TODO: honour the timeoutInMilliseconds setting public bool TrySetActions(int playerIndex, TankAction tankAction1, TankAction tankAction2, ICommunicatorCallback callback, int timeoutInMilliseconds) { ChallengeClient client = new ChallengeClient(EndPointConfigurationName, Url); client.Open(); try { try { client.setActions(tankAction1.Convert(), tankAction2.Convert()); return(true); } catch (FaultException <EndOfGameException> endOfGameFault) { LogDebugError(endOfGameFault, endOfGameFault.Message); callback.UpdateGameOutcomeToLoseDueToError(playerIndex, endOfGameFault.Message); return(false); } catch (FaultException <NoBlameException> noBlameFault) { LogDebugError(noBlameFault, noBlameFault.Message); callback.UpdateGameOutcomeDueToNoBlameCrash(noBlameFault.Message); #if THROW_HARNESS_ERRORS throw; #else return(false); #endif } catch (EndpointNotFoundException endpointException) { LogDebugError(endpointException, endpointException.Message); callback.UpdateGameOutcomeDueToServerUnavailable(endpointException.Message); #if THROW_HARNESS_ERRORS throw; #else return(false); #endif } catch (CommunicationException commsException) { LogDebugError(commsException, commsException.Message); callback.UpdateGameOutcomeDueToServerUnavailable(commsException.Message); #if THROW_HARNESS_ERRORS throw; #else return(false); #endif } } finally { client.Close(); } }
public int LoginAndGetYourPlayerIndex(ICommunicatorCallback callback) { ChallengeClient client = new ChallengeClient(EndPointConfigurationName, Url); client.Open(); try { callback.DoBeforeLoggingIn(); try { // Login: state?[][] states = client.login(); // Set up game board and end game sequence: CellType[,] initialCellTypes = ConvertGameBoard(ref states); callback.InitializeGameBoard(initialCellTypes); int tickAtWhichGameEndSequenceBegins = 1000; // The new wsdl breaks due to an svcutil bug, so revert and use a high value callback.InitializeEndGameSequence(tickAtWhichGameEndSequenceBegins); // Get status for the first time: DateTime localTimeBeforeGetStatusCall = DateTime.Now; game wsGame = client.getStatus(); DateTime localTimeAfterGetStatusCall = DateTime.Now; callback.DoBeforeInitializingPlayersAndUnits( wsGame.currentTick, wsGame.nextTickTime, TimeSpan.FromMilliseconds(wsGame.millisecondsToNextTick), localTimeBeforeGetStatusCall, localTimeAfterGetStatusCall); try { int yourPlayerIndex = InitializePlayersAndUnitsAndGetYourPlayerIndex(wsGame, callback); return(yourPlayerIndex); } finally { callback.DoAfterInitializingPlayersAndUnits(); } } finally { callback.DoBeforeReturningFromLogin(); } } finally { client.Close(); } }
static void Main(string[] args) { //* const string teamSecret = "wHUYV6IVfJh7akUFzCmSqG9Fk/z/GwX"; // Вставь сюда ключ команды var challengeClient = new ChallengeClient(teamSecret); const string challengeId = "projects-course"; var challenge = challengeClient.GetChallengeAsync(challengeId).Result; var sender = new Sender(); Console.WriteLine("Insert number of tests"); var count = int.Parse(Console.ReadLine()); sender.SendSomeAnswers(challengeClient, challenge, count); //*/ //Console.WriteLine(InverseMatrix.GetAnswer(@"-25 & 16 & -20 \\ 19 & 24 & 5 \\ 7 & 8 & 0")); }
static void Main(string[] args) { //* const string teamSecret = "R/72jERH1xsugaFANPVcHmgIiRoMyT4O"; // Вставь сюда ключ команды var challengeClient = new ChallengeClient(teamSecret); const string challengeId = "projects-course"; var challenge = challengeClient.GetChallengeAsync(challengeId).Result; var sender = new Sender(); //sender.ShowResults(challengeClient); //Console.WriteLine("Insert type of your task"); //string type = Console.ReadLine(); Console.WriteLine("Insert number of tests"); var count = int.Parse(Console.ReadLine()); sender.SendSomeAnswers(challengeClient, challenge, count); //*/ //Console.WriteLine(Caesar.GetAns("first longest word=underground|marherxhyezmgvbh0ehihve0hhzhnezassuvbeavegv0hnbnogv0ema1he8xhnhexgbhesramacrurhseav0esramab7urhsebnh8")); }
static async Task Main(string[] args) { const string teamSecret = "upvfPcVHxvgW4d7lyZXrXKqobhzjkoip"; // Вставь сюда ключ команды if (string.IsNullOrEmpty(teamSecret)) { Console.WriteLine("Задай секрет своей команды, чтобы можно было делать запросы от ее имени"); return; } var challengeClient = new ChallengeClient(teamSecret); const string challengeId = "projects-course"; Console.WriteLine($"Нажми ВВОД, чтобы получить информацию о соревновании {challengeId}"); Console.ReadLine(); Console.WriteLine("Ожидание..."); var challenge = await challengeClient.GetChallengeAsync(challengeId); Console.WriteLine(challenge.Description); Console.WriteLine(); Console.WriteLine("----------------"); Console.WriteLine(); //ИЗМЕНИТЬ ТИП ЗАДАНИЯ const string taskType = ""; var utcNow = DateTime.UtcNow; string currentRound = null; foreach (var round in challenge.Rounds) { if (round.StartTimestamp < utcNow && utcNow < round.EndTimestamp) { currentRound = round.Id; } } //ИЗМЕНИТЬ КОЛ-ВО ИТЕРАЦИЙ for (var g = 0; g < 1; g++) { Console.WriteLine( $"Нажми ВВОД, чтобы получить первые 50 взятых командой задач типа {taskType} в раунде {currentRound}"); Console.ReadLine(); Console.WriteLine("Ожидание..."); var firstTasks = await challengeClient.GetTasksAsync(currentRound, taskType, TaskStatus.Pending, 0, 50); for (int i = 0; i < firstTasks.Count; i++) { var task = firstTasks[i]; Console.WriteLine($" Задание {i + 1}, статус {task.Status}"); Console.WriteLine($" Формулировка: {task.UserHint}"); Console.WriteLine($" {task.Question}"); Console.WriteLine(); } Console.WriteLine("----------------"); Console.WriteLine(); Console.WriteLine($"Нажми ВВОД, чтобы получить задачу типа {taskType} в раунде {currentRound}"); Console.ReadLine(); Console.WriteLine("Ожидание..."); var newTask = await challengeClient.AskNewTaskAsync(currentRound, taskType); Console.WriteLine($" Новое задание, статус {newTask.Status}"); Console.WriteLine($" Формулировка: {newTask.UserHint}"); Console.WriteLine($" {newTask.Question}"); Console.WriteLine(); Console.WriteLine("----------------"); Console.WriteLine(); //const string answer = "42"; var str = newTask.Question; var tipe = newTask.TypeId; var answer = ""; //СЮДА КОД С ЗАДАНИЯМИ Console.WriteLine( $"Нажми ВВОД, чтобы ответить на полученную задачу самым правильным ответом: {answer}"); //Console.ReadLine(); Console.WriteLine("Ожидание..."); var updatedTask = await challengeClient.CheckTaskAnswerAsync(newTask.Id, answer); Console.WriteLine($" Новое задание, статус {updatedTask.Status}"); Console.WriteLine($" Формулировка: {updatedTask.UserHint}"); Console.WriteLine($" {updatedTask.Question}"); Console.WriteLine($" Ответ команды: {updatedTask.TeamAnswer}"); Console.WriteLine(); if (updatedTask.Status == TaskStatus.Success) { Console.WriteLine($"Ура! Ответ угадан!"); } else if (updatedTask.Status == TaskStatus.Failed) { Console.WriteLine($"Похоже ответ не подошел и задачу больше сдать нельзя..."); } Console.WriteLine(); Console.WriteLine("----------------"); Console.WriteLine(); Console.WriteLine($"Нажми ВВОД, чтобы завершить работу программы"); Console.ReadLine(); } }
public bool TryGetNewGameState(int playerIndex, int currentTickOnClient, ICommunicatorCallback callback) { ChallengeClient client = new ChallengeClient(EndPointConfigurationName, Url); client.Open(); try { try { callback.DoBeforeCheckingForANewState(); try { DateTime localTimeBeforeGetStatusCall = DateTime.Now; game wsGame = client.getStatus(); DateTime localTimeAfterGetStatusCall = DateTime.Now; int currentTick = wsGame.currentTick; if (currentTick == currentTickOnClient) { #if DEBUG // We don't want to lose important events. // Check that the harness only sends them when the current tick changes: if (wsGame.events != null) { if (wsGame.events.blockEvents != null && wsGame.events.blockEvents.Length > 0) { LogDebugMessage("RACE CONDITION! block events in the middle of a turn"); #if THROW_HARNESS_ERRORS throw new InvalidOperationException( "There are block events on a game object that is not the new game object"); #endif } if (wsGame.events.unitEvents != null && wsGame.events.unitEvents.Length > 0) { LogDebugMessage("RACE CONDITION! unit events in the middle of a turn"); #if THROW_HARNESS_ERRORS throw new InvalidOperationException( "There are unit events on a game object that is not the new game object"); #endif } } #endif return(false); } callback.DoBeforeUpdatingTheState(wsGame.currentTick, wsGame.nextTickTime, TimeSpan.FromMilliseconds(wsGame.millisecondsToNextTick), localTimeBeforeGetStatusCall, localTimeAfterGetStatusCall); bool stateUpdateCompletedSuccessfully = false; try { // Remove any walls that have been shot: List <Point> wallsRemovedAfterPreviousTick = new List <Point>(); List <Point> outOfBoundsBlocksAfterPreviousTick = new List <Point>(); events evts = wsGame.events; if (evts != null && evts.blockEvents != null) { foreach (blockEvent blockEv in evts.blockEvents) { if (blockEv.newStateSpecified) { switch (blockEv.newState) { case state.EMPTY: case state.NONE: Point wallPoint = blockEv.point.Convert(); wallsRemovedAfterPreviousTick.Add(wallPoint); break; #if DEBUG case state.OUT_OF_BOUNDS: outOfBoundsBlocksAfterPreviousTick.Add(blockEv.point.Convert()); break; case state.FULL: throw new InvalidOperationException( String.Format( "A 'FULL' block event was found at ({0}, {1}) contrary to expectation", blockEv.point.x, blockEv.point.y) ); break; #endif } } } } callback.UpdateWalls(wallsRemovedAfterPreviousTick, outOfBoundsBlocksAfterPreviousTick); // Update states of tanks and bullets which were destroyed: if (evts != null && evts.unitEvents != null) { foreach (unitEvent unitEv in evts.unitEvents) { unit u = unitEv.unit; if (u != null) { Point newPos = new Point((short)u.x, (short)u.y); TankAction tankAction = u.actionSpecified ? u.action.Convert() : TankAction.NONE; callback.UpdateTankState(u.id, tankAction, newPos, u.direction.Convert(), isActive: false); } bullet blt = unitEv.bullet; if (blt != null) { Point bulletPos = new Point((short)blt.x, (short)blt.y); callback.UpdateBulletState(blt.id, bulletPos, blt.direction.Convert(), isActive: false); } } } foreach (player plyr in wsGame.players) { if (plyr.units != null) { foreach (unit u in plyr.units) { if (u != null) { Point newPos = new Point((short)u.x, (short)u.y); TankAction tankAction = u.actionSpecified ? u.action.Convert() : TankAction.NONE; callback.UpdateTankState(u.id, tankAction, newPos, u.direction.Convert(), isActive: true); } } } if (plyr.bullets != null) { foreach (bullet blt in plyr.bullets) { Point bulletPos = new Point((short)blt.x, (short)blt.y); callback.UpdateBulletState(blt.id, bulletPos, blt.direction.Convert(), isActive: true); } } } stateUpdateCompletedSuccessfully = true; } finally { callback.DoAfterUpdatingTheState(stateUpdateCompletedSuccessfully); } return(true); } finally { callback.DoBeforeReturningFromCheckingForANewState(); } } catch (FaultException <EndOfGameException> endOfGameFault) { LogDebugError(endOfGameFault, endOfGameFault.Message); callback.UpdateGameOutcomeToLoseDueToError(playerIndex, endOfGameFault.Message); #if THROW_HARNESS_ERRORS throw; #else return(false); #endif } catch (FaultException <NoBlameException> noBlameFault) { LogDebugError(noBlameFault, noBlameFault.Message); callback.UpdateGameOutcomeDueToNoBlameCrash(noBlameFault.Message); #if THROW_HARNESS_ERRORS throw; #else return(false); #endif } catch (EndpointNotFoundException endpointException) { LogDebugError(endpointException, endpointException.Message); callback.UpdateGameOutcomeDueToServerUnavailable(endpointException.Message); #if THROW_HARNESS_ERRORS throw; #else return(false); #endif } catch (CommunicationException commsException) { LogDebugError(commsException, commsException.Message); callback.UpdateGameOutcomeDueToServerUnavailable(commsException.Message); #if THROW_HARNESS_ERRORS throw; #else return(false); #endif } } finally { client.Close(); } }
static void Main(string[] args) { const string teamSecret = ""; // Вставь сюда ключ команды if (string.IsNullOrEmpty(teamSecret)) { Console.WriteLine("Задай секрет своей команды, чтобы можно было делать запросы от ее имени"); return; } var challengeClient = new ChallengeClient(teamSecret); const string challengeId = "projects-course"; Console.WriteLine($"Нажми ВВОД, чтобы получить информацию о челлендже {challengeId}"); Console.ReadLine(); var challenge = challengeClient.GetChallengeAsync(challengeId).Result; Console.WriteLine(challenge.Description); Console.WriteLine(); Console.WriteLine("----------------"); Console.WriteLine(); Console.WriteLine($"Нажми ВВОД, чтобы получить список взятых командой задач"); Console.ReadLine(); var allTasks = challengeClient.GetAllTasksAsync().Result; for (int i = 0; i < allTasks.Count; i++) { var task = allTasks[i]; Console.WriteLine($" Задание {i + 1}, статус {task.Status}"); Console.WriteLine($" Формулировка: {task.UserHint}"); Console.WriteLine($" {task.Question}"); Console.WriteLine(); } Console.WriteLine("----------------"); Console.WriteLine(); const string type = "starter"; string round = challenge.Rounds[challenge.Rounds.Count - 1].Id; Console.WriteLine($"Нажми ВВОД, чтобы получить задачу типа {type}"); Console.ReadLine(); var newTask = challengeClient.AskNewTaskAsync(round, type).Result; Console.WriteLine($" Новое задание, статус {newTask.Status}"); Console.WriteLine($" Формулировка: {newTask.UserHint}"); Console.WriteLine($" {newTask.Question}"); Console.WriteLine(); Console.WriteLine("----------------"); Console.WriteLine(); const string answer = "42"; Console.WriteLine($"Нажми ВВОД, чтобы ответить на полученную задачу самым правильным ответом: {answer}"); Console.ReadLine(); var updatedTask = challengeClient.CheckTaskAnswerAsync(newTask.Id, answer).Result; Console.WriteLine($" Новое задание, статус {updatedTask.Status}"); Console.WriteLine($" Формулировка: {updatedTask.UserHint}"); Console.WriteLine($" {updatedTask.Question}"); Console.WriteLine($" Ответ команды: {updatedTask.TeamAnswer}"); Console.WriteLine(); if (updatedTask.Status == TaskStatus.Success) { Console.WriteLine($"Ура! Ответ угадан!"); } else if (updatedTask.Status == TaskStatus.Failed) { Console.WriteLine($"Похоже ответ не подошел и задачу больше сдать нельзя..."); } Console.WriteLine(); Console.WriteLine("----------------"); Console.WriteLine(); Console.WriteLine($"Нажми ВВОД, чтобы завершить работу программы"); Console.ReadLine(); }
static void Main(string[] args) { /* * * %28 - ( * %29 - ) * %2B - + * %2F - : * * */ //var text = "first longest word=something|80dbnjn hdijn pfjn00ijtdfn hdkjn tnbsj6 tnbsj088jb30urspjpyprf0dpjkpnsjs3trp8j6 pdjs0zpn hdkjvhipjn hs"; //Console.WriteLine(Visioner.GetCypher(text)); /* * var expresion = "2/2"; * var url = "http://api.wolframalpha.com/v2/query?appid=PYVXLP-Y5W998K993&input=" + expresion; * WebClient webClient = new WebClient(); * string result = webClient.DownloadString(url); * Console.WriteLine(result); */ //var dict = new Dictionary<string, string>(); //var json = @"{""padlocked"":-1,""myotonias"":-9,""stanchly"":-8,""millwheel"":2,""denizenation"":9,""pointswoman"":{""linework"":-3,""sizzling"":-5,""combating"":3,""underlout"":5},""youths"":{""ginglymodian"":-3,""embossage"":5,""subperiosteal"":6,""seastroke"":-9,""indurative"":-5,""composition"":-9}}"; /*var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); * var summ = 0.0; * foreach(var e in obj) * { * summ += double.Parse(e.Value); * } * Console.WriteLine((int)summ); */ //var info = JsonConvert.DeserializeObject<Info>(json); //var text = File.ReadAllText("text.txt"); //Console.WriteLine(Determinant.GetDeterminant(@"9 & 0 & -8 & -7 & 8 & 7 & 7 & -8 \\ 4 & 4 & 3 & 9 & 9 & 8 & -1 & -3 \\ -11 & -1 & 9 & 4 & -5 & -3 & -10 & -11 \\ -7 & 0 & -11 & -6 & 1 & -4 & -1 & 10 \\ 2 & -10 & 2 & -10 & 1 & 0 & -7 & -8 \\ -10 & 6 & 1 & 10 & -8 & 8 & 5 & 7 \\ 3 & -8 & 5 & -10 & -9 & 9 & -11 & 1 \\ -2 & -9 & -11 & -3 & 7 & 1 & 1 & -4")); /* * var expression = "(5*6i)-(3*8+4i+8)-(6i+4-5-6i)"; * string url = "https://www.wolframalpha.com/input/?i=2+%2B+3"; * var web = new HtmlAgilityPack.HtmlWeb(); * HtmlDocument doc = web.Load(url); * * /*var pageHtml = LoadPage("https://www.wolframalpha.com/input/?i=" + expression); * var document = new HtmlDocument(); * document.LoadHtml(pageHtml); */ /* * */ const string teamSecret = "jSVy9hRtt7bpflchqLGSc3l0iEgaRtp"; var challengeClient = new ChallengeClient(teamSecret); const string challengeId = "projects-course"; Console.WriteLine($"Нажми ВВОД, чтобы получить информацию о челлендже {challengeId}"); Console.ReadLine(); var challenge = challengeClient.GetChallengeAsync(challengeId).Result; Console.WriteLine(challenge.Description); Console.WriteLine(); Console.WriteLine("----------------"); Console.WriteLine(); Console.WriteLine($"Нажми ВВОД, чтобы получить список взятых командой задач"); Console.ReadLine(); /* * var allTasks = challengeClient.GetAllTasksAsync().Result; * * for (int i = 0; i < allTasks.Count; i++) * { * var task = allTasks[i]; * Console.WriteLine($" Задание {i + 1}, статус {task.Status}"); * Console.WriteLine($" {task.Question}"); * Console.WriteLine($" {task.TeamAnswer}"); * } */ Console.WriteLine("----------------"); Console.WriteLine(); while (true) { Console.WriteLine(" "); string round = challenge.Rounds[2].Id; //Console.ReadLine(); var newTask = challengeClient.AskNewTaskAsync(round).Result; Console.WriteLine($" Новое задание, статус {newTask.Status}"); Console.WriteLine($" Формулировка: {newTask.UserHint}"); Console.WriteLine($" {newTask.Question}"); Console.WriteLine(); Console.WriteLine("----------------"); var answer = ""; if (newTask.TypeId == "math") { if (newTask.Question.Contains("i") && (newTask.Question.Contains("/") || newTask.Question.Contains("%"))) { continue; } if (newTask.Question.Contains("i")) { var expresion = newTask.Question.Replace("+", "%2B"); var url = "http://api.wolframalpha.com/v2/query?appid=PYVXLP-Y5W998K993&input=" + expresion + "&includepodid=Result&format=plaintext"; WebClient webClient = new WebClient(); string result = webClient.DownloadString(url); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(result); XmlElement xRoot = xDoc.DocumentElement; XmlNodeList elements = xDoc.SelectNodes("//pod"); foreach (XmlElement element in elements) { answer = element.InnerText.Replace(" ", ""); } } else { answer = SolveExpression.GetResult(newTask.Question); } } if (newTask.TypeId == "determinant") { answer = Determinant.GetDeterminant(newTask.Question); } if (newTask.TypeId == "polynomial-root") { answer = Polynome.GetPolynomialRoot(newTask.Question); } if (newTask.TypeId == "cypher") { continue; } if (newTask.TypeId == "shape") { answer = "rectangle"; } if (newTask.TypeId == "string-number") { continue; } if (newTask.TypeId == "inverse-matrix") { answer = Determinant.GetInversed(newTask.Question); } if (newTask.TypeId == "json") { answer = JsonParser.SosiBibu(newTask.Question); } Console.WriteLine(answer); // Ответ var updatedTask = challengeClient.CheckTaskAnswerAsync(newTask.Id, answer).Result; Console.WriteLine($" Новое задание, статус {updatedTask.Status}"); Console.WriteLine($" Формулировка: {updatedTask.UserHint}"); Console.WriteLine($" {updatedTask.Question}"); Console.WriteLine(); if (updatedTask.Status == TaskStatus.Success) { Console.WriteLine($"Ура! Ответ угадан!"); } else if (updatedTask.Status == TaskStatus.Failed) { Console.WriteLine($"Похоже ответ не подошел и задачу больше сдать нельзя..."); } Console.WriteLine("-------------------------"); } /* * string answer = newTask.Question + ""; * * Console.WriteLine($"Нажми ВВОД, чтобы ответить на полученную задачу самым правильным ответом: {answer}"); * Console.ReadLine(); * * var updatedTask = challengeClient.CheckTaskAnswerAsync(newTask.Id, answer).Result; * Console.WriteLine($" Новое задание, статус {updatedTask.Status}"); * Console.WriteLine($" Формулировка: {updatedTask.UserHint}"); * Console.WriteLine($" {updatedTask.Question}"); * updatedTask.TeamAnswer = Parser(updatedTask.Question) + ""; * Console.WriteLine($" Ответ команды: {Parser(updatedTask.Question)}"); * Console.WriteLine(); * if (updatedTask.Status == TaskStatus.Success) * Console.WriteLine($"Ура! Ответ угадан!"); * else if (updatedTask.Status == TaskStatus.Failed) * Console.WriteLine($"Похоже ответ не подошел и задачу больше сдать нельзя..."); * Console.WriteLine(); * Console.ReadLine(); */ Console.WriteLine("----------------"); Console.WriteLine(); Console.WriteLine($"Нажми ВВОД, чтобы завершить работу программы"); Console.ReadLine(); }