/// <summary> /// エラー表示用です。 /// </summary> /// <param name="value">表示する内容</param> public static void WriteError(string value) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(value); Console.ForegroundColor = ConsoleColor.Gray; TextIO.WriteStrings(Define.LogFilePath, value); }
public VisitingTeamPlay(TextIO io, IRandom random, Clock clock, Defense defense) : base(io, random, clock) { _io = io; _random = random; _defense = defense; }
public static void AppendProxyToTextFile(FileLink fileLink, Proxy proxy) { EmptyParamContract.Validate(fileLink); EmptyParamContract.Validate(proxy); TextIO.WriteAsync(fileLink.Path, proxy.ToString(), true); }
internal static Position ReadGuess(this TextIO io, string prompt) { io.WriteLine(); io.WriteLine(); var(x, y) = io.Read2Numbers(prompt); return(new Position(x, y)); }
/** Search a position and return the best move and score. Used for test suite processing. */ public TwoReturnValues <Move, string> searchPosition(Position pos, int maxTimeMillis) { // Create a search object ulong[] posHashList = new ulong[200]; tt.nextGeneration(); Search sc = new Search(pos, posHashList, 0, tt); // Determine all legal moves MoveGen.MoveList moves = new MoveGen().pseudoLegalMoves(pos); MoveGen.RemoveIllegal(pos, moves); sc.scoreMoveList(moves, 0); // Find best move using iterative deepening sc.timeLimit(maxTimeMillis, maxTimeMillis); Move bestM = sc.iterativeDeepening(moves, -1, -1, false); // Extract PV string PV = TextIO.moveTostring(pos, bestM, false) + " "; UndoInfo ui = new UndoInfo(); pos.makeMove(bestM, ui); PV += tt.extractPV(pos); pos.unMakeMove(bestM, ui); // tt.printStats(); // Return best move and PV return(new TwoReturnValues <Move, string>(bestM, PV)); }
private void Sample() { CuckComp = new ComputerPlayer(); CuckHumn = new HumanPlayer(); CuckBK = new Book(false); CuckGM = new Game(CuckHumn, CuckComp); Position pos = CuckGM.getPos(); // e4(102) d4(31) ... string CurrentBookMoves = CuckBK.getAllBookMoves(pos); // Nb1-a3;Nb1-c3;...;a2-a3;a2-a4;... string CurrentValidMoves = TextIO.AllMovesTostring(pos, true); // RNB...w KQkq... string CurrentPositionFEN = TextIO.toFEN(pos); // Display board to console TextIO.DispBoard(pos); // Swap & move CuckGM.whitePlayer = CuckComp; CuckGM.blackPlayer = CuckHumn; //CuckComp.bookEnabled = false; CuckComp.maxTimeMillis = 1 * 100; CuckComp.maxTimeMillis = 6 * 100; //CuckComp.maxDepth = 6; // Ng1-f3 string CommandFromComp = CuckComp.getCommand(new Position(pos), CuckGM.haveDrawOffer(), CuckGM.getHistory()); }
/** Check if a draw claim is allowed, possibly after playing "move". * @param move The move that may have to be made before claiming draw. * @return The draw string that claims the draw, or empty string if draw claim not valid. */ private string canClaimDraw(Position pos, ulong[] posHashList, int posHashListSize, Move move) { string drawStr = ""; if (Search.canClaimDraw50(pos)) { drawStr = "draw 50"; } else if (Search.canClaimDrawRep(pos, posHashList, posHashListSize, posHashListSize)) { drawStr = "draw rep"; } else { string strMove = TextIO.moveTostring(pos, move, false); posHashList[posHashListSize++] = pos.zobristHash(); UndoInfo ui = new UndoInfo(); pos.makeMove(move, ui); if (Search.canClaimDraw50(pos)) { drawStr = "draw 50 " + strMove; } else if (Search.canClaimDrawRep(pos, posHashList, posHashListSize, posHashListSize)) { drawStr = "draw rep " + strMove; } pos.unMakeMove(move, ui); } return(drawStr); }
/// <summary> /// ログファイルを新規作成します。 /// </summary> static void CreateLogFile() { Define.LogFilePath = Define.LogFilePath1 + DateTime.Now.Ticks + Define.LogFilePath2; TextIO.WriteStrings(Define.LogFilePath, "MCAS_Log_" + Define.MCAS_Version); // TextIO.WriteStrings(Define.LogFilePath, ""); }
private void Awake() { TxtIO = this; TerrainTable = new double[15, 29]; Load("E:\\Users\\Jakob\\UnityProjects\\AdventurerKings\\TerrainDemands.txt"); }
/** * Update the game state according to move/command string from a player. * @param str The move or command to process. * @return True if str was understood, false otherwise. */ public bool processstring(string str) { if (handleCommand(str)) { return(true); } if (getGameState() != GameState.ALIVE) { return(false); } Move m = TextIO.stringToMove(pos, str); if (m == null) { return(false); } UndoInfo ui = new UndoInfo(); pos.makeMove(m, ui); TextIO.fixupEPSquare(pos); while (currentMove < moveList.Count) { moveList.RemoveAt(currentMove); uiInfoList.RemoveAt(currentMove); drawOfferList.RemoveAt(currentMove); } moveList.Add(m); uiInfoList.Add(ui); drawOfferList.Add(pendingDrawOffer); pendingDrawOffer = false; currentMove++; return(true); }
public List <string> getPosHistory() { List <string> ret = new List <string>(); Position pos2 = new Position(pos /*this.pos*/); for (int i = currentMove; i > 0; i--) { pos2.unMakeMove(moveList[i - 1], uiInfoList[i - 1]); } ret.Add(TextIO.toFEN(pos2)); // Store initial FEN string moves = ""; for (int i = 0; i < moveList.Count; i++) { Move move = moveList[i]; string strMove = TextIO.moveTostring(pos2, move, false); moves += " " + strMove; UndoInfo ui = new UndoInfo(); pos2.makeMove(move, ui); } ret.Add(moves); // Store move list string int numUndo = moveList.Count - currentMove; ret.Add(((int)numUndo).ToString()); return(ret); }
public IEnumerable <Issue> Compare(TextReader expected, TextReader real) { List <string> lexpected = TextIO.SplitLines(expected).Select(x => x.TrimEnd('\r', '\n')).ToList(), lreal = TextIO.SplitLines(real).Select(x => x.TrimEnd('\r', '\n')).ToList(); while (lexpected.Count > 0 && string.IsNullOrEmpty(lexpected.Last())) { lexpected.RemoveAt(lexpected.Count - 1); } while (lreal.Count > 0 && string.IsNullOrEmpty(lreal.Last())) { lreal.RemoveAt(lreal.Count - 1); } if (lexpected.Count != lreal.Count) { yield return(new Issue(IssueLevel.Error, $"The count of lines are not equal: expected {lexpected.Count}, but real {lreal.Count}.")); yield break; } for (int i = 0; i < lexpected.Count; i++) { if (lexpected[i].TrimEnd() != lreal[i].TrimEnd()) { yield return(new Issue(IssueLevel.Error, $"Contents at line {i + 1} are not equal.")); } } }
private void Update1() { try { var wc = new System.Net.WebClient(); wc.DownloadFile("https://trends.google.co.jp/trends/api/dailytrends?hl=ja&tz=-540&geo=JP&ns=15", @"temp.txt"); wc.Dispose(); List <string> json; var b = TextIO.ReadStrings("temp.txt", out json); File.Delete("temp.txt"); if (b) { json.RemoveAt(0); } File.Delete("json.txt"); TextIO.WriteStrings("json.txt", json, false); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Indexファイルを作成(更新)します。既に存在する場合は上書きします。 /// </summary> /// <param name="WorldsPath">ワールドデータのパスのリスト</param> /// <param name="MaxIndex">使用済みインデックスの最大値</param> /// <returns>成功:true、失敗:false</returns> public static bool CreateIndexFile(List <string> WorldsPath, int MaxIndex) { var Strings = new List <string>(); // ヘッダを作成 Strings.Add("MCAS_Index_" + Define.MCAS_Version); Strings.Add("null"); Strings.Add("0"); Strings.Add("null"); Strings.Add("EOH"); int i = 0; // WorldPathがnullならファイルのみ作成 if (WorldsPath != null) { for (i = 0; i < WorldsPath.Count; i++) { Strings.Add(WorldsPath[i]); Strings.Add((i + MaxIndex + 1).ToString()); Strings.Add("0"); Strings.Add("0"); Strings.Add("null"); } } Strings[2] = (i + MaxIndex).ToString(); TextIO.WriteStrings(Define.IndexFile_Path, Strings); return(true); }
// ファイルの仕様 // [Index.save] // 0. "MCAS_Index_x.x.x" // 1. "null"(予約) // 2. 使用済みのインデックスの最大値 // 3. "null"(予約) // 4. "EOH"(ヘッダー終了) // 5. ファイルパス(絶対パス) // 6. インデックス(1以上のint) // 7. 前回のバックアップ時間 // 8. 前回のバックアップファイルの更新日時 // 9. "null"(予約) // 10.ファイルパス(絶対パス) // 11.インデックス(1以上のint) // 12.前回のバックアップ時間 // 13.前回のバックアップファイルの更新日時 // 14."null"(予約) /// <summary> /// Indexファイルを作成(更新)します。既に存在する場合は上書きします。 /// </summary> /// <param name="IndexList">Indexリスト</param> /// <param name="Header">Indexファイルのヘッダー</param> /// <returns>成功:true、失敗:false</returns> public static bool CreateIndexFile(List <Index> IndexList, IndexHeader Header) { var Strings = new List <string>(); // ヘッダを作成 Strings.Add(Header.MCAS_Ver); Strings.Add("null"); Strings.Add(Header.MaxIndex.ToString()); Strings.Add("null"); Strings.Add("EOH"); // IndexListがnullならファイルのみ作成 if (IndexList != null) { for (int i = 0; i < IndexList.Count; i++) { Strings.Add(IndexList[i].FilePath); Strings.Add(IndexList[i].IndexNum.ToString()); Strings.Add(IndexList[i].LastBackupTime.ToString()); Strings.Add(IndexList[i].LastBackupfileTime.ToString()); Strings.Add("null"); } } TextIO.WriteStrings(Define.IndexFile_Path, Strings, false); return(true); }
public Game(TextIO io, IRandom random, int maxNumber, int maxGuessCount) { _io = io; _random = random; _maxNumber = maxNumber; _maxGuessCount = maxGuessCount; }
private Game(Clock clock, Scoreboard scoreboard, TextIO io, IRandom random) { _clock = clock; _scoreboard = scoreboard; _io = io; _random = random; }
public async Task <ActionResult <ProblemPackage> > Export(string id) { IProblemProvider res = await _workspace.Problems.Get(id); if (res == null) { return(NotFound()); } try { ProblemPackage package = new ProblemPackage { Metadata = await res.GetMetadata(), Description = await res.GetDescription(), }; { List <ProblemPackage.TestCasePackage> ls = new List <ProblemPackage.TestCasePackage>(); IEnumerable <ITestCaseProvider> ss = await res.Samples.GetAll(); foreach (ITestCaseProvider s in ss) { ProblemPackage.TestCasePackage t = new ProblemPackage.TestCasePackage { Metadata = await s.GetMetadata(), Input = await TextIO.ToString(await s.GetInput()), Output = await TextIO.ToString(await s.GetOutput()), }; ls.Add(t); } package.Samples = ls; } { List <ProblemPackage.TestCasePackage> ls = new List <ProblemPackage.TestCasePackage>(); IEnumerable <ITestCaseProvider> ss = await res.Tests.GetAll(); foreach (ITestCaseProvider s in ss) { ProblemPackage.TestCasePackage t = new ProblemPackage.TestCasePackage { Metadata = await s.GetMetadata(), Input = await TextIO.ToString(await s.GetInput()), Output = await TextIO.ToString(await s.GetOutput()), }; ls.Add(t); } package.Tests = ls; } return(Ok(package)); } catch { return(NoContent()); } }
public void WriteLine_Float_FormatsNumberSameAsBasic(float value, string basicString) { var outputWriter = new StringWriter(); var io = new TextIO(new StringReader(""), outputWriter); io.WriteLine(value); outputWriter.ToString().Should().BeEquivalentTo(basicString + Environment.NewLine); }
public HomeTeamPlay(TextIO io, IRandom random, Clock clock, Defense defense) : base(io, random, clock) { _io = io; _random = random; _clock = clock; _defense = defense; _ballContest = new BallContest(0.5f, "Shot is blocked. Ball controlled by {0}.", _io, _random); }
void GetGunStates() { string r = TextIO.ReadFile("Assets/TextFiles/GunStates.txt"); lock_state_1_ = r[0] == '1' ? true : false; lock_state_2_ = r[1] == '1' ? true : false; lock_state_3_ = r[2] == '1' ? true : false; lock_state_4_ = r[3] == '1' ? true : false; }
private void Update2() { try { var selectionText = ModeSelect.SelectionBoxItem.ToString(); DateTime dt = DateTime.Now; if (selectionText == "1日前") { dt = dt.AddDays(-1); } else if (selectionText == "2日前") { dt = dt.AddDays(-2); } else if (selectionText == "3日前") { dt = dt.AddDays(-3); } else if (selectionText == "4日前") { dt = dt.AddDays(-4); } else if (selectionText == "5日前") { dt = dt.AddDays(-5); } else if (selectionText == "6日前") { dt = dt.AddDays(-6); } else if (selectionText == "7日前") { dt = dt.AddDays(-7); } var wc = new System.Net.WebClient(); wc.DownloadFile("https://trends.google.com/trends/api/dailytrends?geo=JP&ed=" + dt.Year.ToString("D4") + dt.Month.ToString("D2") + dt.Day.ToString("D2"), @"temp1.txt"); wc.Dispose(); List <string> json; var b = TextIO.ReadStrings("temp1.txt", out json); File.Delete("temp1.txt"); if (b) { json.RemoveAt(0); } File.Delete("json1.txt"); TextIO.WriteStrings("json1.txt", json, false); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void ReadNumbers_ArrayEmpty_ThrowsArgumentException() { var io = new TextIO(new StringReader(""), new StringWriter()); Action readNumbers = () => io.ReadNumbers("foo", Array.Empty <float>()); readNumbers.Should().Throw <ArgumentException>() .WithMessage("'values' must have a non-zero length.*") .WithParameterName("values"); }
/// <summary> /// 設定ファイルを読み込みます。 /// </summary> public static void ReadSettingsFile() { ConsoleIO.WriteLine("設定ファイルを読み込み中…"); bool b = false; if (TextIO.ReadStrings(Define.SettingsFileName, out List <string> SettingsFile)) { if (SettingsFile[0] == "MCAS_Settings_" + Define.MCAS_Version) { if (int.TryParse(SettingsFile[1], out Define.BackupInterval)) { b = true; } else { ConsoleIO.WriteWarning("設定ファイルファイルが異常です。設定ファイルを新規作成します。"); b = false; } } else { ConsoleIO.WriteWarning("設定ファイルのバージョンが異なるかファイルが異常です。設定ファイルを新規作成します。"); b = false; } } else { ConsoleIO.WriteWarning("設定ファイルが見つかりません。設定ファイルを新規作成します。"); b = false; } if (b) { ConsoleIO.WriteLine("設定ファイルの読み込みに成功しました。"); } else { SettingsFile = new List <string>(); SettingsFile.Add("MCAS_Settings_" + Define.MCAS_Version); SettingsFile.Add("90000"); Define.BackupInterval = 90000; TextIO.WriteStrings(Define.SettingsFileName, SettingsFile, false); } ConsoleIO.WriteLine("バックアップ間隔は " + Define.BackupInterval + "[ms] に設定されています。"); if (Define.BackupInterval < 1000) { Define.LoopInterval = Define.BackupInterval / 2; } else { Define.LoopInterval = 500; } return; }
private void initBook(bool verbose) { bookMap = new Dictionary <ulong, List <BookEntry> >(); long t0 = SystemHelper.currentTimeMillis(); numBookMoves = 0; try { /* read /book.bin into buf */ Byte[] buf = Bookbin.DATA; Position startPos = TextIO.readFEN(TextIO.startPosFEN); Position pos = new Position(startPos); UndoInfo ui = new UndoInfo(); int len = buf.Length; for (int i = 0; i < len; i += 2) { int b0 = buf[i]; if (b0 < 0) { b0 += 256; } int b1 = buf[i + 1]; if (b1 < 0) { b1 += 256; } int move = (b0 << 8) + b1; if (move == 0) { pos = new Position(startPos); } else { bool bad = ((move >> 15) & 1) != 0; int prom = (move >> 12) & 7; Move m = new Move(move & 63, (move >> 6) & 63, promToPiece(prom, pos.whiteMove)); if (!bad) { addToBook(pos, m); } pos.makeMove(m, ui); } } } catch (ChessParseError ex) { throw new RuntimeException(); } catch (IOException ex) { SystemHelper.println("Can't read opening book resource"); throw new RuntimeException(); } if (verbose) { long t1 = SystemHelper.currentTimeMillis(); SystemHelper.printf("Book moves: " + numBookMoves.ToString() + "(parse time: " + ((t1 - t0) / 1000).ToString() + ")"); } }
/// <summary> /// ファイルパスファイルを読み込みます。 /// </summary> /// <param name="FilePath">ファイルパスファイルへのパス</param> /// <returns></returns> public static string[] ReadFile_Array(string FilePath) { if (!(File.Exists("FilePath.txt"))) { Console.ForegroundColor = ConsoleColor.Red; ConsoleIO.WriteLine("Error: FilePath.txt が見つかりません。\n FilePath.txt に、ワールドデータへのパスを入力してください。"); Console.ForegroundColor = ConsoleColor.Gray; Environment.Exit(0); } List <string> WorldsPath_List = TextIO.ReadStrings("FilePath.txt"); string[] WorldsPath = WorldsPath_List.ToArray(); if (WorldsPath.Length == 0) { Console.ForegroundColor = ConsoleColor.Red; ConsoleIO.WriteLine("Error: FilePath.txt の中身がありません。\n FilePath.txt に、ワールドデータへのパスを入力してください。"); Console.ForegroundColor = ConsoleColor.Gray; Environment.Exit(0); } WorldsPath_List.Clear(); for (int i = 0; i < WorldsPath.Length; i++) { // 重複確認 if (Array.IndexOf(WorldsPath, WorldsPath[i]) != i) { Console.ForegroundColor = ConsoleColor.Green; ConsoleIO.WriteLine("Warning: FilePath.txt の " + (i + 1) + " 行目に記述のファイルパスは重複しています。"); Console.ForegroundColor = ConsoleColor.Gray; } else { if (ConfirmationWorldFile(WorldsPath[i], i)) { WorldsPath_List.Add(WorldsPath[i]); } } } WorldsPath = WorldsPath_List.ToArray(); if (WorldsPath.Length == 0) { Console.ForegroundColor = ConsoleColor.Red; ConsoleIO.WriteLine("Error: FilePath.txt の中に有効なファイルパスが存在しません。\n FilePath.txt に、ワールドデータへのパスを入力してください。"); Console.ForegroundColor = ConsoleColor.Gray; Environment.Exit(0); } return(WorldsPath); }
public async Task <ActionResult <SubmissionMetadata> > Submit([FromBody] SubmitData data) { if (await _workspace.Problems.Has(data.ProblemId) == false) { return(NotFound()); } if (await _workspace.Users.Has(data.UserId) == false) { return(NotFound()); } SubmissionMetadata meta = new SubmissionMetadata { Id = Guid.NewGuid().ToString(), ProblemId = data.ProblemId, UserId = data.UserId, Language = data.Language, Time = DateTimeOffset.Now, }; ISubmissionProvider sub = await _workspace.Submissions.Create(meta); if (sub == null) { return(Forbid()); } try { if (data.CodeFile != null) { using (System.IO.Stream s = data.CodeFile.OpenReadStream()) { meta.CodeLength = (uint)s.Length; await sub.SetCode(s); } } else { meta.CodeLength = (uint)Encoding.UTF8.GetByteCount(data.Code); using (System.IO.Stream ms = TextIO.ToStream(data.Code ?? "")) await sub.SetCode(ms); } await sub.SetMetadata(meta); SendJudgeRequest(sub.Id); return(Created($"submissions/{meta.Id}", await sub.GetMetadata())); } catch { await _workspace.Submissions.Delete(sub.Id); return(Forbid()); } }
public static void LoadProxiesFromTextFile(FileLink fileLink, ProxyType proxyType = ProxyType.Http, NetworkType netType = NetworkType.Datacenter) { EmptyParamContract.Validate(fileLink); foreach (string line in TextIO.GetLines(fileLink.Path)) { Proxy proxy = Parse(line, proxyType, netType); if (proxy != null) { ProxyManager.AddProxy(proxy, false); } } }
public static Game Create(TextIO io, IRandom random) { io.Write(Resource.Streams.Introduction); var defense = new Defense(io.ReadDefense("Your starting defense will be")); var clock = new Clock(io); io.WriteLine(); var scoreboard = new Scoreboard( new Team("Dartmouth", new HomeTeamPlay(io, random, clock, defense)), new Team(io.ReadString("Choose your opponent"), new VisitingTeamPlay(io, random, clock, defense)), io); return(new Game(clock, scoreboard, io, random)); }
public void ReadingValuesHasExpectedPromptsAndResults <T>( Func <IReadWrite, T> read, string input, string expectedOutput, T expectedResult) { var inputReader = new StringReader(input + Environment.NewLine); var outputWriter = new StringWriter(); var io = new TextIO(inputReader, outputWriter); var result = read.Invoke(io); var output = outputWriter.ToString(); using var _ = new AssertionScope(); output.Should().Be(expectedOutput); result.Should().BeEquivalentTo(expectedResult); }