public void OnExecuting(object sender, Puzzle.SideFX.Framework.Execution.ExecutionCancelEventArgs e) { IEngine engine = sender as IEngine; DisplayObjectsCommand displayObjectsCommand = DisplayObjectsCommand.Evaluate(engine, e.Command); if (displayObjectsCommand == null) return; IObjectService objectService = engine.GetService<IObjectService>(); IDisplayService displayService = engine.GetService<IDisplayService>(); IDatabaseService databaseService = engine.GetService<IDatabaseService>(); databaseService.EnsureTransaction(); Type type = objectService.GetTypeByName(displayObjectsCommand.ClassName); IList objects = null; if (!string.IsNullOrEmpty(displayObjectsCommand.Where)) objects = objectService.GetObjects(type, displayObjectsCommand.Where); else objects = objectService.GetObjects(type, displayObjectsCommand.Match); if (objects != null) { foreach (object obj in objects) { if (displayObjectsCommand.List) displayService.List(obj); else displayService.Display(obj); } } }
public void Construct(List<Puzzle> puzzles) { puzzles.Sort(); foreach (Puzzle puzzle in puzzles) { Puzzle automatedPuzzle = new Puzzle(); automatedPuzzle.Location = new System.Drawing.Point(puzzle.CoordinateX + form.Width - _image.Width - distanseBetweenControls, puzzle.CoordinateY + distanseBetweenControls); automatedPuzzle.Size = new System.Drawing.Size(puzzle.Width, puzzle.Height); automatedPuzzle.Width = puzzle.Width; automatedPuzzle.Height = puzzle.Height; automatedPuzzle.Image = puzzle.Image; automatedPuzzle.BorderStyle = BorderStyle.Fixed3D; automatedPuzzle.Click += new EventHandler(automatedPuzzle_Click); if (puzzle.topPuzzle != null && puzzle.topPuzzle.Image != null) { automatedPuzzle.topPuzzle= SetPuzzle(automatedPuzzle.topPuzzle); automatedPuzzle.topPuzzle.Image = puzzle.topPuzzle.Image; smallPuzzles.SetTopPuzzleLocation(automatedPuzzle); } if (puzzle.rightPuzzle != null && puzzle.rightPuzzle.Image != null) { automatedPuzzle.rightPuzzle = SetPuzzle(automatedPuzzle.rightPuzzle); automatedPuzzle.rightPuzzle.Image = puzzle.rightPuzzle.Image; smallPuzzles.SetRightPuzzleLocation(automatedPuzzle); } form.Controls.Add(automatedPuzzle); automatedConstructPuzzlesList.Add(automatedPuzzle); _image.SendToBack(); } }
public Puzzle.NPersist.Framework.Interfaces.IInterceptableList CreateListProxy(Type baseType, Puzzle.NPersist.Framework.Persistence.IObjectFactory objectFactory, params object[] ctorArgs) { // return Puzzle.NPersist.Framework.Proxy.ListProxyFactory.CreateProxy(baseType,objectFactory,ctorArgs) ; if (baseType == typeof(IInterceptableList) || baseType == typeof(InterceptableList) || baseType == typeof(IList)) { baseType = typeof(InterceptableList); return (Puzzle.NPersist.Framework.Interfaces.IInterceptableList) context.ObjectFactory.CreateInstance(baseType,ctorArgs); } #if NET2 else if (baseType.IsGenericType && baseType.IsInterface) { Type subType = baseType.GetGenericArguments ()[0]; Type genericType = typeof(InterceptableGenericsList<>).MakeGenericType(subType); return (Puzzle.NPersist.Framework.Interfaces.IInterceptableList) context.ObjectFactory.CreateInstance(genericType,ctorArgs); } #endif else { Type proxyType = aopEngine.CreateProxyType(baseType) ; object[] proxyArgs = aopEngine.AddStateToCtorParams(context,ctorArgs); return (Puzzle.NPersist.Framework.Interfaces.IInterceptableList) context.ObjectFactory.CreateInstance(proxyType,proxyArgs); //return Puzzle.NPersist.Framework.Proxy.ListProxyFactory.CreateProxy(baseType,objectFactory,ctorArgs) ; } }
public object HandleCall(Puzzle.NAspect.Framework.MethodInvocation call) { Console.WriteLine("Enter"); object res= call.Proceed(); Console.WriteLine("Exit"); return res; }
void Awake() { instance = this; List<Game> GamePrefabs = new List<Game>(Resources.LoadAll<Game>("Prefabs/Games/Puzzle")); GamePrefabs.RemoveAll(game => game.type != Game.GameType.Puzzle); GamePrefabs.Sort(delegate(Game a, Game b) { return a.order.CompareTo(b.order); }); puzzles = new List<Puzzle>(); foreach (Game game in GamePrefabs) { Puzzle puzzle = new Puzzle(); puzzle.name = game.name; puzzle.stars = PlayerPrefs.GetInt(puzzle.name + "stars", 0); if (puzzles.Count == 0) //first level is always unlocked puzzle.unlocked = true; else puzzle.unlocked = PlayerPrefs.GetInt(puzzle.name + "unlocked", 0) != 0; puzzle.prefab = game; puzzles.Add(puzzle); } }
// Use this for initialization void Start() { progress = 0; uiManager = GameObject.FindObjectOfType<UIManager>(); if (initialPuzzleIndex >= 0) { List<Puzzle> puzzleSet = new List<Puzzle>(puzzlesPrefabs.ToArray()); for (int i = 0; i < puzzleCount + remainingFailures; i++) { puzzlesToComplete.Add(puzzleSet[initialPuzzleIndex]); } currentPuzzle = SpawnPuzzle(puzzlesPrefabs[initialPuzzleIndex]); } else { List<Puzzle> puzzleSet = new List<Puzzle>(puzzlesPrefabs.ToArray()); for (int i = 0; i < puzzleCount + remainingFailures; i++) { int puzzleIndex = Random.Range(0, puzzleSet.Count); puzzlesToComplete.Add(puzzleSet[puzzleIndex]); puzzleSet.RemoveAt(puzzleIndex); if (puzzleSet.Count == 0) puzzleSet = new List<Puzzle>(puzzlesPrefabs.ToArray()); } currentPuzzle = SpawnPuzzle(puzzlesToComplete[progress]); } SetupCurrentPuzzle(); Run(); }
public PuzzleAnalysis(Puzzle start) { Start = start; Static = StaticAnalysis.Generate(start); Static.DeadMap = DeadMapAnalysis.FindDeadMap(Static); }
public override void OnMonsterDead(Puzzle puzzle, MonsterGroup group) { if (group.Remaining != 0) return; puzzle.GetPlace("Place").OpenAllDoors(); }
public override void OnPrepare(Puzzle puzzle) { var lockedPlace = puzzle.NewPlace("LockedPlace"); lockedPlace.DeclareLockSelf(); lockedPlace.ReservePlace(); }
public void InitOnceBeforeAnyTest() { puzzle = new Puzzle(6, 5, new List<byte> {0, 1, 3}, new List<byte> {1, 2}, new List<byte> {3, 4}, true); expected = new Puzzle(6, 5, new List<byte> {0, 1, 3}, new List<byte> {1, 2}, new List<byte> {3, 4}, true); solvedUpperPosition = new byte[,] {{6, 6, 7, 6, 7}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {0, 0, 7, 0, 7}}; solvedLowerPosition = new byte[,] {{0, 0, 7, 0, 7}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {6, 6, 7, 6, 7}}; }
public static String run(int[,] map2d) { // y1r-Solverは2xM, Nx2のパズルには対応していないため, // この時は横長, 縦長に強いSolver1を流用する if (Problem.row == 2 || Problem.column == 2) { return Solver1.run(map2d); } int[] puzzle = new int[Problem.partNum]; for (int i = 0; i < Problem.row; i++) for (int j = 0; j < Problem.column; j++) puzzle[i * Problem.column + j] = map2d[i, j]; Puzzle initial = new Puzzle( puzzle, Problem.column, Problem.row, Problem.selectionLimit, Problem.selectionCost, Problem.replacementCost); PuzzleSolver solver = new PuzzleSolver(initial, initial); solver.Solve(); // test(initial, solver.Puzzle.GetSolution()); Puzzle miniMap = solver.Puzzle; return MiniPuzzleSolver.Solve(miniMap); }
public static void test( Puzzle initial, String proconFormat ) { String[] lines = proconFormat.Split( new string[]{Environment.NewLine}, StringSplitOptions.None); int choiceCount = int.Parse( lines[0] ); for( int i = 0; i < choiceCount; i++ ) { String pos = lines[1 + i * 3]; int moveCount = int.Parse(lines[2 + i * 3]); int blankColumn = int.Parse(pos[0].ToString(), System.Globalization.NumberStyles.AllowHexSpecifier) + 1; int blankRow = int.Parse(pos[1].ToString(), System.Globalization.NumberStyles.AllowHexSpecifier) + 1; int blank = initial[blankColumn,blankRow]; initial.Choice(blank); for( int j = 0; j < moveCount; j++ ) { Puzzle.Position move = initial.CharToPosition(lines[(i + 1) * 3][j]); if (!initial.DoMove(move)) throw new Exception(); } } Console.WriteLine(); for (int i = 1; i <= Problem.row; i++) { for (int j = 1; j <= Problem.column; j++) { Console.Write(initial.Data[initial.CoordToPosition(j, i)] + "\t"); } Console.WriteLine(); } }
public override void OnPuzzleCreate(Puzzle puzzle) { var place = puzzle.GetPlace("PuzzlePlace"); place.SpawnSingleMob("Mob1", 120006, 3); // Young Country Rat place.SpawnSingleMob("Mob2", 30005, 8); // White Spiderling }
public override void OnPuzzleCreate(Puzzle puzzle) { var place = puzzle.GetPlace("PuzzlePlace"); place.SpawnSingleMob("Mob1", 50002, 3); // Red Fox place.SpawnSingleMob("Mob2", 50003, 2); // Gray Fox }
public void SetLeftPuzzleLocation(Puzzle puzzle) { for (int j = 0; j < puzzle.leftPuzzle.Count; j++) { Point point = new Point(); if (puzzle.ImageDegree == 0) { point = new Point(puzzle.Location.X, puzzle.Location.Y + puzzle.leftPuzzle[j].CoordinateY); } else if (puzzle.ImageDegree == 90) { point = new Point(puzzle.Location.X + puzzle.Size.Width - puzzle.leftPuzzle[j].CoordinateY - 10, puzzle.Location.Y); } else if (puzzle.ImageDegree == 180) { point = new Point(puzzle.Location.X + puzzle.Size.Width - 10, puzzle.Location.Y + puzzle.Size.Height - puzzle.leftPuzzle[j].CoordinateY-10); } else { point = new Point(puzzle.Location.X+puzzle.leftPuzzle[j].CoordinateY, puzzle.Location.Y + puzzle.Size.Height - 10); } puzzle.leftPuzzle[j].Location = point; } }
public void FindPath() { var textPuzzle = new Puzzle(new string[] { "~~~###~~~~~", "~~## #~####", "~##e ### #", "## X #", "# X # #", "### X### #", "~~# # #", "~## ## # ##", "~# s ##~", "~# ##~~", "~#######~~~", }); var boundry = textPuzzle.ToMap('#', 'X'); var start = textPuzzle.Where(x=>x=='s').First().Position; var end = textPuzzle.Where(x=>x=='e').First().Position; var result = PathFinder.Find(boundry, start, end); Assert.That(result, Is.Not.Null); Assert.That(result.ToString(), Is.EqualTo("LLUUUURUUL")); }
public void Box() { // Init var report = new TestReport(); var puz = new Puzzle(new String[] { "#####", "#...#", "#...#", "#...#", "#####", }); var stat = StaticAnalysis.Generate(puz); var dead = DeadMapAnalysis.FindDeadMap(stat); Assert.That(dead, Is.Not.Null); report.WriteLine(dead); Assert.That(report, Is.EqualTo(new TestReport( @"..... .XXX. .X.X. .XXX. ....." ))); }
public void CreateRelationship(CreatePropertyCommand createPropertyCommand, object sender, Puzzle.SideFX.Framework.Execution.ExecutionCancelEventArgs e) { IEngine engine = sender as IEngine; ISchemaService schemaService = engine.GetService<ISchemaService>(); IDatabaseService databaseService = engine.GetService<IDatabaseService>(); string className = createPropertyCommand.ClassName; string propertyName = createPropertyCommand.Name; string propertyType = createPropertyCommand.Type.ToString(); string columnName = createPropertyCommand.ColumnName; DbType columnType = DbType.Int32; //TODO: Get the column of the identity property string tableName = schemaService.GetTableForClass(className); switch (createPropertyCommand.Multiplicity) { case Multiplicity.OneToMany: case Multiplicity.OneToOne: //Add a property to the class schemaService.CreateProperty(className, propertyName, propertyType); //Set the nullability of the property schemaService.SetPropertyMetaData(className, propertyName, PropertyMetaData.Nullable, createPropertyCommand.Nullable); //Add a column to the table schemaService.CreateColumn(tableName, columnName, columnType); //Set the nullability of the column schemaService.SetColumnMetaData(tableName, columnName, ColumnMetaData.Nullable, createPropertyCommand.Nullable); //Map the property to the column in the schema schemaService.MapPropertyToColumn(className, propertyName, tableName, columnName); break; case Multiplicity.ManyToMany: //Add a property to the class schemaService.CreateListProperty(className, propertyName, propertyType); //Add a many-many table //schemaService.CreateTable(tableName, columnName, columnType); break; case Multiplicity.ManyToOne: //Add a property to the class schemaService.CreateListProperty(className, propertyName, propertyType); //Add a column to the table //schemaService.CreateColumn(tableName, columnName, columnType); break; } }
public UnityAction StartPuzzle(Puzzle puzzle) { Puzzle puzzleRefCopy = puzzle; return () => { if(currentPuzzle != null) currentPuzzle.SaveProgress(); el.ClearExampleList(); gc.SetPuzzle(puzzleRefCopy); //puzzleRefCopy.LoadProgress(); List<Board> testedExamples = puzzleRefCopy.testedExamples; foreach(Board board in testedExamples) { el.AddExample(board); } if(!el.ContainsExample(puzzleRefCopy.example1)) el.AddExample(puzzleRefCopy.example1); if(!el.ContainsExample(puzzleRefCopy.example2)) el.AddExample(puzzleRefCopy.example2); ssc.SwapTo(el.GetComponent<Animator>()); currentPuzzle = puzzleRefCopy; }; }
public object HandleCall(Puzzle.NAspect.Framework.MethodInvocation call) { Console.WriteLine("entering {0}", call.ValueSignature); object res = call.Proceed(); Console.WriteLine("exiting {0} and returning '{1}'", call.ValueSignature,res); return res; }
public static Puzzle Cleaned(Puzzle puzzle) { var t = Normalise(puzzle); var r = new Puzzle(t); foreach (var cell in t) { if (cell.State == puzzle.Definition.Wall) { var anyFloor = false; foreach (var dir in VectorInt2.Directions) { var po = cell.Position + dir; if (!puzzle.Contains(po)) continue; var o = t[po]; if (puzzle.Definition.AllFloors.Contains(o)) { anyFloor = true; break; } } if (!anyFloor) r[cell.Position] = puzzle.Definition.Void; } } return r; }
public IEnumerable<FoundWord> SolveWordSearch(Puzzle puzzle) { ushort puzzleSize = (ushort)puzzle.Board.GetLength(0); FoundWord tempWord; //Capital letters in ascii are 65 more than the index of the array e.g. A == char[0] == A.toascii - 65; List<FoundWord> returnValue = new List<FoundWord>(); //this is a two dimensional array of list of ushorts, each row represents the row of the board and each column // represents a letter in the alphabet, the array will be the location(s) of that letter in the row. List<ushort>[,] lookupTable = new List<ushort>[puzzleSize, 26]; //build the lookup table... for (ushort i = 0; i < puzzleSize; i++) { for (ushort temp = 0; temp < 26; temp++) lookupTable[i, temp] = new List<ushort>(); for (ushort j = 0; j < puzzleSize; j++) { lookupTable[i, getIndex(puzzle.Board[i, j])].Add(j); } } //now search through the words in the puzzle... for (ushort index = 0; index < puzzle.Words.Count; index++) { //first turn the string into a character array char[] arrSearch = puzzle.Words[index].ToCharArray(); ushort lookupIndex = getIndex(arrSearch[0]); bool wordFound = false; for (ushort rowSearch = 0; rowSearch < puzzleSize; rowSearch++) { if (wordFound) break; tempWord = new FoundWord(); tempWord.Word = puzzle.Words[index]; if (lookupTable[rowSearch, lookupIndex].Count != 0) { //here we look around the letter for the next letter in the word. foreach (ushort item in lookupTable[rowSearch, lookupIndex]) { if (checkWord(rowSearch, item, arrSearch, tempWord, puzzle, puzzleSize) != null) { returnValue.Add(tempWord); tempWord = null; wordFound = true; break; } } } } } return returnValue; }
public override void OnPuzzleCreate(Puzzle puzzle) { var lockedPlace = puzzle.GetPlace("LockedPlace"); puzzle.LockPlace(lockedPlace, "Boss"); lockedPlace.SpawnSingleMob("Mob1", 12001, 6); // Ghost Armor lockedPlace.CloseAllDoors(); }
public override void OnPrepare(Puzzle puzzle) { var propPlace = puzzle.NewPlace("PropPlace"); propPlace.ReservePlace(); if (Random(3) == 0) propPlace.ReserveDoors(); }
public override void OnPrepare(Puzzle puzzle) { var place = puzzle.NewPlace("Place"); place.ReservePlace(); place.ReserveDoors(); puzzle.Set("MonsterI", 1); }
public SecondaryObservationRoom(Puzzle owner) : base(owner) { defaultRight = Direction.Y; Type = TypeName; deletable = true; angles = new Point3(-90, 0, 0); }
public object CreateEntityProxy(Type baseType, Puzzle.NPersist.Framework.Persistence.IObjectFactory objectFactory, Puzzle.NPersist.Framework.Mapping.IClassMap classMap, object[] ctorArgs) { Type proxyType = aopEngine.CreateProxyType(baseType) ; object[] proxyArgs = aopEngine.AddStateToCtorParams(context,ctorArgs); return context.ObjectFactory.CreateInstance(proxyType,proxyArgs); }
public void Initialize() { var puzzle = new Puzzle(6, 5, new List<byte> {0, 1, 3}, new List<byte> {1, 2}, new List<byte> {3, 4}, false); var rules = new Rules { ProhibitedFields = {{0, 2}, {0, 4}, {5, 2}, {5, 4}} }; }
private void buttonRandom_Click(object sender, EventArgs e) { int size; int.TryParse(comboBoxPuzzleSize.Text, out size); var puz = new Puzzle(size); textBoxPuzzleInput2.Text = string.Join(",", puz.StartingNode.State); UpdateTextBoxColors(); }
private void AdjustHighlightColor(Puzzle puzzle) { GameObject obj = puzzle.gameObject; Component[] highlightMgrs = obj.GetComponentsInChildren<HighlightManager>(); foreach (HighlightManager highlighter in highlightMgrs) { highlighter.AdjustHighlightMaterial(highlightMaterial); } }
public void Initialize() { puzzle = new Puzzle(4, "1234", rows); }
public async Task <IActionResult> OnPostImportAsync() { // the BindProperty only binds the event ID, let's get the rest if (await _context.Events.Where((e) => e.ID == ImportEventID).FirstOrDefaultAsync() == null) { return(NotFound()); } // verify that we're an admin of the import event. current event administratorship is already validated. if (!await _context.EventAdmins.Where(ea => ea.Event.ID == ImportEventID && ea.Admin == LoggedInUser).AnyAsync()) { return(Forbid()); } var sourceEventAuthors = await _context.EventAuthors.Where((a) => a.Event.ID == ImportEventID).ToListAsync(); var sourcePuzzles = await _context.Puzzles.Where((p) => p.Event.ID == ImportEventID).ToListAsync(); // TODO: replace this with a checkbox and sufficient danger warnings about duplicate titles bool deletePuzzleIfPresent = true; using (var transaction = _context.Database.BeginTransaction(System.Data.IsolationLevel.Serializable)) { // Step 1: Make sure all authors exist foreach (var sourceEventAuthor in sourceEventAuthors) { var destEventAuthor = await _context.EventAuthors.Where((e) => e.Event == Event && e.Author == sourceEventAuthor.Author).FirstOrDefaultAsync(); if (destEventAuthor == null) { destEventAuthor = new EventAuthors(sourceEventAuthor); destEventAuthor.Event = Event; _context.EventAuthors.Add(destEventAuthor); } } // Step 2: Make sure all puzzles exist Dictionary <int, Puzzle> puzzleCloneMap = new Dictionary <int, Puzzle>(); foreach (var sourcePuzzle in sourcePuzzles) { // delete the puzzle if it exists if (deletePuzzleIfPresent) { foreach (Puzzle p in _context.Puzzles.Where((p) => p.Event == Event && p.Name == sourcePuzzle.Name)) { await PuzzleHelper.DeletePuzzleAsync(_context, p); } } var destPuzzle = new Puzzle(sourcePuzzle); destPuzzle.Event = Event; puzzleCloneMap[sourcePuzzle.ID] = destPuzzle; _context.Puzzles.Add(destPuzzle); } // Step 3: Save so that all our new objects have valid IDs await _context.SaveChangesAsync(); // Step 4: Ancillary tables referring to puzzles foreach (var sourcePuzzle in sourcePuzzles) { // PuzzleAuthors foreach (PuzzleAuthors sourcePuzzleAuthor in _context.PuzzleAuthors.Where((p) => p.Puzzle == sourcePuzzle)) { var destPuzzleAuthor = new PuzzleAuthors(sourcePuzzleAuthor); destPuzzleAuthor.Puzzle = puzzleCloneMap[sourcePuzzleAuthor.Puzzle.ID]; _context.PuzzleAuthors.Add(destPuzzleAuthor); } // Responses foreach (Response sourceResponse in _context.Responses.Where((r) => r.Puzzle == sourcePuzzle)) { var destResponse = new Response(sourceResponse); destResponse.Puzzle = puzzleCloneMap[sourceResponse.Puzzle.ID]; _context.Responses.Add(destResponse); } // Prerequisites foreach (Prerequisites sourcePrerequisite in _context.Prerequisites.Where((r) => r.Puzzle == sourcePuzzle)) { var destPrerequisite = new Prerequisites(sourcePrerequisite); destPrerequisite.Puzzle = puzzleCloneMap[sourcePrerequisite.Puzzle.ID]; destPrerequisite.Prerequisite = puzzleCloneMap[sourcePrerequisite.Prerequisite.ID]; _context.Prerequisites.Add(destPrerequisite); } // Hints foreach (Hint sourceHint in _context.Hints.Where((h) => h.Puzzle == sourcePuzzle)) { var destHint = new Hint(sourceHint); destHint.Puzzle = puzzleCloneMap[sourceHint.Puzzle.ID]; _context.Hints.Add(destHint); foreach (Team team in _context.Teams.Where(t => t.Event == Event)) { _context.HintStatePerTeam.Add(new HintStatePerTeam() { Hint = destHint, TeamID = team.ID }); } } // PuzzleStatePerTeam foreach (Team team in _context.Teams.Where(t => t.Event == Event)) { int newPuzzleId = puzzleCloneMap[sourcePuzzle.ID].ID; bool hasPuzzleStatePerTeam = await(from pspt in _context.PuzzleStatePerTeam where pspt.PuzzleID == newPuzzleId && pspt.TeamID == team.ID select pspt).AnyAsync(); if (!hasPuzzleStatePerTeam) { PuzzleStatePerTeam newPspt = new PuzzleStatePerTeam() { TeamID = team.ID, PuzzleID = newPuzzleId }; _context.PuzzleStatePerTeam.Add(newPspt); } } // TODO: ContentFiles } // Step 5: Final save and commit await _context.SaveChangesAsync(); transaction.Commit(); } return(RedirectToPage("./Index")); }
public bool GetValue(Puzzle puzzle, PuzzleState state) { return((bool)puzzle.GetElementValue(state, this)); }
public void ToggleValue(Puzzle puzzle, PuzzleState state) { SetValue(puzzle, state, !GetValue(puzzle, state)); }
public override bool CanWalk(Puzzle puzzle, PuzzleState state, PuzzleNode nodeA, PuzzleNode nodeB, bool forward) { return(GetValue(puzzle, state)); }
public override IEnumerator <object[]> GetEnumerator() { yield return(new object[] { Puzzle.For <Day06>(), }); }
public override string ToString(Puzzle puzzle, PuzzleState state) { return(base.ToString() + "\n" + (GetValue(puzzle, state) ? "Safe" : "Hole")); }
public void InstantiatePuzzleInGameWorld(Puzzle puzzleToInstantiate) { // Clear old puzzle if one exists foreach (Transform child in puzzleContainer.transform) { GameObject.Destroy(child.gameObject); } // Clear octagons list because we will fill it up with new octagons from the new puzzle OctagonsList.Clear(); // Allow user to click //actionController.GetComponent<ActionControllerScript>().EnableActions(); puzzleToInstantiate.Octagons = puzzleToInstantiate.Octagons.OrderBy(x => x.YCoordinate).ThenBy(x => x.XCoordinate).ToArray(); // Set columns and rows of grid container var dynamicGridRef = puzzleContainer.GetComponent <DynamicGridScript>(); dynamicGridRef.ResizeGrid(puzzleToInstantiate.Width, puzzleToInstantiate.Height); // Now go through and instantiate all octagons for this puzzle foreach (var octagon in puzzleToInstantiate.Octagons) { // Create appropriate game object type - Could be 3 exit, 4 exit, swap var octagonGameObject = GetAppropriateGameObjectOctagon(octagon.Type); var octagonGameObjectControllerScriptRef = octagonGameObject.GetComponent <OctagonControllerScript>(); octagonGameObjectControllerScriptRef.XCoordinate = octagon.XCoordinate; octagonGameObjectControllerScriptRef.YCoordinate = octagon.YCoordinate; octagonGameObjectControllerScriptRef.octagonType = octagon.Type; octagonGameObjectControllerScriptRef.OctagonId = currentOctagonNumber++; while (octagon.Rotations >= 8) { octagon.Rotations -= 8; } octagonGameObjectControllerScriptRef.CorrectRotation = octagon.Rotations * 45; octagonGameObjectControllerScriptRef.CorrectSprite = correctSprite; // Set the gameobject to the appropriate octagon action if (octagonGameObjectControllerScriptRef != null) { octagonGameObjectControllerScriptRef.octagonAction = octagon.Action; octagonGameObjectControllerScriptRef.octagonColor = octagon.Color; } // Set actual color of octagon if (octagon.Type != Enumerations.OctagonType.Empty) { SetVisibleColor(octagonGameObject, octagonGameObjectControllerScriptRef); } var positionToInstantiate = new Vector3(octagon.XCoordinate, octagon.YCoordinate, 0); var objectRotation = GetOctagonRotation(); // Might be trickyish, start rotating could be a 45x, x being the offset, up to 315 var gameObjectRef = (GameObject)Instantiate(octagonGameObject, positionToInstantiate, objectRotation); OctagonsList.Add(gameObjectRef); var gameObjectWidth = gameObjectRef.GetComponent <RectTransform>().rect.width; gameObjectRef.transform.SetParent(puzzleContainer.transform, false); gameObjectRef.transform.localScale = GetScale(gameObjectRef, puzzleToInstantiate.Width, gameObjectWidth); ShowAppropriateIcon(gameObjectRef); RemoveWalls(gameObjectRef, octagon); } // Now that all the octagons are in the game world, go through them and wire up their associated tiles foreach (var octagonGameObject in OctagonsList) { var octagonGameObjectScriptRef = octagonGameObject.GetComponent <OctagonControllerScript>(); if (octagonGameObjectScriptRef.octagonColor != Enumerations.OctagonColor.Default && octagonGameObjectScriptRef.octagonColor != Enumerations.OctagonColor.Locked) { octagonGameObjectScriptRef.linkedOctagons.AddRange(OctagonsList.Where(x => x.GetComponent <OctagonControllerScript>().octagonColor == octagonGameObjectScriptRef.octagonColor && x != octagonGameObject)); } } puzzleContainer.GetComponent <GridLayoutGroup>().enabled = true; UpdateText(); }
private void Awake() { puzzle = GameObject.Find("Scripts").GetComponent(typeof(Puzzle)) as Puzzle; }
private void Start() { _puzzle = _puzzlePiece.GetComponent <Puzzle>(); }
public override bool CanPushBall(Puzzle puzzle, PuzzleState state, PuzzleNode nodeA, PuzzleNode nodeB, bool forward) { return(forward); }
public override bool CanWalk(Puzzle puzzle, PuzzleState state, PuzzleNode nodeA, PuzzleNode nodeB, bool forward) { return(forward || (puzzle.GetItemsInNode <PuzzleBall> (state, nodeA).Count > 0)); }
// Use this for initialization void Start() { parent_puzzle_script = puzzle1.GetComponent <Puzzle> (); active = false; this.GetComponent <MeshRenderer> ().material.color = Color.red; }
// Update is called once per frame void Update() { //Check for collision with liftable objects RaycastHit hitInfo = new RaycastHit(); Ray ray = new Ray(transform.position, transform.rotation * Vector3.forward); bool objectFound = Physics.Raycast(ray, out hitInfo, distanceMax, layerMaskPickup); if (Input.GetButtonDown("Snap")) { snap = !snap; snapText.text = "<b>[X]Snap: </b>" + ((snap) ? "ON" : "OFF"); } if (Input.GetButtonDown("ShowPreview")) { showPreview = !showPreview; previewText.text = "<b>[V]Preview: </b>" + ((showPreview) ? "ON" : "OFF"); } if (carriedObjects.Count > 0 && currentPickupState != PickupState.interactObjectTargeted) { //Check distance mod float scrollDelta = Input.GetAxis("DistanceModification"); if (scrollDelta != 0) { distance = Mathf.Clamp(distance + scrollDelta, distanceMin, distanceMax); } //Set initial drop location dropCoords = new Vector3Int[] { Vector3Int.zero, Vector3Int.zero }; dropLocations = new Vector3[] { Vector3.zero, Vector3.zero }; canDropAtCoords = new bool[] { true, true }; showDrop = new bool[] { true, true }; if (objectFound && hitInfo.distance <= distance) { dropLocations[0] = hitInfo.point + (hitInfo.normal * 0.53f) - (snap ? Vector3.zero : carriedItem.centerLocalTransform); dropCoords[0] = placementGrid.WorldToCell(dropLocations[0]); Box box = hitInfo.transform.gameObject.GetComponent <Box>(); if (box != null) { dropCoords[1] = box.GetBoxOnTopOfMyStack().GetHighestCoordAlignedWithStack() + Vector3Int.up; canDropAtCoords[1] = Vector3.Distance(transform.position, placementGrid.CellToWorld(dropCoords[1])) < distanceMax; } else { placementPreviews[1].transform.position = placementPreviews[0].transform.position; placementPreviews[1].transform.rotation = placementPreviews[0].transform.rotation; canDropAtCoords[1] = false; showDrop[1] = false; } } else { dropLocations[0] = transform.position + (transform.rotation * (Vector3.forward * distance) - carriedItem.centerLocalTransform); dropCoords[0] = placementGrid.WorldToCell(dropLocations[0] + carriedItem.centerLocalTransform); canDropAtCoords[1] = false; showDrop[1] = false; } //Set pickup preview materials if (!canDropAtCoords[1] || dropCoords[0] == dropCoords[1]) { placementPreviews[0].SetPreview(carriedItem, PickupPreview.Prompt.r); showDrop[1] = false; } else { placementPreviews[0].SetPreview(carriedItem, PickupPreview.Prompt.r); placementPreviews[1].SetPreview(carriedItem, PickupPreview.Prompt.g); } //Convert back to world space for (int i = 0; i < dropCoords.Length; ++i) { if (i > 0 || snap) { dropLocations[i] = placementGrid.CellToWorld(dropCoords[i]); } bool obstructionNotDetected = !Physics.CheckBox(dropLocations[i] + new Vector3(0.5f, 0.55f, 0.5f), new Vector3(0.51f, 0.475f, 0.51f), Quaternion.identity, layerMaskObstructed); bool clippingNotDetected = !Physics.CheckBox(dropLocations[i] + new Vector3(0.5f, 0.55f, 0.5f), new Vector3(0.51f, 0.475f, 0.51f), Quaternion.identity, layerMaskHide); bool insideOfPuzzleBounds = true; if (carriedItem.puzzle != null) { insideOfPuzzleBounds = carriedItem.puzzle.IsInPuzzleBoundry(dropLocations[i]); } if (i == 0 && (!obstructionNotDetected || !clippingNotDetected)) { exception.FadeInText("NO SPACE"); } if (i == 0 && !insideOfPuzzleBounds) { exception.FadeInText("OUT OF BOUNDS"); } canDropAtCoords[i] = canDropAtCoords[i] && obstructionNotDetected && clippingNotDetected && insideOfPuzzleBounds; MaterialPropertyBlock properties = new MaterialPropertyBlock(); if (showDrop[i] && showPreview) { placementPreviews[i].gameObject.SetActive(true); prompt.FadeInText("<b>[R]</b>Place"); if (canDropAtCoords[i]) { placementPreviews[i].SetValid(true); //properties.SetColor("_Color", new Color(0.7f, 0.89f, 1f, 0.75f)); } else { prompt.FadeOutText(); placementPreviews[i].SetValid(false); //properties.SetColor("_Color", new Color(1f, 0.89f, 0.7f, 0.75f)); } placementPreviews[i].gameObject.transform.position = Vector3.Lerp(placementPreviews[i].gameObject.transform.position, dropLocations[i], 0.25f); placementPreviews[i].gameObject.transform.rotation = Quaternion.Lerp(placementPreviews[i].gameObject.transform.rotation, Quaternion.identity, 0.25f); //Graphics.DrawMesh(carriedItemMesh, dropLocations[i], Quaternion.identity, carriedItemMaterial, 0, GetComponent<Camera>(), 0, properties, false); } else { placementPreviews[i].gameObject.SetActive(false); } } if ((Input.GetButtonDown("Drop") || (Input.GetButtonDown("DropOnStack") && !canDropAtCoords[1])) && canDropAtCoords[0]) { DropObject(dropLocations[0], Quaternion.identity); } if (Input.GetButtonDown("DropOnStack") && canDropAtCoords[1]) { DropObject(dropLocations[1], Quaternion.identity); } } else { placementPreviews[0].gameObject.SetActive(false); placementPreviews[1].gameObject.SetActive(false); if (Input.GetButtonDown("Fire3")) { if (Player.singleton.myPickup.carriedObjects.Count > 0) //Don't reset anything if player is carrying boxes { return; } Puzzle[] puzzles = FindObjectsOfType <Puzzle>(); Puzzle activePuzzle = null; foreach (Puzzle puzzle in puzzles) { if (puzzle.IsInPuzzleBoundry(Player.singleton.transform.position) == true) { activePuzzle = puzzle; break; } } if (activePuzzle) { PuzzleSystem.ResetPuzzle(activePuzzle); } } } switch (currentPickupState) { case PickupState.noObjectTargeted: if (objectFound) { targetedObject = hitInfo.transform.gameObject; bool busy = true; PickupState nextState = PickupState.noObjectTargeted; switch (hitInfo.transform.tag) { case "Interactable": nextState = PickupState.interactObjectTargeted; targetedItemInteraction = targetedObject.GetComponent <Interaction>(); busy = targetedItemInteraction.IsBusy(); break; case "Liftable": nextState = PickupState.pickupObjectTargeted; targetedItemBox = targetedObject.GetComponent <Box>(); //HighlightGroup(); busy = false; break; default: break; } //Check the availability of the targeted object if (busy == false) { currentPickupState = nextState; //Debug.Log("Target found."); //Debug.Log("Targeted item: " + targetedObject.name); } } break; case PickupState.interactObjectTargeted: if (!targetedItemInteraction.IsBusy()) { RefreshText(); } if (InteractTargetLost(objectFound, hitInfo)) { //Object not targeted anymore LoseTarget(); } else { if (Input.GetButtonDown("Interact/Pickup")) { //Interact with object targetedItemInteraction.Interact(this); } } break; case PickupState.pickupObjectTargeted: if (PickupTargetLost(objectFound, hitInfo)) { //UnHighlightGroup(); LoseTarget(); } else { prompt.FadeInText("<b>[E]</b>Lift"); bool pickup = false; Box box = targetedItemBox; if (Input.GetButtonDown("Interact/Pickup")) { //Pickup object pickup = true; } if (Input.GetButtonDown("PickupOnStack")) { //Pickup object on top of a stack pickup = true; box = targetedItemBox.GetBoxOnTopOfMyStack(); } if (carriedObjects.Count == 0) //TODO Find way to show exceptions for picking up and placing seperately { if (box.isTooHeavy) { exception.FadeInText("TOO HEAVY"); } else if (carriedObjects.Count == carryObjectLimit) { exception.FadeInText("INVENTORY FULL"); } else if (pickup) { PickupObject(box); } } } //else if (box.GetBoxOnTopOfMe() != null) //{ // exception.FlashText("BOX BLOCKED", 2f); //} break; } //if Input.GetButtonDown("Pickup"){ //} }
public SolverNodeRootReverse(VectorInt2 playerBefore, VectorInt2 push, Bitmap crateMap, Bitmap moveMap, INodeEvaluator evaluator, Puzzle puzzle) : base(playerBefore, push, crateMap, moveMap, evaluator, puzzle) { }
public virtual string ToString(Puzzle puzzle, PuzzleState state) { return(ToString()); }
/* GENERATE HTML */ static object time(Puzzle puzzle) => Ut.NewArray <object>( puzzle.AverageTime == null ? "🕛" : "🕛🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚".Substring(((int)puzzle.AverageTime.Value) / 60 % 60 / 5 * 2, 2), " ", formatTime(puzzle.AverageTime));
public IEnumerator Move() { bool onceMore; int processCounter = 0; bool[] processed = new bool[_levelData.GetWaveEnemyCount()]; for (int i = 0; i < _levelData.GetWaveEnemyCount(); i++) { processed[i] = false; } do { onceMore = false; processCounter = 0; for (int i = 0; i < _enemyCounter; i++) { if (_enemies[i]._script != null && !_enemies[i]._script.GetGemScript().IsDead() && !processed[i]) { Figure figure = _enemies[i]._script; Gem ed = figure.GetGemScript(); Figure hFigure = GameManager.Instance.HeroManager.FindNearest(ed.GetGridPosition()); Gem hd = null; Directions attackDir = Directions.None; if (hFigure != null) { hd = hFigure.GetGemScript(); attackDir = GetAttackDir(hd.GetGridPosition(), ed.GetGridPosition()); if (attackDir != Directions.None) { /// attack adjacent hero yield return(StartCoroutine(GameManager.Instance.HeroManager.Attack(figure, hFigure, attackDir))); Debug.Log("Attack: " + i + "," + ed.IsDead() + "," + hd.IsDead()); yield return(StartCoroutine(Puzzle.CollapseField(attackDir, null))); } } if (attackDir == Directions.None) { if (figure.PowerCharge == 0 && figure.IsPowerAttackAvailable()) { yield return(StartCoroutine(figure.PowerAttack())); } else if (hd != null) { Vector2i last = ed.GetGridPosition(); yield return(StartCoroutine(figure.Move(hd))); if (ed.GetGridPosition() == last) { onceMore = true; continue; } } else { yield return(StartCoroutine(figure.PlayerAttack())); } } processCounter++; processed[i] = true; } } } while (onceMore && processCounter > 0); }
public PanelGameScreen(Puzzle panel, Point screenSize, GraphicsDevice device, Dictionary <string, Texture2D> TextureProvider, Dictionary <string, SpriteFont> FontProvider, ContentManager Content) : this(panel, false, screenSize, device, TextureProvider, FontProvider, Content) { }
void InitSlicerInfo(Puzzle puzzle) { // 퍼즐에 대한 정보 얻어오기 puzzleCubes = puzzle.cubes; puzzleSize = new int[3] { puzzle.zLen, puzzle.yLen, puzzle.xLen }; startLocation = puzzleCubes[0, 0, 0].transform.position; // 슬라이서의 종류(Red 또는 Blue)와 포지션에 따라 시작 위치와 이동 range를 정한다 if (slicerType == SLICER_TYPE.RED) { maxStep = puzzleSize[2] - 1; switch (slicerPosition) { case SLICER_POSITION.FRONT_LEFT: dir = -1; startLocation += cubeWidth * (new Vector3(.5f, -puzzleSize[1] * .5f + .5f, 1f)); break; case SLICER_POSITION.FRONT_RIGHT: dir = 1; startLocation += cubeWidth * (new Vector3(-puzzleSize[2] + .5f, -puzzleSize[1] * .5f + .5f, 1f)); break; case SLICER_POSITION.BACK_LEFT: dir = -1; startLocation += cubeWidth * (new Vector3(.5f, -puzzleSize[1] * .5f + .5f, -puzzleSize[0])); break; case SLICER_POSITION.BACK_RIGHT: dir = 1; startLocation += cubeWidth * (new Vector3(-puzzleSize[2] + .5f, -puzzleSize[1] * .5f + .5f, -puzzleSize[0])); break; } // 슬라이서 드래그 좌표의 min, max 설정 minClampValue = Mathf.Min(startLocation.x, startLocation.x + dir * maxStep * cubeWidth); maxClampValue = Mathf.Max(startLocation.x, startLocation.x + dir * maxStep * cubeWidth); } else if (slicerType == SLICER_TYPE.BLUE) { maxStep = puzzleSize[0] - 1; switch (slicerPosition) { case SLICER_POSITION.FRONT_LEFT: dir = -1; startLocation += cubeWidth * (new Vector3(1f, -puzzleSize[1] * .5f + .5f, .5f)); break; case SLICER_POSITION.FRONT_RIGHT: dir = -1; startLocation += cubeWidth * (new Vector3(-puzzleSize[2], -puzzleSize[1] * .5f + .5f, .5f)); break; case SLICER_POSITION.BACK_LEFT: dir = 1; startLocation += cubeWidth * (new Vector3(1f, -puzzleSize[1] * .5f + .5f, -puzzleSize[0] + .5f)); break; case SLICER_POSITION.BACK_RIGHT: startLocation += cubeWidth * (new Vector3(-puzzleSize[2], -puzzleSize[1] * .5f + .5f, -puzzleSize[0] + .5f)); dir = 1; break; } // 슬라이서 드래그 좌표의 min, max 설정 minClampValue = Mathf.Min(startLocation.z, startLocation.z + dir * maxStep * cubeWidth); maxClampValue = Mathf.Max(startLocation.z, startLocation.z + dir * maxStep * cubeWidth); } // 각 step 사이의 거리 계산 stepDistance = Mathf.Abs(minClampValue - maxClampValue) / maxStep; }
public PuzzleForPresentation(Puzzle question, bool answerTime, bool showAnswer) { pairs = question.Pairs; answer = question.AnswerPairs; InitializeComponent(); // if (answerTime) { var c1 = pairs.Where(p => !string.IsNullOrWhiteSpace(p.Key)).Select(p => p.Key).ToArray(); tableLayoutPanel1.RowCount = c1.Length; for (int i = 0; i < c1.Length; i++) { tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize)); } var j = 0; foreach (var s in c1) { //if (!string.IsNullOrWhiteSpace(s)) //{ Label lbl = new Label(); lbl.Text = s; lbl.AutoSize = true; if (!showAnswer && answerTime) { lbl.Click += LblKey_Click; lbl.Cursor = Cursors.Hand; } lbl.Tag = j; lbl.RightToLeft = RightToLeft.Yes; lbl.Padding = new Padding(10); tableLayoutPanel1.Controls.Add(lbl, 0, j); if (showAnswer) { var aLbl = new Label(); aLbl.Text = pairs[j].Value; aLbl.RightToLeft = RightToLeft.Yes; aLbl.Padding = new Padding(10); aLbl.AutoSize = true; aLbl.BackColor = BaseCodes.Utilities.Globals.Colors.TrueOption; if (!string.IsNullOrWhiteSpace(pairs[j].Value)) { tableLayoutPanel1.Controls.Add(aLbl, 1, j); } } j++; //} } var c2 = pairs.Select(p => p.Value).ToArray(); foreach (var s in c2) { if (!string.IsNullOrWhiteSpace(s)) { Label lbl = new Label(); lbl.Text = s; lbl.AutoSize = true; if (!showAnswer && answerTime) { lbl.Click += LblAns_Click; lbl.Cursor = Cursors.Hand; } lbl.BackColor = Color.White; lbl.Padding = new Padding(10); lbl.RightToLeft = RightToLeft.Yes; var pairInAnswer = answer?.Where(p => p.Value == s).ToArray(); if (pairInAnswer != null && pairInAnswer.Length > 0) { tableLayoutPanel1.Controls.Add(lbl, 1, pairs.IndexOf(pairInAnswer[0])); } else { flowLayoutPanel1.Controls.Add(lbl); } } } } }
public override void UpdateState(Puzzle puzzle, PuzzleState state, PuzzleNode node) { bool hasBall = puzzle.NodeHasItem <PuzzleBall> (state, node); node.TriggerValue(puzzle, state, hasBall); }
private void SpawnButtons() { TouchButton btnClose = new TouchButton(new Rectangle(), texClose, null); btnClose.Click += () => { AbortTracing(); SoundManager.PlayOnce(Sound.MenuOpen); ScreenManager.Instance.GoBack(); }; buttons.Add(btnClose); ToggleButton btnLike = new ToggleButton(new Rectangle(), texLike[1], texLike[0], null, FileStorageManager.IsPanelInFavourites(panel)); btnLike.Click += () => { // Add panel the list of favourite panels (or remove from it) if (btnLike.IsActivated) { FileStorageManager.AddPanelToFavourites(panel); } else { FileStorageManager.DeletePanelFromFavourites(panel); } SoundManager.PlayOnce(btnLike.IsActivated ? Sound.ButtonLike : Sound.ButtonUnlike); }; buttons.Add(btnLike); // When panel is standalone, it cannot have Next button if (!IsStandalonePanel) { TwoStateButton btnNext = new TwoStateButton(new Rectangle(), texDelete, texNext, null, null, null, false); btnNext.Click += () => { Action callback = null; callback = () => { AbortTracing(); Puzzle nextPanel = DI.Get <PanelGenerator>().GeneratePanel(); FileStorageManager.SaveCurrentPanel(nextPanel); LoadNewPanel(nextPanel); btnNext.StateActive = false; btnLike.Deactivate(); fade.FadeOutComplete -= callback; }; // Add panel to the list of last 10 discarded panels if (!btnNext.StateActive) { FileStorageManager.AddPanelToDiscardedList(panel); } SoundManager.PlayOnce(btnNext.StateActive ? Sound.ButtonNextSuccess : Sound.ButtonNext); fade.FadeOutComplete += callback; fade.Restart(); }; buttons.Add(btnNext); } UpdateButtonsPosition(); }
public void InitSlicer(Puzzle puzzle) { InitSlicerInfo(puzzle); SetSlicerToStartPosition(); }
public void TestPuzzleSolver() { RsaKey key = TestKeys.Default; PuzzleSolution expectedSolution = null; Puzzle puzzle = key.PubKey.GeneratePuzzle(ref expectedSolution); var parameters = new SolverParameters { FakePuzzleCount = 50, RealPuzzleCount = 10, ServerKey = key.PubKey }; SolverClientSession client = new SolverClientSession(parameters); SolverServerSession server = new SolverServerSession(key, parameters); var clientEscrow = new Key(); var serverEscrow = new Key(); var clientRedeem = new Key(); var escrow = CreateEscrowCoin(clientEscrow.PubKey, serverEscrow.PubKey, clientRedeem.PubKey); client.ConfigureEscrowedCoin(escrow, clientEscrow, clientRedeem); client.AcceptPuzzle(puzzle.PuzzleValue); RoundTrip(ref client, parameters); PuzzleValue[] puzzles = client.GeneratePuzzles(); RoundTrip(ref client, parameters); RoundTrip(ref puzzles); server.ConfigureEscrowedCoin(escrow, serverEscrow); var commitments = server.SolvePuzzles(puzzles); RoundTrip(ref server, parameters, key); RoundTrip(ref commitments); var revelation = client.Reveal(commitments); RoundTrip(ref client, parameters); RoundTrip(ref revelation); SolutionKey[] fakePuzzleKeys = server.CheckRevelation(revelation); RoundTrip(ref server, parameters, key); RoundTrip(ref fakePuzzleKeys); BlindFactor[] blindFactors = client.GetBlindFactors(fakePuzzleKeys); RoundTrip(ref client, parameters); RoundTrip(ref blindFactors); var offerInformation = server.CheckBlindedFactors(blindFactors, FeeRate); RoundTrip(ref server, parameters, key); var clientOfferSig = client.SignOffer(offerInformation); //Verify if the scripts are correctly created var fulfill = server.FulfillOffer(clientOfferSig, new Key().ScriptPubKey, FeeRate); var offerRedeem = client.CreateOfferRedeemTransaction(FeeRate, clientRedeem.ScriptPubKey); var offerTransaction = server.GetSignedOfferTransaction(); var offerCoin = offerTransaction.Transaction.Outputs.AsCoins().First(); TransactionBuilder txBuilder = new TransactionBuilder(); txBuilder.AddCoins(client.EscrowedCoin); Assert.True(txBuilder.Verify(offerTransaction.Transaction)); txBuilder = new TransactionBuilder(); txBuilder.AddCoins(offerCoin); Assert.True(txBuilder.Verify(fulfill.Transaction)); var offerRedeemTx = offerRedeem.ReSign(offerCoin); txBuilder = new TransactionBuilder(); txBuilder.AddCoins(offerCoin); Assert.True(txBuilder.Verify(offerRedeemTx)); //Check if can resign fulfill in case offer get malleated offerTransaction.Transaction.LockTime = new LockTime(1); offerCoin = offerTransaction.Transaction.Outputs.AsCoins().First(); fulfill.Transaction.Inputs[0].PrevOut = offerCoin.Outpoint; txBuilder = new TransactionBuilder(); txBuilder.Extensions.Add(new OfferBuilderExtension()); txBuilder.AddKeys(server.GetInternalState().FulfillKey); txBuilder.AddCoins(offerCoin); txBuilder.SignTransactionInPlace(fulfill.Transaction); Assert.True(txBuilder.Verify(fulfill.Transaction)); offerRedeemTx.Inputs[0].PrevOut = offerCoin.Outpoint; txBuilder = new TransactionBuilder(); txBuilder.Extensions.Add(new OfferBuilderExtension()); txBuilder.AddKeys(offerRedeem.Key); txBuilder.AddCoins(offerCoin); txBuilder.SignTransactionInPlace(offerRedeemTx); Assert.True(txBuilder.Verify(offerRedeemTx)); //////////////////////////////////////////////// client.CheckSolutions(fulfill.Transaction); RoundTrip(ref client, parameters); var solution = client.GetSolution(); RoundTrip(ref client, parameters); Assert.True(solution == expectedSolution); }
public void SetValue(Puzzle puzzle, PuzzleState state, bool value) { puzzle.SetElementValue(state, this, value); }
internal void PuzzleSelected(Puzzle puzzle) { _puzzle = puzzle; }
public PuzzleCompletedValidator(Puzzle puzzle) { _puzzle = puzzle; }
public override bool CanSee(Puzzle puzzle, PuzzleState state, PuzzleNode nodeA, PuzzleNode nodeB, bool forward) { return(false); }
private bool AppendCharsRecursively(Puzzle puzzle, int length, int currentIndex, EqualLengthWordSet wordSet, Cursor cursor, string selectedWord, DateTime startTime) { if (currentIndex == length) { if (wordSet.GetWordCount() == 0) { return(false); } puzzle.Words.Add(new WordData { Word = selectedWord ?? wordSet.GetFinalWord(), Position = cursor.GetWordHistory() }); return(true); } var tempWordSet = wordSet.Clone(); var tempSelectedWord = (string)selectedWord?.Clone(); var tempPuzzle = puzzle.Clone(); var tempCursor = new Cursor(cursor.Rows, cursor.Columns, cursor.CopyWordHistory(), null); tempCursor.SetPosition(cursor.X, cursor.Y); bool appendStatus; do { var didMove = tempCursor.MoveRandomly(); if (!didMove) { return(false); } appendStatus = TryChooseChar(tempPuzzle.PuzzleGrid, length, currentIndex, tempWordSet, tempCursor, ref tempSelectedWord); if (appendStatus == false) { tempCursor.Rollback(); tempPuzzle = puzzle; } else { var nextAppendStatus = AppendCharsRecursively(tempPuzzle, length, currentIndex + 1, tempWordSet, tempCursor, tempSelectedWord, startTime); if (nextAppendStatus == false) { tempCursor.Rollback(); tempWordSet.RollBack(); tempPuzzle = puzzle.Clone(); appendStatus = false; continue; } else { puzzle.PuzzleGrid = tempPuzzle.PuzzleGrid; cursor = tempCursor; return(nextAppendStatus); } } } while (!appendStatus); return(true); }