public void UpdateMeta(int serialLength) { BulkDataStartOffset += serialLength - Exports.First().SerialSize; Exports.First().SerialSize = serialLength; NameCount = Names.Length; int num = 193; int num2 = 0; FNameEntry[] names = Names; foreach (FNameEntry fNameEntry in names) { num2 += fNameEntry.GetLength(); } int num3 = ImportCount * 28; int num4 = ExportCount * 108; ImportOffset = num + num2; ExportOffset = num + num2 + num3; DependsOffset = num + num2 + num3 + num4 - 4; TotalHeaderSize = num + num2 + num3 + num4 + 4; AssetRegistryDataOffset = num + num2 + num3 + num4; PreloadDependencyOffset = TotalHeaderSize; Generations.First().NameCount = Names.Length; Exports.First().SerialOffset = TotalHeaderSize; }
public Core() { taskScheduler = new GHMattiTaskScheduler(); initialized = false; EventHandlers["onServerResourceStart"] += new Action <string>(Initialization); Exports.Add("Query", new Func <string, dynamic, Task <int> >( (query, parameters) => Query(query, parameters)) ); Exports.Add("QueryResult", new Func <string, dynamic, Task <MySQLResult> >( (query, parameters) => QueryResult(query, parameters)) ); Exports.Add("QueryScalar", new Func <string, dynamic, Task <dynamic> >( (query, parameters) => QueryScalar(query, parameters)) ); Exports.Add("QueryAsync", new Action <string, dynamic, CallbackDelegate>( (query, parameters, cb) => QueryAsync(query, parameters, cb)) ); Exports.Add("QueryResultAsync", new Action <string, dynamic, CallbackDelegate>( (query, parameters, cb) => QueryResultAsync(query, parameters, cb)) ); Exports.Add("QueryScalarAsync", new Action <string, dynamic, CallbackDelegate>( (query, parameters, cb) => QueryScalarAsync(query, parameters, cb)) ); Exports.Add("Insert", new Action <string, dynamic>( (table, parameters) => Insert(table, parameters)) ); }
public Main() { Debug.WriteLine(typeof(MySql.Data.MySqlClient.MySqlConnection).Name); // to work around mysql-async ready event not triggering on starts Exports.Add("hasTicked", new Func <bool>(() => m_ticked)); }
public Data() { EventHandlers.Add("Sync:Client:Data:Get", new Action <object>(GetServer)); EventHandlers.Add("Sync:Client:Data:GetAll", new Action <dynamic>(GetAllServer)); EventHandlers.Add("Sync:Client:Data:Has", new Action <bool>(HasServer)); Exports.Add("client_sync_data_enable_debug", new Action <bool, CallbackDelegate>((enableDebug, callback) => { Debug = enableDebug; })); Exports.Add("client_sync_data_set", new Action <int, string, object>(Set)); Exports.Add("client_sync_data_reset", new Action <int, string>(Reset)); Exports.Add("client_sync_data_get", new Func <int, string, Task <object> >(async(id, key) => await Get(id, key))); Exports.Add("client_sync_data_getall", new Func <int, Task <object> >(async id => await GetAll(id))); Exports.Add("client_sync_data_has", new Func <int, string, Task <bool> >(async(id, key) => await Has(id, key))); Exports.Add("client_sync_data_set_locally", new Action <int, string, object>(SetLocally)); Exports.Add("client_sync_data_reset_locally", new Action <int, string>(ResetLocally)); Exports.Add("client_sync_data_get_locally", new Func <int, string, object>(GetLocally)); Exports.Add("client_sync_data_getall_locally", new Func <int, object>(GetAllKeyLocally)); Exports.Add("client_sync_data_has_locally", new Func <int, string, bool>(HasLocally)); TriggerEvent("OnClientSyncDataLoaded", CitizenFX.Core.Native.API.GetCurrentResourceName()); }
/// <summary> /// Written to produce certificates that were not collected on the day. 2017-01-22 /// </summary> /// <returns></returns> public string [] CustomOpenCert( ) { List <CertificateData> certs = new List <CertificateData>(); //foreach ( ACompetitor a in getCurrentChampionship().ListAllCompetitors().OrderBy(x => x.checkParameter("School")).ToList() ) //{ // if ( a.Result == null ) continue ; // if ( a.result.rank <= 13 ) continue; // if ( a.Result.CertificateEarned ) // certs.AddRange ( ACertificate.GenerateCertificates( a ) ); //} foreach (AEvent Event in getCurrentChampionship().listAllEvents()) { certs.AddRange(Event.getCertificateData( )); } List <string> tempFiles = new List <string>(); tempFiles.AddRange(PrintCertificates.SaveIndividualCertificates(certs, ((App)Application.Current).CurrentChampionship.getChampionshipExportsDir( ))); Exports.MergeMultiplePDFIntoSinglePDF(((App)Application.Current).CurrentChampionship.getChampionshipExportsDir( ) + "\\All Certs.pdf", tempFiles.ToArray( )); return(tempFiles.ToArray( )); }
public ExecutionStatus Execute() { var method = Exports.GetMethod("start"); if (method is null) { return(ExecutionStatus.MissingEntry); } var gasLimitField = Exports.GetField("💩 GasLimit"); gasLimitField.SetValue(null, GasLimit); try { CompiledInstance.Exports.start(); } catch (OverflowException e) { Logger.LogWarning($"Overflow exception {e}"); throw new OutOfGasException(GasUsed); } catch (InvalidProgramException e) { Logger.LogWarning($"Invalid program exception {e}"); return(ExecutionStatus.JitCorruption); } return(ExecutionStatus.Ok); }
private void generateDataEventyForms_Click(object sender, RoutedEventArgs e) { List <AEvent> evs = new List <AEvent>(); //if ( ((App)Application.Current ).CurrentChampionship.Name.Contains ( "TF" ) ) //{ foreach (EventVM Event in ((App)Application.Current).CurrentChampionship.Events) { evs.Add(Event.Event); } try { Exports.GenerateResultEntryForms(evs, true); } catch (Exception ex) { MessageBox.Show("Failed to open results sheet. \n" + ex.Message); } //} //else //{ //// 2015-06-07 printBothResults is part of the cross country application. //new Print ( ).printBothResults ( evs , true ); //} }
public async Task AddOrUpdateExport(BeatmapExport export) { if (export.BeatmapId == null || export.BeatmapId.Length == 0) { Console.WriteLine("No beatmap found."); return; } var beatmap = await Beatmaps.FindAsync(export.BeatmapId); if (beatmap == null) { Console.WriteLine("No beatmap found."); return; } var exist = await Exports.FindAsync(export.Id); if (exist != null) { exist.UpdateTime = DateTime.Now; exist.ExportPath = export.ExportPath; exist.IsValid = true; } else { export.Beatmap = beatmap; Exports.Add(export); } await SaveChangesAsync(); }
private void ExportAthleteProfiles_Click(object sender, RoutedEventArgs e) { List <Athlete> athletes = new List <Athlete>(); foreach (EventVM Event in ((App)Application.Current).CurrentChampionship.Events) { foreach (ACompetitor competitor in Event.Event.EnteredCompetitors.Where(c => c.SelectedForNextEvent)) { if (competitor is Competitor) { if (!athletes.Contains(((Competitor)competitor).Athlete)) { athletes.Add(((Competitor)competitor).Athlete); } } } } try { athletes = athletes.OrderBy(c => c.DateOfBirth).OrderBy(c => c.Gender).ToList( ); Exports.GenerateAthleteProfile(athletes, false); } catch (Exception ex) { MessageBox.Show("Failed to open athletes profile sheets. \n" + ex.Message); } }
private void ExportEnvelopes_Click(object sender, RoutedEventArgs e) { List <Team> teams = ((App)Application.Current).CurrentChampionship.Championship.Teams.ToList(); List <AEvent> events = ((App)Application.Current).CurrentChampionship.Championship.Events.ToList(); Exports.GenerateEnvelope(teams, events); }
public override void PostSetup(IServiceProvider serviceProvider) { base.PostSetup(serviceProvider); Exports.RegisterMetadataProvider(serviceProvider.GetService <CXXMetadataProvider>()); Exports.RegisterMetadataProvider(serviceProvider.GetService <UnrealMetadataProvider>()); }
public ExportInfo(string extension, Exports export, Type exportType, bool haveSettings) { Extension = extension; ExportType = exportType; Export = export; HaveSettings = haveSettings; }
public bool ExecuteCommand(Exports.ICommand command) { if (m_log.IsDebugEnabled) { m_log.Debug("Created new command of type " + command); } bool result = false; if (command.CanExecute(m_engine)) { if (m_log.IsDebugEnabled) { m_log.Debug("Executing command of type " + command.GetType()); } command.Execute(m_engine); result = true; } else { if (m_log.IsDebugEnabled) { m_log.Debug("Command of type " + command.GetType() + "cannot be executed now"); } } return result; }
/// <summary> /// Initializes a new instance of the <see cref="SCInfo"/> class. /// </summary> /// <param name="SCFile">The sc file used to load this instance.</param> internal SCInfo(SCFile SCFile) { this.SCFile = SCFile; this.Exports = new Exports(); this.Temporary = new Temporary(); }
public ServerBase() { Exports.Add("QueryResult", new Func <string, dynamic, Task <List <dynamic> > >( (query, parameters) => QueryResult(query, parameters)) ); Exports.Add("QueryAsync", new Action <string, dynamic, CallbackDelegate>( (query, parameters, cb) => QueryAsync(query, parameters, cb)) ); _saveMinutes = 15; _flushHours = 3; _logger = new ServerLogger("GGSQL", LogLevel.Info); EventHandlers["onServerResourceStart"] += new Action <string>(BaseOnServerResourceStart); EventHandlers["playerReady"] += new Action <Player>(OnPlayerReady); EventHandlers["gg_internal:updateXpMoney"] += new Action <int, int, int>(OnUpdateXpAndMoney); EventHandlers["gg_internal:syncUsers"] += new Action <string>(OnUsersSync); EventHandlers["gg_internal:syncUser"] += new Action <string, string>(OnUserSync); EventHandlers["gg_internal:syncWinner"] += new Action <string>(OnWinnerSync); // Tick += SaveTick; // Tick += FlushTick; Tick += InitializeController; }
public Weather() { // Add the exports Exports.Add("getWeatherSyncMode", new Func <int>(() => API.GetConvarInt("simplesync_modeweather", 0))); Exports.Add("setWeatherSyncMode", new Func <int, bool>((i) => SetSyncMode(i, "simplesync_modeweather"))); Exports.Add("getWeather", new Func <string>(() => currentWeather)); Exports.Add("setWeather", new Func <string, bool>(SetWeather)); Exports.Add("getTransitionWeather", new Func <string>(() => transitionWeather)); Exports.Add("getNextWeatherFetch", new Func <long>(() => nextFetch)); Exports.Add("getWeatherTransitionFinish", new Func <long>(() => transitionFinish)); // Get the Weather Switches as a string string data = API.LoadResourceFile(API.GetCurrentResourceName(), "Switch.json"); // And try to parse it try { switches = JsonConvert.DeserializeObject <Dictionary <string, List <string> > >(data); } // If we failed, notify it catch (JsonException e) { Debug.WriteLine($"Error when parsing Switch.json: {e.Message}"); } // And log some important commands Logging.Log("Weather Synchronization has started"); Logging.Log($"Sync Mode is set to {Convars.WeatherMode}"); Logging.Log(string.IsNullOrWhiteSpace(Convars.OpenWeatherKey) ? "No OpenWeather API Key is set" : "An OpenWeather API Key is present"); Logging.Log(string.IsNullOrWhiteSpace(Convars.OpenWeatherCity) ? "No OpenWeather City is set" : $"OpenWeather City is set to {Convars.OpenWeatherCity}"); }
public string GetMaxVersion() { if (!Exports.Any()) { return(CurrentVersion); } long numeric = 0; string version = "0.0.0.0"; foreach (string ver in Exports.Select(e => e.Version)) { long current = convertToLong(ver); if (current > numeric) { numeric = current; version = ver; } } return(version); }
/// <summary> /// Register the exports /// </summary> private void RegisterExports() { Exports.Add("show", new Action(ShowInteraction)); Exports.Add("hide", new Action(HideInteraction)); Exports.Add("highlight", new Action <bool>(Highlight)); Exports.Add("option", new Action <int, string>(SetOption)); Exports.Add("reset", new Action(Reset)); }
public InputMessagesProcessor(Exports.IChessEngine engine, Exports.IReadOnlyMessageQueue message_queue) { Debug.Assert(engine != null); m_engine = engine; Debug.Assert(message_queue != null); m_message_queue = message_queue; }
public Passive() { Exports.Add("getActivation", new Func <int, bool>(GetPlayerActivation)); Exports.Add("setActivation", new Func <int, bool, bool>(SetPlayerActivation)); Exports.Add("isOverriden", new Func <int, bool>((id) => overrides.ContainsKey(id))); Exports.Add("setOverride", new Func <int, bool, bool>(SetPlayerOverride)); Exports.Add("clearOverride", new Func <int, bool>(ClearOverride)); }
public Passive() { // Add the exports Exports.Add("getActivation", new Func <bool>(() => GetPlayerActivation(Game.Player.ServerId))); Exports.Add("setActivation", new Action <bool>(SetPassiveActivation)); // And tell the server that this client is ready to work TriggerServerEvent("simplepassive:initialized"); }
public void ListDates() { var dates = Exports.ListExportDates(); Assert.NotNull(dates); Assert.NotEmpty(dates); Assert.True(dates[0].Date != DateTime.MinValue); }
public bool IsPieceAt(ChessboardCell cell, out Players player, out Exports.Pieces piece) { int data = m_cells[cell.Value]; player = (Players)DecodePlayer(data); piece = (Exports.Pieces)DecodePiece(data); return piece != Exports.Pieces.NoPiece; }
private void PrintAthleteNotesT(object obj) //Tuple < int, string > tuple ) // AthleteID, string Printer = "A5-1" ) { // FC 2017-01-11 To Do Tuple <int, string> tuple = (Tuple <int, string>)obj; int AthleteID = tuple.Item1; string Printer = tuple.Item2; if (AthleteID == 0) { return; } // existing athlete Athlete Athlete = getAthlete((int)AthleteID); if (Athlete == null) { return; } List <Athlete> athletes = new List <Athlete>() { Athlete }; PrintOptions po; switch (Printer) { case "A5-1": po = PrintOptions.A5_1; break; case "A5-2": po = PrintOptions.A5_2; break; case "PDF": po = PrintOptions.PDF; break; default: po = PrintOptions.NO_PRINT; break; } try { Exports.GenerateAthleteProfile(athletes, false, po, false, true); } catch // ( Exception ex ) { //MessageBox.Show ( "Failed to open athletes profile sheets. \n" + ex.Message ); return; } }
public KoiStream(string name, IReadableSegment contents, ILogger logger) : base(name, contents) { var reader = contents.CreateReader(); logger.Debug(Tag, "Reading koi stream header..."); uint magic = reader.ReadUInt32(); if (magic != Signature) { logger.Warning(Tag, $"Koi stream data does not start with a valid signature (Expected 0x{Signature:X4} but read 0x{magic:X4})."); } uint mdCount = reader.ReadUInt32(); uint strCount = reader.ReadUInt32(); uint expCount = reader.ReadUInt32(); logger.Debug(Tag, $"Reading {mdCount} references..."); for (int i = 0; i < mdCount; i++) { uint id = Utils.ReadCompressedUInt(ref reader); uint token = Utils.FromCodedToken(Utils.ReadCompressedUInt(ref reader)); References.Add(id, new MetadataToken(token)); } logger.Debug(Tag, $"Reading {strCount} strings..."); for (int i = 0; i < strCount; i++) { uint id = Utils.ReadCompressedUInt(ref reader); int length = (int)Utils.ReadCompressedUInt(ref reader); byte[] buffer = new byte[length * 2]; reader.ReadBytes(buffer, 0, buffer.Length); Strings.Add(id, Encoding.Unicode.GetString(buffer)); } logger.Debug(Tag, $"Reading {expCount} exports..."); for (int i = 0; i < expCount; i++) { uint id = Utils.ReadCompressedUInt(ref reader); var exportInfo = VMExportInfo.FromReader(ref reader); // Exports in KoiVM either point to entrypoints of virtualised methods, or just act as a descriptor // for methods that are intra linked through instructions like ldftn. if (exportInfo.IsSignatureOnly) { logger.Debug(Tag, $"Export {id} maps to a method signature of an intra-linked method."); } else { logger.Debug(Tag, $"Export {id} maps to function_{exportInfo.EntrypointAddress:X4}."); } Exports.Add(id, exportInfo); } }
/** * Call remote procedure MOUNTPROC_EXPORT_1. * @return Result from remote procedure call (of type exports). * @throws OncRpcException if an ONC/RPC error occurs. * @throws IOException if an I/O error occurs. */ public Exports MOUNTPROC_EXPORT() { XdrVoid args_ = XdrVoid.XDR_VOID; Exports result_ = new Exports(); client.call(NFSv2MountProtocol.MOUNTPROC_EXPORT, NFSv2MountProtocol.MOUNTVERS, args_, result_); return(result_); }
/// <summary> /// Add a single repository to the set that is exported by this daemon. /// <para /> /// The existence (or lack-thereof) of <code>git-daemon-export-ok</code> is /// ignored by this method. The repository is always published. /// </summary> /// <param name="name"> /// name the repository will be published under. /// </param> /// <param name="db">the repository instance. </param> public void ExportRepository(string name, Repository db) { if (!name.EndsWith(Constants.DOT_GIT_EXT)) { name = name + Constants.DOT_GIT_EXT; } Exports.Add(name, db); RepositoryCache.register(db); }
public void AddExport(string sheetName, dynamic export, dynamic data) { Exports.Add(new ExportItem() { Export = export, Data = data, SheetName = sheetName }); }
public BaseServer() { Tick += FirstTick; Self = this; Exports.Add("registerPluginOutlet", new Action <string, CallbackDelegate>(this.RegisterPluginOutlet)); Exports.Add("registerPluginPage", new Action <string, CallbackDelegate>(this.RegisterPluginPage)); Exports.Add("isInRole", new Func <string, bool>(this.IsInRole)); Exports.Add("getPluginUrl", new Func <string, IDictionary <string, object>, string>(this.GetPluginUrl)); }
public void ListFiles() { var dates = Exports.ListExportDates(); var files = Exports.ListExportFiles(dates[0].Date); Assert.NotNull(files); Assert.NotEmpty(files); Assert.NotNull(files[0].Name); Assert.NotNull(files[0].Md5Sum); }
/// <summary> /// Expects there to be only one export of the interface T /// If several exists the first export will be used /// /// To get a specific type use the the overloads of Get /// </summary> /// <returns></returns> public static T Get() { if (ExportAttribute.InstanceRule == InstanceRule.Multiple) { Activator.CreateInstance(Exports.First()); } //throw new Exception("Cant get singleton from type marked as multiple"); return(Singleton); }
public void ShouldSignFileWithExportMethodsUnicode() { Exports.SignFileWithSHA256Unicode(FileName, "evtInfoEmpregador", SerialNumber, TokenPin); var signedXml = new XmlDocument(); signedXml.Load(FileName); signedXml.Save("envio-assinado-exports-unicode.xml"); Assert.IsTrue(signedXml.GetElementsByTagName("Signature").Count > 0); }
private void SetupExports() { Exports.Add("SpawnCar", new Func <string, Task <Vehicle> >((veh) => { return(SpawnCar(veh)); })); Exports.Add("SpawnCarWithCoords", new Func <string, dynamic, Task <Vehicle> >((veh, coord) => { return(SpawnCar(veh, coord)); })); }
/// <summary> /// Constructor for pawn promotions moves /// </summary> public Move(int from_cell, int to_cell, Flags flags, Exports.Pieces promote_to) { Debug.Assert(flags.HasFlag(Flags.Promotion)); Debug.Assert(!(flags.HasFlag(Flags.EnPassantCapture) || flags.HasFlag(Flags.ShortCastle) || flags.HasFlag(Flags.LongCastle))); Debug.Assert(promote_to == Exports.Pieces.Knight || promote_to == Exports.Pieces.Bishop || promote_to == Exports.Pieces.Rook || promote_to == Exports.Pieces.Queen); m_data = new Bitmask32(); Init((int)Exports.Pieces.Pawn, from_cell, to_cell, (int)flags, (int)promote_to); }
public Move(Exports.Pieces piece, int from_cell, int to_cell, uint cell_index, Flags flags) { // If castle flag is set, then this must be a king's move Debug.Assert( !((flags.HasFlag(Flags.ShortCastle) || flags.HasFlag(Flags.LongCastle)) && piece != Exports.Pieces.King)); // Must use another consructor for pawn promotions Debug.Assert(!flags.HasFlag(Flags.Promotion)); // EnPassantCapture implies Capture Debug.Assert(!flags.HasFlag(Flags.EnPassantCapture) || flags.HasFlag(Flags.Capture)); m_data = new Bitmask32(); Init((int)piece, from_cell, to_cell, (int)flags, 0); }
public Exports.UserExportApplyResult UserExportApplyResult( string machineName, string securityToken, Exports.UserExportApply exportApply, VehicleInfo vehicleInfo) { Exports.UserExportApplyResult result = null; string messageResult = this.GetInvalidLoginTokenResult(machineName, securityToken); if (!string.IsNullOrEmpty(messageResult)) return new Exports.UserExportApplyResult() { HResult = -10, ErrorMsg = messageResult }; throw new NotImplementedException(); if (result != null && result.HResult == 0) { //如果成功申报,则需要清理时间戳,必须重新刷卡登录 SecurityTokenManager.Instance.RemoveToken(securityToken); } }
public MibModule(ISymbolEnumerator symbols) { if (symbols == null) { throw new ArgumentNullException("lexer"); } Symbol temp = symbols.NextNonEOLSymbol(); temp.AssertIsValidIdentifier(); _name = temp.ToString().ToUpperInvariant(); // all module names are uppercase temp = symbols.NextNonEOLSymbol(); temp.Expect(Symbol.Definitions); temp = symbols.NextNonEOLSymbol(); temp.Expect(Symbol.Assign); temp = symbols.NextSymbol(); temp.Expect(Symbol.Begin); temp = symbols.NextNonEOLSymbol(); if (temp == Symbol.Imports) { _imports = ParseDependents(symbols); } else if (temp == Symbol.Exports) { _exports = ParseExports(symbols); } else { symbols.PutBack(temp); } ParseEntities(symbols); }
public PlugInAssemblyExport(Exports.IAssembly assembly) { this.assembly = assembly; }
public MoveDesc GetLegalMove(ChessboardCell from, ChessboardCell to, Exports.Pieces promote_to) { lock (m_legal_moves_lock) { return m_legal_moves?.Find(x => x.From.IsSame(from) && x.To.IsSame(to) && x.IsPromotion && x.PromoteTo == promote_to); } }
private static byte Encode(Players player, Exports.Pieces piece) { if (piece == Pieces.NoPiece) { return 0; } return (byte)(((int)player << 3) + (int)piece); }
private void AddPiece(Players player, Exports.Pieces piece, int index) { Debug.Assert(m_cells[index] == 0); m_cells[index] = Encode(player, piece); }
public static PlayerPieceSet MovePiece(PlayerPieceSet base_obj, Exports.Pieces piece, int remove_at_cell, int new_cell) { Debug.Assert(base_obj != null); Debug.Assert(piece != Exports.Pieces.NoPiece); Debug.Assert(remove_at_cell >= 0 && remove_at_cell < 64); Debug.Assert(new_cell >= 0 && new_cell < 64); Debug.Assert(remove_at_cell != new_cell); Debug.Assert(base_obj.IsOccupiedCell(remove_at_cell)); Debug.Assert(!base_obj.IsOccupiedCell(new_cell)); var result = (PlayerPieceSet)base_obj.MemberwiseClone(); result.m_bitboard.UnsetBit(remove_at_cell); result.m_bitboard.SetBit(new_cell); // Insert new_cell first. Easier to do it now, because we know // the sorted ranges uint range_begin = 0; uint range_length = 0; switch (piece) { case Exports.Pieces.Pawn: range_begin = result.PawnsStartIndex; range_length = result.PawnsCount; break; case Exports.Pieces.Knight: range_begin = result.KnightsStartIndex; range_length = result.KnightsCount; break; case Exports.Pieces.Bishop: range_begin = result.BishopsStartIndex; range_length = result.BishopsCount; break; case Exports.Pieces.Rook: range_begin = result.RooksStartIndex; range_length = result.RooksCount; break; case Exports.Pieces.Queen: range_begin = result.QueensStartIndex; range_length = result.QueensCount; break; case Exports.Pieces.King: range_begin = 0; range_length = 1; break; } bool is_inserted = false; for (uint i = range_begin, e = range_begin + range_length; i < e; ++i) { if (new_cell < result.m_pieces_cells.GetCell(i)) { result.m_pieces_cells.InsertAt(i, new_cell); is_inserted = true; break; } } if (!is_inserted) { result.m_pieces_cells.InsertAt(range_begin + range_length, new_cell); } result.m_pieces_cells.EraseAt( (uint)result.m_pieces_cells.FindIndex(remove_at_cell)); return result; }
private static void MakeMovesAlongLine(Exports.Pieces piece, PlayerPieceSet my_pieces, PlayerPieceSet other_pieces, int from_cell, int delta_row, int delta_column, int count, List<Move> moves) { var from_cell_obj = new ChessboardCell(from_cell); // count must be such that we hit the border of the chessboard at the end // of the loop Debug.Assert( from_cell_obj.Row + count * delta_row == Chessboard.ROW_MIN || from_cell_obj.Row + count * delta_row == Chessboard.ROW_MAX || from_cell_obj.Column + count * delta_column == Chessboard.COLUMN_MIN || from_cell_obj.Column + count * delta_column == Chessboard.COLUMN_MAX); int cur_row = from_cell_obj.Row; int cur_column = from_cell_obj.Column; for (int i = 0; i < count; ++i) { cur_row += delta_row; cur_column += delta_column; Debug.Assert(cur_row >= Chessboard.ROW_MIN && cur_row <= Chessboard.ROW_MAX && cur_column >= Chessboard.COLUMN_MIN && cur_column <= Chessboard.COLUMN_MAX); var cur_cell = ChessboardCell.CalculateValue(cur_row, cur_column); if (my_pieces.IsOccupiedCell(cur_cell)) { break; } bool is_capture = other_pieces.IsOccupiedCell(cur_cell); moves.Add(new Move(piece, from_cell, cur_cell, 0 /* TODO - FIXME */, is_capture ? Move.Flags.Capture : 0)); if (is_capture) { break; } } }
IEnumerable<ICommandOutput> LoadPlugin(Exports.ISolutionPlugin plugin) { yield return new Info("Starting plugin {0}.", plugin.Name); Exception error = null; if (!TryDo(()=> _plugins.Add(new KeyValuePair<string,IDisposable>(plugin.Name,plugin.Start())), ex => error = ex)) yield return new Warning("Plugin initialization failed.\r\n" + error); }
private static void MakeDiagonalMoves(Exports.Pieces piece, PlayerPieceSet my_pieces, PlayerPieceSet other_pieces, int from_cell, uint cell_index, List<Move> moves) { Debug.Assert(piece == Exports.Pieces.Bishop || piece == Exports.Pieces.Queen); var from_cell_obj = new ChessboardCell(from_cell); // Down-left diagonal MakeMovesAlongLine(piece, my_pieces, other_pieces, from_cell, -1, -1, Math.Min(from_cell_obj.Row, from_cell_obj.Column), moves); // Down-right diagonal MakeMovesAlongLine(piece, my_pieces, other_pieces, from_cell, 1, -1, Math.Min(Chessboard.ROW_MAX - from_cell_obj.Row, from_cell_obj.Column), moves); // Up-right diagonal MakeMovesAlongLine(piece, my_pieces, other_pieces, from_cell, 1, 1, Math.Min(Chessboard.ROW_MAX - from_cell_obj.Row, Chessboard.COLUMN_MAX - from_cell_obj.Column), moves); // Up-left diagonal MakeMovesAlongLine(piece, my_pieces, other_pieces, from_cell, -1, 1, Math.Min(from_cell_obj.Row, Chessboard.COLUMN_MAX - from_cell_obj.Column), moves); }
public static PlayerPieceSet InsertPiece(PlayerPieceSet base_obj, Exports.Pieces piece_to_insert, int insert_at_cell) { Debug.Assert(base_obj != null); Debug.Assert(piece_to_insert != Exports.Pieces.NoPiece && piece_to_insert != Exports.Pieces.King); Debug.Assert(insert_at_cell >= 0 && insert_at_cell < 64); Debug.Assert(!base_obj.IsOccupiedCell(insert_at_cell)); var result = (PlayerPieceSet)base_obj.MemberwiseClone(); result.m_bitboard.SetBit(insert_at_cell); uint start_index = 0; uint cur_piece_count = 0; switch (piece_to_insert) { // TODO - add checks like PawnsCount < MAX_PAWN_COUNT case Exports.Pieces.Pawn: start_index = result.PawnsStartIndex; cur_piece_count = result.PawnsCount; ++result.PawnsCount; break; case Exports.Pieces.Knight: start_index = result.KnightsStartIndex; cur_piece_count = result.KnightsCount; // Increment result.KnightsCount ++result.PawnsStartIndex; break; case Exports.Pieces.Bishop: start_index = result.BishopsStartIndex; cur_piece_count = result.BishopsCount; // Increment result.BishopsCount ++result.PawnsStartIndex; ++result.KnightsStartIndex; break; case Exports.Pieces.Rook: start_index = result.RooksStartIndex; cur_piece_count = result.RooksCount; // Increment result.RooksCount ++result.PawnsStartIndex; ++result.KnightsStartIndex; ++result.BishopsStartIndex; break; case Exports.Pieces.Queen: start_index = result.QueensStartIndex; cur_piece_count = result.QueensCount; // Increment result.QueensCount ++result.PawnsStartIndex; ++result.KnightsStartIndex; ++result.BishopsStartIndex; ++result.RooksStartIndex; break; } result.m_pieces_cells.InsertAt(result.m_pieces_cells .GetInsertionIndex(start_index, cur_piece_count, insert_at_cell), insert_at_cell); return result; }
public bool MakeChildNewRoot(ChessboardCell from, ChessboardCell to, Exports.Pieces promote_to = Exports.Pieces.NoPiece) { if (Root == null) { return false; } // Discard all root children and their subtrees, except the child // specified by the method parameters ReleaseChildren(child => { return child.ParentMove.FromCell != from.Value || child.ParentMove.ToCell != to.Value || child.ParentMove.PromoteToPiece != promote_to; }, Root); if (Root.Children.Count != 1) { Clean(); m_listener.RootPositionChanged(null); return false; } // Discard current root Interlocked.Decrement(ref m_node_count); // Set a new root Root = Root.Children[0]; m_listener.RootPositionChanged(Root.Position); GenerateAllChildren(Root, 2); return true; }
public static PlayerPieceSet RemovePiece(PlayerPieceSet base_obj, Exports.Pieces piece_to_remove, int remove_at_cell) { Debug.Assert(base_obj != null); Debug.Assert(piece_to_remove != Exports.Pieces.NoPiece && piece_to_remove != Exports.Pieces.King); Debug.Assert(remove_at_cell >= 0 && remove_at_cell < 64); Debug.Assert(base_obj.IsOccupiedCell(remove_at_cell)); var result = (PlayerPieceSet)base_obj.MemberwiseClone(); result.m_bitboard.UnsetBit(remove_at_cell); uint start_index = 0; switch (piece_to_remove) { case Exports.Pieces.Pawn: start_index = result.PawnsStartIndex; Debug.Assert(result.PawnsCount > 0); --result.PawnsCount; break; case Exports.Pieces.Knight: start_index = result.KnightsStartIndex; Debug.Assert(result.KnightsCount > 0); // Decrement result.KnightsCount --result.PawnsStartIndex; break; case Exports.Pieces.Bishop: start_index = result.BishopsStartIndex; Debug.Assert(result.BishopsCount > 0); // Decrement result.BishopsCount --result.PawnsStartIndex; --result.KnightsStartIndex; break; case Exports.Pieces.Rook: start_index = result.RooksStartIndex; Debug.Assert(result.RooksCount > 0); // Decrement result.RooksCount --result.PawnsStartIndex; --result.KnightsStartIndex; --result.BishopsStartIndex; break; case Exports.Pieces.Queen: start_index = result.QueensStartIndex; Debug.Assert(result.QueensCount > 0); // Decrement result.QueensCount --result.PawnsStartIndex; --result.KnightsStartIndex; --result.BishopsStartIndex; --result.RooksStartIndex; break; } result.m_pieces_cells.EraseAt((uint)result.m_pieces_cells .FindNextIndex(start_index, remove_at_cell)); return result; }
private static void MakeHorizVertMoves(Exports.Pieces piece, PlayerPieceSet my_pieces, PlayerPieceSet other_pieces, int from_cell, List<Move> moves) { Debug.Assert(piece == Exports.Pieces.Rook || piece == Exports.Pieces.Queen); var from_cell_obj = new ChessboardCell(from_cell); // Left MakeMovesAlongLine(piece, my_pieces, other_pieces, from_cell, 0, -1, from_cell_obj.Column, moves); // Right MakeMovesAlongLine(piece, my_pieces, other_pieces, from_cell, 0, 1, Chessboard.COLUMN_MAX - from_cell_obj.Column, moves); // Down MakeMovesAlongLine(piece, my_pieces, other_pieces, from_cell, -1, 0, from_cell_obj.Row, moves); // Up MakeMovesAlongLine(piece, my_pieces, other_pieces, from_cell, 1, 0, Chessboard.ROW_MAX - from_cell_obj.Row, moves); }