├── .gitignore ├── .vscode ├── launch.json └── tasks.json ├── LICENSE ├── README.md └── src └── Heuristic.PathfindingLab ├── Heuristic.PathfindingLab.sln └── Heuristic.PathfindingLab ├── .dockerignore ├── Controllers ├── EmbedController.cs ├── HomeController.cs └── PathfindingController.cs ├── Dockerfile ├── Helpers └── AlgorithmCore.cs ├── Heuristic.PathfindingLab.csproj ├── Models ├── AlgorithmProgressDetail.cs ├── AlgorithmSolution.cs ├── MapSettings.cs ├── Obstacle.cs ├── PathfindingRequestBody.cs ├── PathfindingSettings.cs └── ResponseBody.cs ├── Observers ├── AlgorithmObserver.cs └── AlgorithmObserverFactory.cs ├── Program.cs ├── Startup.cs ├── Views ├── Embed │ └── Index.cshtml ├── Home │ ├── Index.cshtml │ ├── _Algorithm.cshtml │ └── _Map.cshtml ├── Shared │ └── _Layout.cshtml ├── _ViewImports.cshtml └── _ViewStart.cshtml ├── appsettings.Development.json ├── appsettings.Production.json ├── appsettings.json ├── bundleconfig.json ├── package-lock.json ├── tsconfig.json └── wwwroot ├── css └── site.css ├── favicon.ico ├── images ├── assets.png └── tileGrass.png └── js ├── chart.ts ├── core.ts ├── layer.ts ├── site.js └── tile.ts /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # TypeScript 7 | 8 | src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/core.js 9 | src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/core.js.map 10 | 11 | src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/tile.js 12 | src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/tile.js.map 13 | 14 | src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/layer.js 15 | src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/layer.js.map 16 | 17 | src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/chart.js 18 | src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/chart.js.map 19 | 20 | # Minimized 21 | 22 | *.min.css 23 | *.min.js 24 | 25 | # User-specific files 26 | *.suo 27 | *.user 28 | *.userosscache 29 | *.sln.docstates 30 | 31 | # User-specific files (MonoDevelop/Xamarin Studio) 32 | *.userprefs 33 | 34 | # Build results 35 | [Dd]ebug/ 36 | [Dd]ebugPublic/ 37 | [Rr]elease/ 38 | [Rr]eleases/ 39 | x64/ 40 | x86/ 41 | bld/ 42 | [Bb]in/ 43 | [Oo]bj/ 44 | [Ll]og/ 45 | 46 | # Visual Studio 2015/2017 cache/options directory 47 | .vs/ 48 | # Uncomment if you have tasks that create the project's static files in wwwroot 49 | #wwwroot/ 50 | 51 | # Visual Studio 2017 auto generated files 52 | Generated\ Files/ 53 | 54 | # MSTest test Results 55 | [Tt]est[Rr]esult*/ 56 | [Bb]uild[Ll]og.* 57 | 58 | # NUNIT 59 | *.VisualState.xml 60 | TestResult.xml 61 | 62 | # Build Results of an ATL Project 63 | [Dd]ebugPS/ 64 | [Rr]eleasePS/ 65 | dlldata.c 66 | 67 | # Benchmark Results 68 | BenchmarkDotNet.Artifacts/ 69 | 70 | # .NET Core 71 | project.lock.json 72 | project.fragment.lock.json 73 | artifacts/ 74 | **/Properties/launchSettings.json 75 | 76 | # StyleCop 77 | StyleCopReport.xml 78 | 79 | # Files built by Visual Studio 80 | *_i.c 81 | *_p.c 82 | *_i.h 83 | *.ilk 84 | *.meta 85 | *.obj 86 | *.iobj 87 | *.pch 88 | *.pdb 89 | *.ipdb 90 | *.pgc 91 | *.pgd 92 | *.rsp 93 | *.sbr 94 | *.tlb 95 | *.tli 96 | *.tlh 97 | *.tmp 98 | *.tmp_proj 99 | *.log 100 | *.vspscc 101 | *.vssscc 102 | .builds 103 | *.pidb 104 | *.svclog 105 | *.scc 106 | 107 | # Chutzpah Test files 108 | _Chutzpah* 109 | 110 | # Visual C++ cache files 111 | ipch/ 112 | *.aps 113 | *.ncb 114 | *.opendb 115 | *.opensdf 116 | *.sdf 117 | *.cachefile 118 | *.VC.db 119 | *.VC.VC.opendb 120 | 121 | # Visual Studio profiler 122 | *.psess 123 | *.vsp 124 | *.vspx 125 | *.sap 126 | 127 | # Visual Studio Trace Files 128 | *.e2e 129 | 130 | # TFS 2012 Local Workspace 131 | $tf/ 132 | 133 | # Guidance Automation Toolkit 134 | *.gpState 135 | 136 | # ReSharper is a .NET coding add-in 137 | _ReSharper*/ 138 | *.[Rr]e[Ss]harper 139 | *.DotSettings.user 140 | 141 | # JustCode is a .NET coding add-in 142 | .JustCode 143 | 144 | # TeamCity is a build add-in 145 | _TeamCity* 146 | 147 | # DotCover is a Code Coverage Tool 148 | *.dotCover 149 | 150 | # AxoCover is a Code Coverage Tool 151 | .axoCover/* 152 | !.axoCover/settings.json 153 | 154 | # Visual Studio code coverage results 155 | *.coverage 156 | *.coveragexml 157 | 158 | # NCrunch 159 | _NCrunch_* 160 | .*crunch*.local.xml 161 | nCrunchTemp_* 162 | 163 | # MightyMoose 164 | *.mm.* 165 | AutoTest.Net/ 166 | 167 | # Web workbench (sass) 168 | .sass-cache/ 169 | 170 | # Installshield output folder 171 | [Ee]xpress/ 172 | 173 | # DocProject is a documentation generator add-in 174 | DocProject/buildhelp/ 175 | DocProject/Help/*.HxT 176 | DocProject/Help/*.HxC 177 | DocProject/Help/*.hhc 178 | DocProject/Help/*.hhk 179 | DocProject/Help/*.hhp 180 | DocProject/Help/Html2 181 | DocProject/Help/html 182 | 183 | # Click-Once directory 184 | publish/ 185 | 186 | # Publish Web Output 187 | *.[Pp]ublish.xml 188 | *.azurePubxml 189 | # Note: Comment the next line if you want to checkin your web deploy settings, 190 | # but database connection strings (with potential passwords) will be unencrypted 191 | *.pubxml 192 | *.publishproj 193 | 194 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 195 | # checkin your Azure Web App publish settings, but sensitive information contained 196 | # in these scripts will be unencrypted 197 | PublishScripts/ 198 | 199 | # NuGet Packages 200 | *.nupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/[Pp]ackages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/[Pp]ackages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/[Pp]ackages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | 275 | # Microsoft Fakes 276 | FakesAssemblies/ 277 | 278 | # GhostDoc plugin setting file 279 | *.GhostDoc.xml 280 | 281 | # Node.js Tools for Visual Studio 282 | .ntvs_analysis.dat 283 | node_modules/ 284 | 285 | # Visual Studio 6 build log 286 | *.plg 287 | 288 | # Visual Studio 6 workspace options file 289 | *.opt 290 | 291 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 292 | *.vbw 293 | 294 | # Visual Studio LightSwitch build output 295 | **/*.HTMLClient/GeneratedArtifacts 296 | **/*.DesktopClient/GeneratedArtifacts 297 | **/*.DesktopClient/ModelManifest.xml 298 | **/*.Server/GeneratedArtifacts 299 | **/*.Server/ModelManifest.xml 300 | _Pvt_Extensions 301 | 302 | # Paket dependency manager 303 | .paket/paket.exe 304 | paket-files/ 305 | 306 | # FAKE - F# Make 307 | .fake/ 308 | 309 | # JetBrains Rider 310 | .idea/ 311 | *.sln.iml 312 | 313 | # CodeRush 314 | .cr/ 315 | 316 | # Python Tools for Visual Studio (PTVS) 317 | __pycache__/ 318 | *.pyc 319 | 320 | # Cake - Uncomment if you are using it 321 | # tools/** 322 | # !tools/packages.config 323 | 324 | # Tabs Studio 325 | *.tss 326 | 327 | # Telerik's JustMock configuration file 328 | *.jmconfig 329 | 330 | # BizTalk build output 331 | *.btp.cs 332 | *.btm.cs 333 | *.odx.cs 334 | *.xsd.cs 335 | 336 | # OpenCover UI analysis results 337 | OpenCover/ 338 | 339 | # Azure Stream Analytics local run output 340 | ASALocalRun/ 341 | 342 | # MSBuild Binary and Structured Log 343 | *.binlog 344 | 345 | # NVidia Nsight GPU debugger configuration file 346 | *.nvuser 347 | 348 | # MFractors (Xamarin productivity tool) working folder 349 | .mfractor/ 350 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to find out which attributes exist for C# debugging 3 | // Use hover for the description of the existing attributes 4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (web)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/bin/Debug/netcoreapp2.0/Heuristic.PathfindingLab.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/src/Heuristic.PathfindingLab/Heuristic.PathfindingLab", 16 | "stopAtEntry": false, 17 | "internalConsoleOptions": "openOnSessionStart", 18 | "launchBrowser": { 19 | "enabled": true, 20 | "args": "${auto-detect-url}", 21 | "windows": { 22 | "command": "cmd.exe", 23 | "args": "/C start ${auto-detect-url}" 24 | }, 25 | "osx": { 26 | "command": "open" 27 | }, 28 | "linux": { 29 | "command": "xdg-open" 30 | } 31 | }, 32 | "env": { 33 | "ASPNETCORE_ENVIRONMENT": "Development" 34 | }, 35 | "sourceFileMap": { 36 | "/Views": "${workspaceFolder}/Views" 37 | } 38 | }, 39 | { 40 | "name": ".NET Core Attach", 41 | "type": "coreclr", 42 | "request": "attach", 43 | "processId": "${command:pickProcess}" 44 | } 45 | ] 46 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Heuristic.PathfindingLab.csproj" 11 | ], 12 | "problemMatcher": "$msCompile" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Robert Vandenberg Huang 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pathfinding Laboratory 2 | 3 | [![Docker Image Size](https://images.microbadger.com/badges/image/rvhuang/pathfinding-lab.svg)](https://microbadger.com/images/rvhuang/pathfinding-lab "Get your own image badge on microbadger.com") [![Docker Image Version](https://images.microbadger.com/badges/version/rvhuang/pathfinding-lab.svg)](https://microbadger.com/images/rvhuang/pathfinding-lab "Get your own version badge on microbadger.com") 4 | 5 | A playground where you can run, test and compare pathfinding algorithms and heuristic functions. 6 | 7 | Visit [the website](https://pathfinding-lab.codedwith.fun/) running on DigitalOcean and try it out. 8 | 9 | The project is written in ASP.NET Core MVC/Web API and TypeScript. The algorithm part of the project is based on [LINQ to A\*](https://github.com/rvhuang/linq-to-astar): a POC about pathfinding algorithms written in C# and used with LINQ expressions. 10 | 11 | ## Features 12 | 13 | * An editable, retro RPG-style map where you can place various obstacles, creating whatever maze you want. 14 | * Five algorithms and three heuristic functions available for playing with (more to be added). 15 | * Right-clicking on two positions to find a path (can be undone). 16 | * An overlay grid with animation to show expanded nodes and depths(levels). 17 | * A line chart that fully illustrates the evolution of Open List during the process. 18 | * A code snippet that demonstrates LINQ statement using LINQ to A*. 19 | 20 | ## Build the project 21 | 22 | ```sh 23 | cd src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/ 24 | npm i -s d3 25 | npm i -s @types/d3 26 | tsc -p tsconfig.json 27 | dotnet build Heuristic.PathfindingLab.csproj 28 | ``` 29 | 30 | ## Build Docker image 31 | 32 | ```sh 33 | cd src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/ 34 | docker build -t pathfinding-lab . 35 | ``` 36 | 37 | ## Run Dockerized instance 38 | 39 | ```sh 40 | docker pull rvhuang/pathfinding-lab:latest 41 | docker run -d -p 8080:80 pathfinding-lab:latest --name p-lab 42 | ``` 43 | 44 | ## License 45 | 46 | Copyright © Robert Vandenberg Huang 47 | 48 | The project is licensed under the MIT license. Feel free to copy, modify and use it in your computer science homework (grades not guaranteed). 49 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27703.2035 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Heuristic.PathfindingLab", "Heuristic.PathfindingLab\Heuristic.PathfindingLab.csproj", "{54C47D90-D04A-4890-9FC7-CEC736205B93}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {54C47D90-D04A-4890-9FC7-CEC736205B93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {54C47D90-D04A-4890-9FC7-CEC736205B93}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {54C47D90-D04A-4890-9FC7-CEC736205B93}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {54C47D90-D04A-4890-9FC7-CEC736205B93}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {55ED30D1-0E65-48A4-981B-F47B668FF5E0} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/.dockerignore: -------------------------------------------------------------------------------- 1 | bin\ 2 | obj\ -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Controllers/EmbedController.cs: -------------------------------------------------------------------------------- 1 | using Heuristic.PathfindingLab.Models; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Primitives; 4 | 5 | namespace Heuristic.PathfindingLab.Controllers 6 | { 7 | public class EmbedController : Controller 8 | { 9 | private readonly static StringValues iframe = new StringValues(new [] 10 | { 11 | "connect-src https:", 12 | "default-src 'self' 'unsafe-inline' 'unsafe-eval' https:", 13 | "img-src https: data:", "media-src https: blob:" 14 | }); 15 | 16 | [HttpGet] 17 | public IActionResult Index([FromQuery]int w = MapSettings.DefaultMapWidth, [FromQuery]int h = MapSettings.DefaultMapHeight) 18 | { 19 | #if !DEBUG 20 | Response.Headers.Add("Content-Security-Policy", string.Join(";", iframe)); 21 | #endif 22 | Response.Headers.Add("X-Content-Type-Options", "nosniff"); 23 | Response.Headers.Add("X-XSS-Protection", "1; mode=block"); 24 | 25 | return View(new MapSettings(w, h)); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using Heuristic.PathfindingLab.Models; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Net.Http.Headers; 4 | using System; 5 | using System.Linq; 6 | using System.Net.Http; 7 | using System.Threading.Tasks; 8 | 9 | namespace Heuristic.PathfindingLab.Controllers 10 | { 11 | public class HomeController : Controller 12 | { 13 | private readonly static string[] mimes = new[] { "application/json", "text/json", "text/x-json" }; 14 | private readonly static string[] mobiles = new[] { "iPhone", "Android" }; 15 | private readonly static string[] touches = new[] { "iPhone", "Android", "iPad" }; 16 | private readonly static HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(4) }; 17 | 18 | [HttpGet] 19 | public IActionResult Index([FromQuery]int w = MapSettings.DefaultMapWidth, [FromQuery]int h = MapSettings.DefaultMapHeight) 20 | { 21 | var userAgent = Request.Headers[HeaderNames.UserAgent].FirstOrDefault(); 22 | 23 | if (!Request.Query.ContainsKey("w") && !string.IsNullOrWhiteSpace(userAgent) && mobiles.Any(userAgent.Contains)) 24 | { 25 | return View(new MapSettings(MapSettings.MinMapWidth, h) { IsSmartDevice = touches.Any(userAgent.Contains) }); 26 | } 27 | else 28 | { 29 | return View(new MapSettings(w, h) { IsSmartDevice = touches.Any(userAgent.Contains) }); 30 | } 31 | } 32 | 33 | [HttpGet] 34 | public async Task Load(string from) 35 | { 36 | var uri = default(Uri); 37 | 38 | if (!Uri.TryCreate(from, UriKind.Absolute, out uri) || uri.Scheme != Uri.UriSchemeHttp || uri.Scheme != Uri.UriSchemeHttps) 39 | return View(nameof(Index), new MapSettings()); 40 | try 41 | { 42 | using (var response = await client.GetAsync(from)) 43 | if (mimes.Any(response.Content.Headers.ContentType.MediaType.StartsWith)) 44 | return View(nameof(Index), await response.Content.ReadAsAsync()); 45 | } 46 | catch 47 | { 48 | return View(nameof(Index), new MapSettings()); // TODO 49 | } 50 | return View(nameof(Index), new MapSettings()); 51 | } 52 | 53 | [HttpGet] 54 | public IActionResult Map([FromQuery]int w = MapSettings.DefaultMapWidth, [FromQuery]int h = MapSettings.DefaultMapHeight) 55 | { 56 | Response.ContentType = "image/svg+xml"; 57 | 58 | return PartialView("_Map", new MapSettings(w, h)); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Controllers/PathfindingController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using System; 3 | using System.Linq; 4 | using System.Net; 5 | 6 | namespace Heuristic.PathfindingLab.Controllers 7 | { 8 | using Linq; 9 | using PathfindingLab.Models; 10 | using PathfindingLab.Helpers; 11 | 12 | [Produces("application/json")] 13 | [Route("api/[controller]")] 14 | public class PathfindingController : ControllerBase 15 | { 16 | [HttpPost] 17 | public ResponseBody Find([FromBody]PathfindingRequestBody body) 18 | { 19 | var settings = body.ToSettings(); 20 | 21 | if (!PathfindingSettings.CheckIfValid(settings)) 22 | { 23 | Response.StatusCode = (int)HttpStatusCode.BadRequest; 24 | return new ResponseBody() { Errors = new[] { ResponseError.InvalidFromAndGoalSettings } }; 25 | } 26 | try 27 | { 28 | var result = AlgorithmCore.Find(settings, body.Map); 29 | 30 | return new ResponseBody() { Data = result }; 31 | } 32 | catch (InvalidOperationException) 33 | { 34 | Response.StatusCode = (int)HttpStatusCode.BadRequest; 35 | return new ResponseBody() { }; 36 | } 37 | catch (Exception) 38 | { 39 | Response.StatusCode = (int)HttpStatusCode.InternalServerError; 40 | return new ResponseBody() { }; 41 | } 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:alpine AS typescript 2 | WORKDIR /app 3 | COPY . ./ 4 | RUN npm install typescript -g 5 | RUN npm i -s d3 6 | RUN npm i -s @types/d3 7 | RUN tsc -p tsconfig.json 8 | 9 | FROM microsoft/dotnet:sdk AS build-env 10 | WORKDIR /app 11 | 12 | # Copy csproj and restore as distinct layers 13 | COPY --from=typescript /app/*.csproj ./ 14 | RUN dotnet restore 15 | 16 | # Copy everything else and build 17 | COPY --from=typescript /app ./ 18 | RUN dotnet restore 19 | RUN dotnet bundle 20 | RUN dotnet publish -c Release -o out 21 | 22 | # Build runtime image 23 | FROM microsoft/dotnet:aspnetcore-runtime 24 | WORKDIR /app 25 | COPY --from=build-env /app/out . 26 | ENTRYPOINT ["dotnet", "Heuristic.PathfindingLab.dll"] -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Helpers/AlgorithmCore.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | 6 | namespace Heuristic.PathfindingLab.Helpers 7 | { 8 | using Linq; 9 | using PathfindingLab.Models; 10 | using PathfindingLab.Observers; 11 | 12 | public static class AlgorithmCore 13 | { 14 | public static AlgorithmSolution Find(PathfindingSettings settings, int[][] map) 15 | { 16 | return Find(settings, map.Max(row => row.Length), map.Length, GetAllObstacles(map)); 17 | } 18 | 19 | public static AlgorithmSolution Find(PathfindingSettings settings, int mapWidth, int mapHeight, IEnumerable obstacles) 20 | { 21 | var observer = new AlgorithmObserverFactory(); 22 | var start = new Point(settings.FromX, settings.FromY); 23 | var goal = new Point(settings.GoalX, settings.GoalY); 24 | var boundary = new Rectangle(0, 0, mapWidth, mapHeight); 25 | var unit = 1; 26 | var queryable = HeuristicSearch.Use(settings.Algorithm, start, goal, (step, i) => step.GetFourDirections(unit), null, observer); 27 | var solution = ApplyHeuristicFunction(queryable.Except(obstacles).Where(boundary.Contains), settings.Heuristics); 28 | 29 | return new AlgorithmSolution() 30 | { 31 | Details = observer.Details, 32 | Solution = solution.ToArray(), 33 | NumberOfEstimatedNodes = observer.Estimated.Count, 34 | }; 35 | } 36 | 37 | public static HeuristicSearchBase ApplyHeuristicFunction(HeuristicSearchBase queryable, string[] heuristicNames) 38 | { 39 | var orderBy = default(HeuristicSearchOrderBy); 40 | var goal = queryable.To; 41 | 42 | switch (heuristicNames.FirstOrDefault()) 43 | { 44 | case nameof(PointExtensions.GetChebyshevDistance): 45 | orderBy = queryable.OrderBy(p => p.GetChebyshevDistance(goal)); 46 | break; 47 | 48 | case nameof(PointExtensions.GetEuclideanDistance): 49 | orderBy = queryable.OrderBy(p => p.GetEuclideanDistance(goal)); 50 | break; 51 | 52 | case nameof(PointExtensions.GetManhattanDistance): 53 | orderBy = queryable.OrderBy(p => p.GetManhattanDistance(goal)); 54 | break; 55 | 56 | default: 57 | return queryable; 58 | } 59 | foreach (var heuristicName in heuristicNames.Skip(1).Take(2)) 60 | { 61 | switch (heuristicName) 62 | { 63 | case nameof(PointExtensions.GetChebyshevDistance): 64 | orderBy = orderBy.ThenBy(p => p.GetChebyshevDistance(goal)); 65 | break; 66 | 67 | case nameof(PointExtensions.GetEuclideanDistance): 68 | orderBy = orderBy.ThenBy(p => p.GetEuclideanDistance(goal)); 69 | break; 70 | 71 | case nameof(PointExtensions.GetManhattanDistance): 72 | orderBy = orderBy.ThenBy(p => p.GetManhattanDistance(goal)); 73 | break; 74 | 75 | default: 76 | continue; 77 | } 78 | } 79 | return orderBy; 80 | } 81 | 82 | public static IEnumerable GetAllObstacles(int[][] map) 83 | { 84 | for (var y = 0; y < map.Length; y++) 85 | for (var x = 0; x < map[y].Length; x++) 86 | if (map[y][x] < 0) 87 | yield return new Point(x, y); 88 | } 89 | } 90 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Heuristic.PathfindingLab.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp2.2 5 | 3.2 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Models/AlgorithmProgressDetail.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Drawing; 3 | 4 | namespace Heuristic.PathfindingLab.Models 5 | { 6 | public class AlgorithmProgressDetail 7 | { 8 | public int Level { get; set; } 9 | 10 | public Point Step { get; set; } 11 | 12 | public Point[] Candidates { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Models/AlgorithmSolution.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Drawing; 3 | 4 | namespace Heuristic.PathfindingLab.Models 5 | { 6 | public class AlgorithmSolution 7 | { 8 | public IList Solution { get; set; } 9 | 10 | public IList Details { get; set; } 11 | 12 | public int NumberOfEstimatedNodes { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Models/MapSettings.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Drawing; 5 | using System.Linq; 6 | 7 | namespace Heuristic.PathfindingLab.Models 8 | { 9 | public class MapSettings 10 | { 11 | public const int DefaultMapWidth = 40; 12 | public const int DefaultMapHeight = 20; 13 | public const int MinMapWidth = 10; 14 | public const int MinMapHeight = 10; 15 | 16 | private int _width; 17 | private int _height; 18 | 19 | private IReadOnlyList _obstacles; 20 | private IReadOnlyList _settings; 21 | 22 | [JsonProperty(Required = Required.Default)] 23 | public IReadOnlyList Obstacles { get => _obstacles; set => _obstacles = value ?? Array.Empty(); } 24 | 25 | [JsonProperty(Required = Required.Always)] 26 | public int Width { get => _width; set => Math.Max(MinMapWidth, value); } 27 | 28 | [JsonProperty(Required = Required.Always)] 29 | public int Height { get => _height; set => Math.Max(MinMapHeight, value); } 30 | 31 | [JsonIgnore] 32 | public bool IsSmartDevice { get; set; } 33 | 34 | public MapSettings() 35 | { 36 | _width = DefaultMapWidth; 37 | _height = DefaultMapHeight; 38 | _obstacles = Array.Empty(); 39 | _settings = Array.Empty(); 40 | } 41 | 42 | public MapSettings(int mapWidth, int mapHeight) 43 | { 44 | _width = Math.Max(MinMapWidth, mapWidth); 45 | _height = Math.Max(MinMapHeight, mapHeight); 46 | _obstacles = Array.Empty(); 47 | _settings = Array.Empty(); 48 | } 49 | 50 | public bool CheckIfObstacleValid(Obstacle o) 51 | { 52 | return Obstacle.CheckIfValid(o) && o.X < Width && o.Y < Height; 53 | } 54 | 55 | public bool CheckIfPathfindingSettingsValid(PathfindingSettings s) 56 | { 57 | return PathfindingSettings.CheckIfValid(s) && _obstacles.Where(CheckIfObstacleValid).All(o => o.CheckIfPathfindingSettingsValid(s)); 58 | } 59 | 60 | public IEnumerable GetObstaclePoints() 61 | { 62 | foreach (var obstacle in Obstacles) 63 | if (Obstacle.CheckIfValid(obstacle)) 64 | yield return new Point(obstacle.X, obstacle.Y); 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Models/Obstacle.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Heuristic.PathfindingLab.Models 4 | { 5 | public class Obstacle 6 | { 7 | [JsonProperty(Required = Required.Always)] 8 | public int Value { get; set; } 9 | 10 | [JsonProperty(Required = Required.Always)] 11 | public int X { get; set; } 12 | 13 | [JsonProperty(Required = Required.Always)] 14 | public int Y { get; set; } 15 | 16 | public bool CheckIfPathfindingSettingsValid(PathfindingSettings s) 17 | { 18 | return s != null && s.FromX != X && s.FromY != Y && s.GoalX != X && s.GoalY != Y; 19 | } 20 | 21 | public static bool CheckIfValid(Obstacle o) 22 | { 23 | return o != null && o.Value > 0 && o.X >= 0 && o.Y >= 0; 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Models/PathfindingRequestBody.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Heuristic.PathfindingLab.Models 4 | { 5 | public class PathfindingRequestBody 6 | { 7 | [JsonProperty(Required = Required.Always)] 8 | public int FromX { get; set; } 9 | 10 | [JsonProperty(Required = Required.Always)] 11 | public int FromY { get; set; } 12 | 13 | [JsonProperty(Required = Required.Always)] 14 | public int GoalX { get; set; } 15 | 16 | [JsonProperty(Required = Required.Always)] 17 | public int GoalY { get; set; } 18 | 19 | [JsonProperty(Required = Required.Always)] 20 | public int[][] Map { get; set; } 21 | 22 | [JsonProperty(Required = Required.Always)] 23 | public string[] Heuristics { get; set; } 24 | 25 | [JsonProperty(Required = Required.Always)] 26 | public string Algorithm { get; set; } 27 | 28 | public PathfindingSettings ToSettings() 29 | { 30 | return new PathfindingSettings() 31 | { 32 | Algorithm = Algorithm, 33 | FromX = FromX, 34 | FromY = FromY, 35 | GoalX = GoalX, 36 | GoalY = GoalY, 37 | Heuristics = Heuristics 38 | }; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Models/PathfindingSettings.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Heuristic.PathfindingLab.Models 4 | { 5 | using Linq; 6 | 7 | public class PathfindingSettings 8 | { 9 | [JsonProperty(Required = Required.Always)] 10 | public int FromX { get; set; } 11 | 12 | [JsonProperty(Required = Required.Always)] 13 | public int FromY { get; set; } 14 | 15 | [JsonProperty(Required = Required.Always)] 16 | public int GoalX { get; set; } 17 | 18 | [JsonProperty(Required = Required.Always)] 19 | public int GoalY { get; set; } 20 | 21 | [JsonProperty(Required = Required.Default)] 22 | public string[] Heuristics { get; set; } 23 | 24 | [JsonProperty(Required = Required.Always)] 25 | public string Algorithm { get; set; } 26 | 27 | public static bool CheckIfValid(PathfindingSettings s) 28 | { 29 | if (s == null) return false; 30 | if (s.FromX < 0 || s.FromY < 0) return false; 31 | if (s.FromX == s.GoalX && s.FromY == s.GoalY) return false; 32 | 33 | return HeuristicSearch.RegisteredAlgorithms.ContainsKey(s.Algorithm); 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Models/ResponseBody.cs: -------------------------------------------------------------------------------- 1 | namespace Heuristic.PathfindingLab.Models 2 | { 3 | public class ResponseBody where T : class 4 | { 5 | public T Data { get; set; } 6 | 7 | public ResponseError[] Errors { get; set; } 8 | } 9 | 10 | public class ResponseError 11 | { 12 | public static ResponseError InvalidFromAndGoalSettings => new ResponseError() { Code = 1, Message = "Invalid from And goal settings." }; 13 | 14 | public int Code { get; set; } 15 | 16 | public string Message { get; set; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Observers/AlgorithmObserver.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Drawing; 3 | using System.Linq; 4 | 5 | namespace Heuristic.PathfindingLab.Observers 6 | { 7 | using Linq.Algorithms; 8 | using PathfindingLab.Models; 9 | 10 | public class AlgorithmObserver : IProgress> 11 | { 12 | public Action Callback { get; set; } 13 | 14 | public void Report(AlgorithmState p) 15 | { 16 | Callback(new AlgorithmProgressDetail() 17 | { 18 | Level = p.Node != null ? p.Node.Level : -1, 19 | Step = p.Node != null ? p.Node.Step : new Point(-1, -1), 20 | Candidates = p.Candidates.Select(c => c.Step).ToArray() 21 | }); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Observers/AlgorithmObserverFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.ObjectModel; 4 | using System.Drawing; 5 | 6 | namespace Heuristic.PathfindingLab.Observers 7 | { 8 | using Linq; 9 | using Linq.Algorithms; 10 | using PathfindingLab.Models; 11 | 12 | public class AlgorithmObserverFactory : IAlgorithmObserverFactory 13 | { 14 | public ObservableCollection Details { get; private set; } 15 | 16 | public ISet Estimated { get; private set; } 17 | 18 | public AlgorithmObserverFactory() 19 | { 20 | Details = new ObservableCollection(); 21 | Estimated = new HashSet(); 22 | } 23 | 24 | IProgress> IAlgorithmObserverFactory.Create(HeuristicSearchBase source) 25 | { 26 | var progress = new AlgorithmObserver(); 27 | 28 | Details.Clear(); 29 | progress.Callback = ProgressCallback; 30 | 31 | return progress; 32 | } 33 | 34 | private void ProgressCallback(AlgorithmProgressDetail detail) 35 | { 36 | Details.Add(detail); 37 | Estimated.UnionWith(detail.Candidates); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore; 2 | using Microsoft.AspNetCore.Hosting; 3 | 4 | namespace Heuristic.PathfindingLab 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | BuildWebHost(args).Run(); 11 | } 12 | 13 | public static IWebHost BuildWebHost(string[] args) => 14 | WebHost.CreateDefaultBuilder(args) 15 | .UseStartup() 16 | .Build(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Newtonsoft.Json; 6 | using Newtonsoft.Json.Serialization; 7 | using System; 8 | using System.Drawing; 9 | 10 | namespace Heuristic.PathfindingLab 11 | { 12 | public class Startup 13 | { 14 | public Startup(IConfiguration configuration) 15 | { 16 | Configuration = configuration; 17 | } 18 | 19 | public IConfiguration Configuration { get; } 20 | 21 | // This method gets called by the runtime. Use this method to add services to the container. 22 | public void ConfigureServices(IServiceCollection services) 23 | { 24 | services.AddMvc().AddJsonOptions(options => { 25 | // https://www.c-sharpcorner.com/blogs/serialization-in-web-api-with-asp-net-core 26 | options.SerializerSettings.ContractResolver = new DefaultContractResolver() 27 | { 28 | NamingStrategy = new CamelCaseNamingStrategy() 29 | }; 30 | options.SerializerSettings.Converters.Add(new PointJsonConverter()); 31 | options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; 32 | }); 33 | } 34 | 35 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 36 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 37 | { 38 | if (env.IsDevelopment()) 39 | { 40 | app.UseBrowserLink(); 41 | app.UseDeveloperExceptionPage(); 42 | } 43 | #if RELEASE 44 | app.UseHsts(); 45 | app.UseHttpsRedirection(); 46 | #endif 47 | app.UseStaticFiles(); 48 | app.UseMvc(routes => 49 | { 50 | routes.MapRoute( 51 | name: "default", 52 | template: "{controller=Home}/{action=Index}/{id?}"); 53 | }); 54 | } 55 | } 56 | 57 | public class PointJsonConverter : JsonConverter 58 | { 59 | public override bool CanConvert(Type objectType) 60 | { 61 | return objectType == typeof(Point); 62 | } 63 | 64 | public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 65 | { 66 | var x = 0; 67 | var y = 0; 68 | 69 | while (reader.Read()) 70 | { 71 | if (reader.TokenType != JsonToken.PropertyName) 72 | break; 73 | 74 | var propertyName = (string)reader.Value; 75 | 76 | if (!reader.Read()) 77 | continue; 78 | 79 | if (string.Equals(propertyName, "x")) 80 | x = (int)reader.Value; 81 | 82 | if (string.Equals(propertyName, "y")) 83 | y = (int)reader.Value; 84 | } 85 | return new Point(x, y); 86 | } 87 | 88 | public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 89 | { 90 | var point = (Point)value; 91 | 92 | writer.WriteStartObject(); 93 | writer.WritePropertyName("x"); 94 | writer.WriteValue(point.X); 95 | writer.WritePropertyName("y"); 96 | writer.WriteValue(point.Y); 97 | writer.WriteEndObject(); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Views/Embed/Index.cshtml: -------------------------------------------------------------------------------- 1 | @using Heuristic.Linq 2 | @using Heuristic.PathfindingLab.Models 3 | @using Microsoft.AspNetCore.Http 4 | @using Microsoft.AspNetCore.Http.Extensions 5 | @model MapSettings 6 | @section Styles { 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | } 15 |
16 |
17 |
@await Html.PartialAsync("../Home/_Map", Model)
18 |
19 |
20 |
21 |
22 |
23 |
24 | 27 | 30 | 33 | 34 | 35 | 36 |
37 | @await Html.PartialAsync("../Home/_Algorithm") 38 | @if (Model.IsSmartDevice) 39 | { 40 | 43 | } 44 |
45 |
46 |
47 |
48 | 55 | @section Scripts { 56 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Views/Home/Index.cshtml: -------------------------------------------------------------------------------- 1 | @using Heuristic.Linq 2 | @using Heuristic.PathfindingLab.Controllers 3 | @using Heuristic.PathfindingLab.Models 4 | @model MapSettings 5 | @section Styles { 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | } 14 |
15 |
16 |
@await Html.PartialAsync("_Map", Model)
17 |
18 |
19 |
20 |
21 |
22 |
23 | 26 | 29 | 32 | 35 | 38 |
39 | @await Html.PartialAsync("_Algorithm") 40 | @if (Model.IsSmartDevice) 41 | { 42 | 45 | } 46 | else 47 | { 48 | Left click to place obstacles, right click on two positions to get a path. 49 | } 50 |
51 |
52 |
53 |
54 |
55 | 56 | 57 | 58 | 59 |

60 | Current node: 
61 | Is a part of final solution? 
62 | Number of nodes on open list: 
63 | Number of stale nodes on open list: 
64 |
65 |
66 |

67 |

68 | Tip: you can change the map size by attaching w and h parameters to the query string. The default size is @(MapSettings.DefaultMapWidth)x@(MapSettings.DefaultMapHeight) and the minimum size is @(MapSettings.MinMapWidth)x@(MapSettings.MinMapHeight). 69 |

70 |
71 |
72 |
73 |
74 |
75 |
76 | 77 | 78 | 79 | 80 | 81 | 86 | 87 |
88 |
89 |
// Equivalent LINQ expression using SelectMany() will be shown here.
 90 | 
 91 | 
 92 | 
 93 | 
 94 | 
 95 |                                     
96 |
97 |
98 |
// Equivalent LINQ expression using Except() will be shown here.
 99 | 
100 | 
101 | 
102 | 
103 | 
104 |                                     
105 |
106 |
107 |
// Equivalent LINQ expression using Where() clause will be shown here.
108 | 
109 | 
110 | 
111 | 
112 | 
113 |                                 
114 |
115 |
116 |
117 |
118 | 119 | 148 | 149 | 168 | 175 | @section Scripts { 176 | 177 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | } 195 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Views/Home/_Algorithm.cshtml: -------------------------------------------------------------------------------- 1 | @using Heuristic.Linq 2 | @using Microsoft.AspNetCore.Http 3 | @using Microsoft.AspNetCore.Http.Extensions 4 | @{ 5 | const int assetSize = 16; 6 | } 7 |
8 |
9 | 12 | 90 |
91 |
92 |
93 |
94 | 95 | 101 |
102 |
103 |
104 | 105 | 106 | 107 |
108 | 109 | 110 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Views/Home/_Map.cshtml: -------------------------------------------------------------------------------- 1 | @using Microsoft.AspNetCore.Http 2 | @using Microsoft.AspNetCore.Http.Extensions 3 | @using Heuristic.PathfindingLab.Models 4 | @model MapSettings 5 | @{ 6 | const int assetSize = 16; // pixel 7 | const int baseOffsetX = 5 * assetSize + 5; 8 | const int baseOffsetY = 19 * assetSize + 19; 9 | } 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 | @using Heuristic.PathfindingLab.Controllers 2 | @using Microsoft.AspNetCore.Http 3 | @using Microsoft.AspNetCore.Http.Extensions 4 | @{ 5 | var title = "Pathfinding Laboratory - Powered by LINQ to A*"; 6 | var description = "Run, test and compare pathfinding algorithms and heuristic functions"; 7 | var controller = ViewContext.RouteData.Values["Controller"].ToString(); 8 | } 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | @title 20 | 21 | 22 | @RenderSection("Styles", false) 23 | 24 | 25 | @if (!nameof(EmbedController).Replace("Controller", string.Empty).Equals(controller, StringComparison.OrdinalIgnoreCase)) 26 | { 27 | 28 | Fork me on GitHub 29 | 30 | } 31 |
32 | @if (!nameof(EmbedController).Replace("Controller", string.Empty).Equals(controller, StringComparison.OrdinalIgnoreCase)) 33 | { 34 | 40 | } 41 | @RenderBody() 42 |
43 | 44 | 45 | @RenderSection("Scripts", required: false) 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Views/_ViewImports.cshtml: -------------------------------------------------------------------------------- 1 | @using Heuristic.PathfindingLab 2 | @using Heuristic.PathfindingLab.Models 3 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers 4 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "_Layout"; 3 | } 4 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Debug", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/appsettings.Production.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/bundleconfig.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "outputFileName": "wwwroot/css/site.min.css", 4 | "inputFiles": [ 5 | "wwwroot/css/site.css" 6 | ] 7 | }, 8 | { 9 | "outputFileName": "wwwroot/js/site.min.js", 10 | "inputFiles": [ 11 | "wwwroot/js/site.js" 12 | ], 13 | "minify": { 14 | "enabled": true, 15 | "renameLocals": false 16 | }, 17 | "sourceMap": false 18 | }, 19 | { 20 | "outputFileName": "wwwroot/js/core.min.js", 21 | "inputFiles": [ 22 | "wwwroot/js/tile.js", 23 | "wwwroot/js/layer.js", 24 | "wwwroot/js/core.js", 25 | "wwwroot/js/chart.js" 26 | ], 27 | "minify": { 28 | "enabled": true, 29 | "renameLocals": false 30 | }, 31 | "sourceMap": false 32 | } 33 | ] 34 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "requires": true, 3 | "lockfileVersion": 1, 4 | "dependencies": { 5 | "@types/d3": { 6 | "version": "5.7.0", 7 | "resolved": "https://registry.npmjs.org/@types/d3/-/d3-5.7.0.tgz", 8 | "integrity": "sha512-zk39IR/djm4A/CO0OWydc33u572TyV5L7FRZVnj54vyeBHgRc+WCfEPZmiRtQx3QkuGb5/IKJtQr0tpU25CKkg==", 9 | "requires": { 10 | "@types/d3-array": "*", 11 | "@types/d3-axis": "*", 12 | "@types/d3-brush": "*", 13 | "@types/d3-chord": "*", 14 | "@types/d3-collection": "*", 15 | "@types/d3-color": "*", 16 | "@types/d3-contour": "*", 17 | "@types/d3-dispatch": "*", 18 | "@types/d3-drag": "*", 19 | "@types/d3-dsv": "*", 20 | "@types/d3-ease": "*", 21 | "@types/d3-fetch": "*", 22 | "@types/d3-force": "*", 23 | "@types/d3-format": "*", 24 | "@types/d3-geo": "*", 25 | "@types/d3-hierarchy": "*", 26 | "@types/d3-interpolate": "*", 27 | "@types/d3-path": "*", 28 | "@types/d3-polygon": "*", 29 | "@types/d3-quadtree": "*", 30 | "@types/d3-random": "*", 31 | "@types/d3-scale": "*", 32 | "@types/d3-scale-chromatic": "*", 33 | "@types/d3-selection": "*", 34 | "@types/d3-shape": "*", 35 | "@types/d3-time": "*", 36 | "@types/d3-time-format": "*", 37 | "@types/d3-timer": "*", 38 | "@types/d3-transition": "*", 39 | "@types/d3-voronoi": "*", 40 | "@types/d3-zoom": "*" 41 | } 42 | }, 43 | "@types/d3-array": { 44 | "version": "1.2.5", 45 | "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-1.2.5.tgz", 46 | "integrity": "sha512-kELkPCl/pCcelr5cXDoQyy3WOkLn8dVdYA+qmtQcuxX9gLoD4s12/CJf6Yxx4UvvuMKJHA8kUbdcH/3DY8SzNg==" 47 | }, 48 | "@types/d3-axis": { 49 | "version": "1.0.11", 50 | "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-1.0.11.tgz", 51 | "integrity": "sha512-cuigApCyCwYJxaQPghj+BqaxzbdRdT/lpZBMtF7EuEIJ61NMQ8yvGnqFvHCIgJEmUu2Wb2wiZqy9kiHi3Ddftg==", 52 | "requires": { 53 | "@types/d3-selection": "*" 54 | } 55 | }, 56 | "@types/d3-brush": { 57 | "version": "1.0.9", 58 | "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-1.0.9.tgz", 59 | "integrity": "sha512-mAx8IVc0luUHfk51pl0UN1vzybnAzLMUsvIwLt3fbsqqPkSXr+Pu1AxOPPeyNc27LhHJnfH/LCV7Jlv+Yzqu1A==", 60 | "requires": { 61 | "@types/d3-selection": "*" 62 | } 63 | }, 64 | "@types/d3-chord": { 65 | "version": "1.0.8", 66 | "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-1.0.8.tgz", 67 | "integrity": "sha512-F0ftYOo7FenAIxsRjXLt8vbij0NLDuVcL+xaGY7R9jUmF2Mrpj1T5XukBI9Cad+Ei7YSxEWREIO+CYcaKCl2qQ==" 68 | }, 69 | "@types/d3-collection": { 70 | "version": "1.0.7", 71 | "resolved": "https://registry.npmjs.org/@types/d3-collection/-/d3-collection-1.0.7.tgz", 72 | "integrity": "sha512-vR3BT0GwHc5y93Jv6bxn3zoxP/vGu+GdXu/r1ApjbP9dLk9I2g6NiV7iP/QMQSuFZd0It0n/qWrfXHxCWwHIkg==" 73 | }, 74 | "@types/d3-color": { 75 | "version": "1.2.1", 76 | "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-1.2.1.tgz", 77 | "integrity": "sha512-xwb1tqvYNWllbHuhMFhiXk63Imf+QNq/dJdmbXmr2wQVnwGenCuj3/0IWJ9hdIFQIqzvhT7T37cvx93jtAsDbQ==" 78 | }, 79 | "@types/d3-contour": { 80 | "version": "1.3.0", 81 | "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-1.3.0.tgz", 82 | "integrity": "sha512-AUCUIjEnC5lCGBM9hS+MryRaFLIrPls4Rbv6ktqbd+TK/RXZPwOy9rtBWmGpbeXcSOYCJTUDwNJuEnmYPJRxHQ==", 83 | "requires": { 84 | "@types/d3-array": "*", 85 | "@types/geojson": "*" 86 | } 87 | }, 88 | "@types/d3-dispatch": { 89 | "version": "1.0.6", 90 | "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-1.0.6.tgz", 91 | "integrity": "sha512-xyWJQMr832vqhu6fD/YqX+MSFBWnkxasNhcStvlhqygXxj0cKqPft0wuGoH5TIq5ADXgP83qeNVa4R7bEYN3uA==" 92 | }, 93 | "@types/d3-drag": { 94 | "version": "1.2.2", 95 | "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-1.2.2.tgz", 96 | "integrity": "sha512-+UKFeaMVTfSQvMO0PTzOyLXSr7OZbF2Rx1iNVwo2XsyiOsd4MSuLyJKUwRmGn67044QpbNzr+VD6/8iBBLExWw==", 97 | "requires": { 98 | "@types/d3-selection": "*" 99 | } 100 | }, 101 | "@types/d3-dsv": { 102 | "version": "1.0.35", 103 | "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-1.0.35.tgz", 104 | "integrity": "sha512-QeH7cN9phcm68TDwpSGmzE71/JtGoKZ2rZJABNUMQ7nYIhHkm2UldqI1Cp2pjEo8ycSeutudjzq+Lfim/ZCadQ==" 105 | }, 106 | "@types/d3-ease": { 107 | "version": "1.0.7", 108 | "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-1.0.7.tgz", 109 | "integrity": "sha1-k6MBhovp4VBh89RDQ7GrP4rLbwk=" 110 | }, 111 | "@types/d3-fetch": { 112 | "version": "1.1.5", 113 | "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-1.1.5.tgz", 114 | "integrity": "sha512-o9c0ItT5/Gl3wbNuVpzRnYX1t3RghzeWAjHUVLuyZJudiTxC4f/fC0ZPFWLQ2lVY8pAMmxpV8TJ6ETYCgPeI3A==", 115 | "requires": { 116 | "@types/d3-dsv": "*" 117 | } 118 | }, 119 | "@types/d3-force": { 120 | "version": "1.1.1", 121 | "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-1.1.1.tgz", 122 | "integrity": "sha512-ePkELuaFWY4yOuf+Bvx5Xd+ihFiYG4bdnW0BlvigovIm8Sob2t76e9RGO6lybQbv6AlW9Icn9HuZ9fmdzEoJyg==" 123 | }, 124 | "@types/d3-format": { 125 | "version": "1.3.0", 126 | "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-1.3.0.tgz", 127 | "integrity": "sha512-ZiY4j3iJvAdOwzwW24WjlZbUNvqOsnPAMfPBmdXqxj3uKJbrzBlRrdGl5uC89pZpFs9Dc92E81KcwG2uEgkIZA==" 128 | }, 129 | "@types/d3-geo": { 130 | "version": "1.11.0", 131 | "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-1.11.0.tgz", 132 | "integrity": "sha512-/IbMHRG9cur+6hkWvBrRg3DnnUWtaSW8Bl6nu1OO1J8K25BxRYyLslyjIBbwlK0kV0haztlAR2LCIRuDc/U2LA==", 133 | "requires": { 134 | "@types/geojson": "*" 135 | } 136 | }, 137 | "@types/d3-hierarchy": { 138 | "version": "1.1.5", 139 | "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-1.1.5.tgz", 140 | "integrity": "sha512-DKhqURrURt2c7MsF9sHiF2wrWf2+yZR4Q9oIG026t/ZY4VWoM0Yd7UonaR+rygyReWcFSEjKC/+5A27TgD8R8g==" 141 | }, 142 | "@types/d3-interpolate": { 143 | "version": "1.3.0", 144 | "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-1.3.0.tgz", 145 | "integrity": "sha512-Ng4ds7kPSvP/c3W3J5PPUQlgewif1tGBqCeh5lgY+UG82Y7H9zQ8c2gILsEFDLg7wRGOwnuKZ940Q/LSN14w9w==", 146 | "requires": { 147 | "@types/d3-color": "*" 148 | } 149 | }, 150 | "@types/d3-path": { 151 | "version": "1.0.7", 152 | "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-1.0.7.tgz", 153 | "integrity": "sha512-U8dFRG+8WhkLJr2sxZ9Cw/5WeRgBnNqMxGdA1+Z0+ZG6tK0s75OQ4OXnxeyfKuh6E4wQPY8OAKr1+iNDx01BEQ==" 154 | }, 155 | "@types/d3-polygon": { 156 | "version": "1.0.6", 157 | "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-1.0.6.tgz", 158 | "integrity": "sha512-E6Kyodn9JThgLq20nxSbEce9ow5/ePgm9PX2EO6W1INIL4DayM7cFaiG10DStuamjYAd0X4rntW2q+GRjiIktw==" 159 | }, 160 | "@types/d3-quadtree": { 161 | "version": "1.0.6", 162 | "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-1.0.6.tgz", 163 | "integrity": "sha512-sphVuDdiSIaxLt9kQgebJW98pTktQ/xuN7Ysd8X68Rnjeg/q8+c36/ShlqU52qoKg9nob/JEHH1uQMdxURZidQ==" 164 | }, 165 | "@types/d3-random": { 166 | "version": "1.1.1", 167 | "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-1.1.1.tgz", 168 | "integrity": "sha512-jUPeBq1XKK9/5XasTvy5QAUwFeMsjma2yt/nP02yC2Tijovx7i/W5776U/HZugxc5SSmtpx4Z3g9KFVon0QrjQ==" 169 | }, 170 | "@types/d3-scale": { 171 | "version": "2.1.0", 172 | "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-2.1.0.tgz", 173 | "integrity": "sha512-vLzRDF5lRxZdCLUOvmw90pkiuSsZdgroBQaat0Ov7Z7OnO9iJsPSm/TZw3wW6m2z/NhIn1E4N0RLNfEi1k4kAA==", 174 | "requires": { 175 | "@types/d3-time": "*" 176 | } 177 | }, 178 | "@types/d3-scale-chromatic": { 179 | "version": "1.3.0", 180 | "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-1.3.0.tgz", 181 | "integrity": "sha512-JqQH5uu1kmdQEa6XSu7NYzQM71lL1YreBPS5o8SnmEDcBRKL6ooykXa8iFPPOEUiTah25ydi+cTrbsogBSMNSQ==" 182 | }, 183 | "@types/d3-selection": { 184 | "version": "1.3.4", 185 | "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-1.3.4.tgz", 186 | "integrity": "sha512-WQ6Ivy7VuUlZ/Grqc8493ZxC+y/fpvZLy5+8ELvmCr2hll8eJPUqC05l6fgRRA7kjqlpbH7lbmvY6pRKf6yzxw==" 187 | }, 188 | "@types/d3-shape": { 189 | "version": "1.3.0", 190 | "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-1.3.0.tgz", 191 | "integrity": "sha512-ERWJ8bNZjkzfWfPAlkN3XCqYOOsWTnqTX0jX2Bx+WLd2AfEl97WXr2igwssFc91MadrZLw7HNS/JTUZPQL5sZQ==", 192 | "requires": { 193 | "@types/d3-path": "*" 194 | } 195 | }, 196 | "@types/d3-time": { 197 | "version": "1.0.9", 198 | "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-1.0.9.tgz", 199 | "integrity": "sha512-m+D4NbQdDlTVaO7QgXAnatR3IDxQYDMBtRhgSCi5rs9R1LPq1y7/2aqa1FJ2IWjFm1mOV63swDxonnCDlHgHMA==" 200 | }, 201 | "@types/d3-time-format": { 202 | "version": "2.1.0", 203 | "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-2.1.0.tgz", 204 | "integrity": "sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==" 205 | }, 206 | "@types/d3-timer": { 207 | "version": "1.0.8", 208 | "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-1.0.8.tgz", 209 | "integrity": "sha512-AKUgQ/nljUFcUO2P3gK24weVI5XwUTdJvjoh8gJ0yxT4aJ+d7t2Or3TB+k9dEYl14BAjoj32D0ky+YzQSVszfg==" 210 | }, 211 | "@types/d3-transition": { 212 | "version": "1.1.3", 213 | "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-1.1.3.tgz", 214 | "integrity": "sha512-1EukXNuVu/z2G1GZpZagzFJnie9C5zze17ox/vhTgGXNy46rYAm4UkhLLlUeeZ1ndq88k95SOeC8898RpKMLOQ==", 215 | "requires": { 216 | "@types/d3-selection": "*" 217 | } 218 | }, 219 | "@types/d3-voronoi": { 220 | "version": "1.1.8", 221 | "resolved": "https://registry.npmjs.org/@types/d3-voronoi/-/d3-voronoi-1.1.8.tgz", 222 | "integrity": "sha512-zqNhW7QsYQGlfOdrwPNPG3Wk64zUa4epKRurkJ/dVc6oeXrB+iTDt8sRZ0KZKOOXvvfa1dcdB0e45TZeLBiodQ==" 223 | }, 224 | "@types/d3-zoom": { 225 | "version": "1.7.3", 226 | "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-1.7.3.tgz", 227 | "integrity": "sha512-Tz7+z4+Id0MxERw/ozinC5QHJmGLARs9Mpi/7VVfiR+9AHcFGe9q+fjQa30/oPNY8WPuCh5p5uuXmBYAJ3y91Q==", 228 | "requires": { 229 | "@types/d3-interpolate": "*", 230 | "@types/d3-selection": "*" 231 | } 232 | }, 233 | "@types/geojson": { 234 | "version": "7946.0.5", 235 | "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.5.tgz", 236 | "integrity": "sha512-rLlMXpd3rdlrp0+xsrda/hFfOpIxgqFcRpk005UKbHtcdFK+QXAjhBAPnvO58qF4O1LdDXrcaiJxMgstCIlcaw==" 237 | }, 238 | "commander": { 239 | "version": "2.19.0", 240 | "resolved": "https://registry.npmjs.org/commander/-/commander-2.19.0.tgz", 241 | "integrity": "sha512-6tvAOO+D6OENvRAh524Dh9jcfKTYDQAqvqezbCW82xj5X0pSrcpxtvRKHLG0yBY6SD7PSDrJaj+0AiOcKVd1Xg==" 242 | }, 243 | "d3": { 244 | "version": "5.8.0", 245 | "resolved": "https://registry.npmjs.org/d3/-/d3-5.8.0.tgz", 246 | "integrity": "sha512-0rc4LL3fbyWhAqrxOt00svoxB2qoHHo6Bgs0WGcDPZ8ELqbA09evfeCnuy0ZrYbRHc+hCvBZaTT+GW3pnn05fw==", 247 | "requires": { 248 | "d3-array": "1", 249 | "d3-axis": "1", 250 | "d3-brush": "1", 251 | "d3-chord": "1", 252 | "d3-collection": "1", 253 | "d3-color": "1", 254 | "d3-contour": "1", 255 | "d3-dispatch": "1", 256 | "d3-drag": "1", 257 | "d3-dsv": "1", 258 | "d3-ease": "1", 259 | "d3-fetch": "1", 260 | "d3-force": "1", 261 | "d3-format": "1", 262 | "d3-geo": "1", 263 | "d3-hierarchy": "1", 264 | "d3-interpolate": "1", 265 | "d3-path": "1", 266 | "d3-polygon": "1", 267 | "d3-quadtree": "1", 268 | "d3-random": "1", 269 | "d3-scale": "2", 270 | "d3-scale-chromatic": "1", 271 | "d3-selection": "1", 272 | "d3-shape": "1", 273 | "d3-time": "1", 274 | "d3-time-format": "2", 275 | "d3-timer": "1", 276 | "d3-transition": "1", 277 | "d3-voronoi": "1", 278 | "d3-zoom": "1" 279 | } 280 | }, 281 | "d3-array": { 282 | "version": "1.2.4", 283 | "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-1.2.4.tgz", 284 | "integrity": "sha512-KHW6M86R+FUPYGb3R5XiYjXPq7VzwxZ22buHhAEVG5ztoEcZZMLov530mmccaqA1GghZArjQV46fuc8kUqhhHw==" 285 | }, 286 | "d3-axis": { 287 | "version": "1.0.12", 288 | "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-1.0.12.tgz", 289 | "integrity": "sha512-ejINPfPSNdGFKEOAtnBtdkpr24c4d4jsei6Lg98mxf424ivoDP2956/5HDpIAtmHo85lqT4pruy+zEgvRUBqaQ==" 290 | }, 291 | "d3-brush": { 292 | "version": "1.0.6", 293 | "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-1.0.6.tgz", 294 | "integrity": "sha512-lGSiF5SoSqO5/mYGD5FAeGKKS62JdA1EV7HPrU2b5rTX4qEJJtpjaGLJngjnkewQy7UnGstnFd3168wpf5z76w==", 295 | "requires": { 296 | "d3-dispatch": "1", 297 | "d3-drag": "1", 298 | "d3-interpolate": "1", 299 | "d3-selection": "1", 300 | "d3-transition": "1" 301 | } 302 | }, 303 | "d3-chord": { 304 | "version": "1.0.6", 305 | "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-1.0.6.tgz", 306 | "integrity": "sha512-JXA2Dro1Fxw9rJe33Uv+Ckr5IrAa74TlfDEhE/jfLOaXegMQFQTAgAw9WnZL8+HxVBRXaRGCkrNU7pJeylRIuA==", 307 | "requires": { 308 | "d3-array": "1", 309 | "d3-path": "1" 310 | } 311 | }, 312 | "d3-collection": { 313 | "version": "1.0.7", 314 | "resolved": "https://registry.npmjs.org/d3-collection/-/d3-collection-1.0.7.tgz", 315 | "integrity": "sha512-ii0/r5f4sjKNTfh84Di+DpztYwqKhEyUlKoPrzUFfeSkWxjW49xU2QzO9qrPrNkpdI0XJkfzvmTu8V2Zylln6A==" 316 | }, 317 | "d3-color": { 318 | "version": "1.2.3", 319 | "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-1.2.3.tgz", 320 | "integrity": "sha512-x37qq3ChOTLd26hnps36lexMRhNXEtVxZ4B25rL0DVdDsGQIJGB18S7y9XDwlDD6MD/ZBzITCf4JjGMM10TZkw==" 321 | }, 322 | "d3-contour": { 323 | "version": "1.3.2", 324 | "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-1.3.2.tgz", 325 | "integrity": "sha512-hoPp4K/rJCu0ladiH6zmJUEz6+u3lgR+GSm/QdM2BBvDraU39Vr7YdDCicJcxP1z8i9B/2dJLgDC1NcvlF8WCg==", 326 | "requires": { 327 | "d3-array": "^1.1.1" 328 | } 329 | }, 330 | "d3-dispatch": { 331 | "version": "1.0.5", 332 | "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-1.0.5.tgz", 333 | "integrity": "sha512-vwKx+lAqB1UuCeklr6Jh1bvC4SZgbSqbkGBLClItFBIYH4vqDJCA7qfoy14lXmJdnBOdxndAMxjCbImJYW7e6g==" 334 | }, 335 | "d3-drag": { 336 | "version": "1.2.3", 337 | "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-1.2.3.tgz", 338 | "integrity": "sha512-8S3HWCAg+ilzjJsNtWW1Mutl74Nmzhb9yU6igspilaJzeZVFktmY6oO9xOh5TDk+BM2KrNFjttZNoJJmDnkjkg==", 339 | "requires": { 340 | "d3-dispatch": "1", 341 | "d3-selection": "1" 342 | } 343 | }, 344 | "d3-dsv": { 345 | "version": "1.0.10", 346 | "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-1.0.10.tgz", 347 | "integrity": "sha512-vqklfpxmtO2ZER3fq/B33R/BIz3A1PV0FaZRuFM8w6jLo7sUX1BZDh73fPlr0s327rzq4H6EN1q9U+eCBCSN8g==", 348 | "requires": { 349 | "commander": "2", 350 | "iconv-lite": "0.4", 351 | "rw": "1" 352 | } 353 | }, 354 | "d3-ease": { 355 | "version": "1.0.5", 356 | "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-1.0.5.tgz", 357 | "integrity": "sha512-Ct1O//ly5y5lFM9YTdu+ygq7LleSgSE4oj7vUt9tPLHUi8VCV7QoizGpdWRWAwCO9LdYzIrQDg97+hGVdsSGPQ==" 358 | }, 359 | "d3-fetch": { 360 | "version": "1.1.2", 361 | "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-1.1.2.tgz", 362 | "integrity": "sha512-S2loaQCV/ZeyTyIF2oP8D1K9Z4QizUzW7cWeAOAS4U88qOt3Ucf6GsmgthuYSdyB2HyEm4CeGvkQxWsmInsIVA==", 363 | "requires": { 364 | "d3-dsv": "1" 365 | } 366 | }, 367 | "d3-force": { 368 | "version": "1.2.0", 369 | "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-1.2.0.tgz", 370 | "integrity": "sha512-PFLcDnRVANHMudbQlIB87gcfQorEsDIAvRpZ2bNddfM/WxdsEkyrEaOIPoydhH1I1V4HPjNLGOMLXCA0AuGQ9w==", 371 | "requires": { 372 | "d3-collection": "1", 373 | "d3-dispatch": "1", 374 | "d3-quadtree": "1", 375 | "d3-timer": "1" 376 | } 377 | }, 378 | "d3-format": { 379 | "version": "1.3.2", 380 | "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-1.3.2.tgz", 381 | "integrity": "sha512-Z18Dprj96ExragQ0DeGi+SYPQ7pPfRMtUXtsg/ChVIKNBCzjO8XYJvRTC1usblx52lqge56V5ect+frYTQc8WQ==" 382 | }, 383 | "d3-geo": { 384 | "version": "1.11.3", 385 | "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-1.11.3.tgz", 386 | "integrity": "sha512-n30yN9qSKREvV2fxcrhmHUdXP9TNH7ZZj3C/qnaoU0cVf/Ea85+yT7HY7i8ySPwkwjCNYtmKqQFTvLFngfkItQ==", 387 | "requires": { 388 | "d3-array": "1" 389 | } 390 | }, 391 | "d3-hierarchy": { 392 | "version": "1.1.8", 393 | "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-1.1.8.tgz", 394 | "integrity": "sha512-L+GHMSZNwTpiq4rt9GEsNcpLa4M96lXMR8M/nMG9p5hBE0jy6C+3hWtyZMenPQdwla249iJy7Nx0uKt3n+u9+w==" 395 | }, 396 | "d3-interpolate": { 397 | "version": "1.3.2", 398 | "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-1.3.2.tgz", 399 | "integrity": "sha512-NlNKGopqaz9qM1PXh9gBF1KSCVh+jSFErrSlD/4hybwoNX/gt1d8CDbDW+3i+5UOHhjC6s6nMvRxcuoMVNgL2w==", 400 | "requires": { 401 | "d3-color": "1" 402 | } 403 | }, 404 | "d3-path": { 405 | "version": "1.0.7", 406 | "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.7.tgz", 407 | "integrity": "sha512-q0cW1RpvA5c5ma2rch62mX8AYaiLX0+bdaSM2wxSU9tXjU4DNvkx9qiUvjkuWCj3p22UO/hlPivujqMiR9PDzA==" 408 | }, 409 | "d3-polygon": { 410 | "version": "1.0.5", 411 | "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-1.0.5.tgz", 412 | "integrity": "sha512-RHhh1ZUJZfhgoqzWWuRhzQJvO7LavchhitSTHGu9oj6uuLFzYZVeBzaWTQ2qSO6bz2w55RMoOCf0MsLCDB6e0w==" 413 | }, 414 | "d3-quadtree": { 415 | "version": "1.0.5", 416 | "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-1.0.5.tgz", 417 | "integrity": "sha512-U2tjwDFbZ75JRAg8A+cqMvqPg1G3BE7UTJn3h8DHjY/pnsAfWdbJKgyfcy7zKjqGtLAmI0q8aDSeG1TVIKRaHQ==" 418 | }, 419 | "d3-random": { 420 | "version": "1.1.2", 421 | "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-1.1.2.tgz", 422 | "integrity": "sha512-6AK5BNpIFqP+cx/sreKzNjWbwZQCSUatxq+pPRmFIQaWuoD+NrbVWw7YWpHiXpCQ/NanKdtGDuB+VQcZDaEmYQ==" 423 | }, 424 | "d3-scale": { 425 | "version": "2.2.2", 426 | "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-2.2.2.tgz", 427 | "integrity": "sha512-LbeEvGgIb8UMcAa0EATLNX0lelKWGYDQiPdHj+gLblGVhGLyNbaCn3EvrJf0A3Y/uOOU5aD6MTh5ZFCdEwGiCw==", 428 | "requires": { 429 | "d3-array": "^1.2.0", 430 | "d3-collection": "1", 431 | "d3-format": "1", 432 | "d3-interpolate": "1", 433 | "d3-time": "1", 434 | "d3-time-format": "2" 435 | } 436 | }, 437 | "d3-scale-chromatic": { 438 | "version": "1.3.3", 439 | "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-1.3.3.tgz", 440 | "integrity": "sha512-BWTipif1CimXcYfT02LKjAyItX5gKiwxuPRgr4xM58JwlLocWbjPLI7aMEjkcoOQXMkYsmNsvv3d2yl/OKuHHw==", 441 | "requires": { 442 | "d3-color": "1", 443 | "d3-interpolate": "1" 444 | } 445 | }, 446 | "d3-selection": { 447 | "version": "1.4.0", 448 | "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-1.4.0.tgz", 449 | "integrity": "sha512-EYVwBxQGEjLCKF2pJ4+yrErskDnz5v403qvAid96cNdCMr8rmCYfY5RGzWz24mdIbxmDf6/4EAH+K9xperD5jg==" 450 | }, 451 | "d3-shape": { 452 | "version": "1.3.3", 453 | "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.3.tgz", 454 | "integrity": "sha512-f7V9wHQCmv4s4N7EmD5i0mwJ5y09L8r1rWVrzH1Av0YfgBKJCnTJGho76rS4HNUIw6tTBbWfFcs4ntP/MKWF4A==", 455 | "requires": { 456 | "d3-path": "1" 457 | } 458 | }, 459 | "d3-time": { 460 | "version": "1.0.10", 461 | "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-1.0.10.tgz", 462 | "integrity": "sha512-hF+NTLCaJHF/JqHN5hE8HVGAXPStEq6/omumPE/SxyHVrR7/qQxusFDo0t0c/44+sCGHthC7yNGFZIEgju0P8g==" 463 | }, 464 | "d3-time-format": { 465 | "version": "2.1.3", 466 | "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-2.1.3.tgz", 467 | "integrity": "sha512-6k0a2rZryzGm5Ihx+aFMuO1GgelgIz+7HhB4PH4OEndD5q2zGn1mDfRdNrulspOfR6JXkb2sThhDK41CSK85QA==", 468 | "requires": { 469 | "d3-time": "1" 470 | } 471 | }, 472 | "d3-timer": { 473 | "version": "1.0.9", 474 | "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-1.0.9.tgz", 475 | "integrity": "sha512-rT34J5HnQUHhcLvhSB9GjCkN0Ddd5Y8nCwDBG2u6wQEeYxT/Lf51fTFFkldeib/sE/J0clIe0pnCfs6g/lRbyg==" 476 | }, 477 | "d3-transition": { 478 | "version": "1.2.0", 479 | "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-1.2.0.tgz", 480 | "integrity": "sha512-VJ7cmX/FPIPJYuaL2r1o1EMHLttvoIuZhhuAlRoOxDzogV8iQS6jYulDm3xEU3TqL80IZIhI551/ebmCMrkvhw==", 481 | "requires": { 482 | "d3-color": "1", 483 | "d3-dispatch": "1", 484 | "d3-ease": "1", 485 | "d3-interpolate": "1", 486 | "d3-selection": "^1.1.0", 487 | "d3-timer": "1" 488 | } 489 | }, 490 | "d3-voronoi": { 491 | "version": "1.1.4", 492 | "resolved": "https://registry.npmjs.org/d3-voronoi/-/d3-voronoi-1.1.4.tgz", 493 | "integrity": "sha512-dArJ32hchFsrQ8uMiTBLq256MpnZjeuBtdHpaDlYuQyjU0CVzCJl/BVW+SkszaAeH95D/8gxqAhgx0ouAWAfRg==" 494 | }, 495 | "d3-zoom": { 496 | "version": "1.7.3", 497 | "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-1.7.3.tgz", 498 | "integrity": "sha512-xEBSwFx5Z9T3/VrwDkMt+mr0HCzv7XjpGURJ8lWmIC8wxe32L39eWHIasEe/e7Ox8MPU4p1hvH8PKN2olLzIBg==", 499 | "requires": { 500 | "d3-dispatch": "1", 501 | "d3-drag": "1", 502 | "d3-interpolate": "1", 503 | "d3-selection": "1", 504 | "d3-transition": "1" 505 | } 506 | }, 507 | "iconv-lite": { 508 | "version": "0.4.24", 509 | "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", 510 | "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", 511 | "requires": { 512 | "safer-buffer": ">= 2.1.2 < 3" 513 | } 514 | }, 515 | "rw": { 516 | "version": "1.3.3", 517 | "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz", 518 | "integrity": "sha1-P4Yt+pGrdmsUiF700BEkv9oHT7Q=" 519 | }, 520 | "safer-buffer": { 521 | "version": "2.1.2", 522 | "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", 523 | "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" 524 | } 525 | } 526 | } 527 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES6" 4 | }, 5 | "compileOnSave": true, 6 | "outFile": "wwwroot/js/core.js", 7 | "files": [ 8 | "wwwroot/js/tile.ts", 9 | "wwwroot/js/layer.ts", 10 | "wwwroot/js/chart.ts", 11 | "wwwroot/js/core.ts" 12 | ] 13 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/css/site.css: -------------------------------------------------------------------------------- 1 | pre, code { 2 | font-size: x-small; 3 | white-space: pre !important; 4 | overflow-x: scroll !important; 5 | } 6 | 7 | button.algorithm { 8 | min-width: 10ch 9 | } 10 | 11 | span.position { 12 | display: inline-block; 13 | min-width: 8ch; 14 | } 15 | 16 | span.number { 17 | display: inline-block; 18 | min-width: 4ch; 19 | } 20 | 21 | .axis path, .axis line { 22 | fill: none; 23 | stroke: #000; 24 | shape-rendering: crispEdges; 25 | } 26 | 27 | /*.x.axis path { 28 | display: none; 29 | }*/ 30 | 31 | .line { 32 | fill: none; 33 | stroke-width: 2px; 34 | } 35 | 36 | .circle { 37 | stroke-width: 2px; 38 | fill: white; 39 | } 40 | 41 | .zeroline { 42 | fill: none; 43 | stroke: green; 44 | stroke-width: 0.5px; 45 | stroke-dasharray: 5 5; 46 | } 47 | 48 | .zerolinetext { 49 | fill: red; 50 | } 51 | 52 | .overlay { 53 | fill: none; 54 | stroke: none; 55 | pointer-events: all; 56 | } 57 | 58 | .focusLine { 59 | fill: none; 60 | stroke: darkgreen; 61 | stroke-width: 1px; 62 | } 63 | 64 | /*#chart > svg { 65 | font-family: Sans-Serif, Arial; 66 | } 67 | 68 | #chart .line { 69 | stroke-width: 2; 70 | fill: none; 71 | } 72 | 73 | #chart .axis path { 74 | stroke: black; 75 | } 76 | 77 | #chart .text { 78 | font-size: 12px; 79 | } 80 | 81 | #chart .title-text { 82 | font-size: 12px; 83 | }*/ -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rvhuang/pathfinding-lab/3bbe6bc31d66901cfe11341122da095f47879863/src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/favicon.ico -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/images/assets.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rvhuang/pathfinding-lab/3bbe6bc31d66901cfe11341122da095f47879863/src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/images/assets.png -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/images/tileGrass.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rvhuang/pathfinding-lab/3bbe6bc31d66901cfe11341122da095f47879863/src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/images/tileGrass.png -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/chart.ts: -------------------------------------------------------------------------------- 1 | class Chart { 2 | private static readonly margin = { top: 20, left: 20, right: 20, bottom: 20 }; 3 | 4 | private readonly elementId: string; 5 | private readonly containerWidth: number; 6 | private readonly containerHeight: number; 7 | private readonly width: number; 8 | private readonly height: number; 9 | private readonly main: d3.Line; 10 | private readonly sub: d3.Line; 11 | 12 | constructor(element: HTMLElement) { 13 | if (element == null) { 14 | return; 15 | } 16 | else { 17 | this.elementId = element.id; 18 | this.containerWidth = element.clientWidth; 19 | this.containerHeight = Math.round(element.clientWidth / 3); 20 | this.width = this.containerWidth - Chart.margin.left - Chart.margin.right; 21 | this.height = this.containerHeight - Chart.margin.top - Chart.margin.bottom; 22 | this.main = d3.line(); 23 | this.sub = d3.line(); 24 | } 25 | } 26 | 27 | public removeStatistics() { 28 | if (this.elementId == null) { 29 | return; 30 | } 31 | d3.select("#" + this.elementId).select("svg").remove(); 32 | } 33 | 34 | public updateStatistics(history: PathfindingHistory, showDetail: (d: Detail, h: PathfindingHistory) => void, hideDetail: () => void) { 35 | if (this.elementId == null) { 36 | return; 37 | } 38 | 39 | let parent = d3.select("#" + this.elementId); 40 | let svg = parent.select("svg"); 41 | 42 | if (svg.node() == null) { 43 | svg = parent.append("svg").attr("width", this.containerWidth).attr("height", this.containerHeight); 44 | } 45 | 46 | let g = svg.select('g'); 47 | 48 | if (g.node() != null) { 49 | g.remove(); 50 | } 51 | 52 | g = svg.append('g').attr('transform', 'translate(' + Chart.margin.left + ', ' + Chart.margin.top + ')'); 53 | 54 | let xDomain = d3.extent(history.details, function (d, i) { return i; }) 55 | let yDomain = d3.extent(history.details, function (d) { return d.candidates.length; }); 56 | 57 | yDomain[0] = 0; 58 | 59 | let xScale = d3.scaleLinear().range([0, this.width]).domain(xDomain); 60 | let yScale = d3.scaleLinear().range([this.height, 0]).domain(yDomain); 61 | 62 | let xAxis = d3.axisBottom(xScale); 63 | let yAxis = d3.axisLeft(yScale); 64 | 65 | this.main.x(function (d, i) { return xScale(i); }).y(d => yScale(d.candidates.length)); 66 | this.sub.x(function (d, i) { return xScale(i); }).y(d => yScale(d.candidates.filter(c => !history.checkIfStepExists(c)).length)); 67 | 68 | g.append('g') 69 | .attr('class', 'x axis') 70 | .attr('transform', 'translate(0, ' + this.height + ')') 71 | .call(xAxis) 72 | .append('text') 73 | .attr('x', this.containerWidth - 100) 74 | .attr('y', -15) 75 | .attr('dx', '.71em') 76 | .attr('dy', '.71em') 77 | .style("fill", "darkgreen") 78 | .text("Index of expanded node"); 79 | 80 | g.append('g') 81 | .attr('class', 'y axis') 82 | .call(yAxis) 83 | .append('text') 84 | .attr('transform', 'rotate(-90)') 85 | .attr('y', 6) 86 | .attr('dy', '.71em') 87 | .attr('text-anchor', 'end') 88 | .style("fill", "darkgreen") 89 | .text("Nodes in open list"); 90 | 91 | g.append('path') 92 | .datum(history.details) 93 | .attr('class', 'line') 94 | .attr('d', this.main(history.details)) 95 | .style('stroke', history.color); 96 | 97 | g.append('path') 98 | .datum(history.details) 99 | .attr('class', 'line') 100 | .attr('d', this.sub(history.details)) 101 | .style('stroke', "silver"); 102 | 103 | g.selectAll('circle').data(history.details).enter().append('circle') 104 | .attr('cx', function (d, i) { return xScale(i); }) 105 | .attr('cy', function (d) { return yScale(d.candidates.length); }) 106 | .attr('r', 4) 107 | .attr('class', 'circle') 108 | .style('fill', function (d) { return history.steps.some(s => s.x === d.step.x && s.y === d.step.y) ? history.color : "white"; }) 109 | .style('stroke', history.color) 110 | 111 | // focus tracking 112 | var focus = g.append('g').style('display', 'none'); 113 | var focusLineX = focus.append('line') 114 | .attr('id', 'focusLineX') 115 | .attr('class', 'focusLine'); 116 | var focusLineY = focus.append('line') 117 | .attr('id', 'focusLineY') 118 | .attr('class', 'focusLine'); 119 | 120 | g.append('rect') 121 | .attr('class', 'overlay') 122 | .attr('width', this.width) 123 | .attr('height', this.height) 124 | .on('mouseover', function () { focus.style('display', null); }) 125 | .on('mouseout', function () { 126 | if (history.isVisible) { 127 | for (let tile of history.path) { 128 | tile.show(); 129 | tile.unhighlight(); 130 | } 131 | for (let tile of history.unvisited) { 132 | tile.show(); 133 | tile.unhighlight(); 134 | } 135 | } 136 | focus.style('display', 'none'); 137 | hideDetail(); 138 | }) 139 | .on('mousemove', function () { 140 | var mouse = d3.mouse(this); 141 | var mouseX = xScale.invert(mouse[0]); 142 | var i = Math.round(mouseX); 143 | var d = history.details[i]; 144 | var x = xScale(i); 145 | var y = yScale(d.candidates.length); 146 | 147 | focusLineX.attr('x1', x).attr('y1', yScale(yDomain[0])).attr('x2', x).attr('y2', yScale(yDomain[1])); 148 | focusLineY.attr('x1', xScale(xDomain[0])).attr('y1', y).attr('x2', xScale(xDomain[1])).attr('y2', y); 149 | 150 | if (history.isVisible) { 151 | for (let tile of history.path) { 152 | if ((d.step.x === tile.x && d.step.y === tile.y) || d.candidates.some(c => c.x === tile.x && c.y === tile.y)) { 153 | tile.show(); 154 | } 155 | else { 156 | tile.hide(); 157 | } 158 | if (d.step.x === tile.x && d.step.y === tile.y) { 159 | tile.highlight(); 160 | } 161 | else { 162 | tile.unhighlight(); 163 | } 164 | } 165 | for (let tile of history.unvisited) { 166 | if ((d.step.x === tile.x && d.step.y === tile.y) || d.candidates.some(c => c.x === tile.x && c.y === tile.y)) { 167 | tile.show(); 168 | } 169 | else { 170 | tile.hide(); 171 | } 172 | if (d.step.x === tile.x && d.step.y === tile.y) { 173 | tile.highlight(); 174 | } 175 | else { 176 | tile.unhighlight(); 177 | } 178 | } 179 | } 180 | showDetail(d, history); 181 | }); 182 | } 183 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/core.ts: -------------------------------------------------------------------------------- 1 | class Core { 2 | public readonly mapWidth: number; 3 | public readonly mapHeight: number; 4 | 5 | private readonly map: Direction[][]; 6 | 7 | private fromX: number; 8 | private fromY: number; 9 | 10 | public constructor(mapWidth: number, mapHeight: number) { 11 | this.map = new Array(mapHeight); 12 | 13 | for (var y = 0; y < mapHeight; y++) { 14 | this.map[y] = new Array(mapWidth); 15 | for (var x = 0; x < mapWidth; x++) { 16 | this.map[y][x] = Direction.None; 17 | } 18 | } 19 | this.mapWidth = mapWidth; 20 | this.mapHeight = mapHeight; 21 | this.fromX = NaN; 22 | this.fromY = NaN; 23 | } 24 | 25 | public placeObstacle(x: number, y: number, obstacle: number): boolean { 26 | if (y < 0 || y >= this.map.length || x < 0 || x >= this.map[0].length) { 27 | return false; 28 | } 29 | if (this.map[y][x] < 0) { 30 | this.map[y][x] = Direction.None; // clear obstacle 31 | return false; 32 | } else { 33 | // less than zero -> obstacle 34 | // 0 -> none 35 | this.map[y][x] = 0 - Math.abs(obstacle); 36 | return true; 37 | } 38 | } 39 | 40 | public isObstacle(x: number, y: number): boolean { 41 | if (y < 0 || y >= this.map.length || x < 0 || x >= this.map[0].length) { 42 | return true; 43 | } 44 | return this.map[y][x] < 0; 45 | } 46 | 47 | public clearObstacles(): ReadonlyArray { 48 | var obstacles = new Array(); 49 | 50 | for (var y = 0; y < this.map.length; y++) { 51 | for (var x = 0; x < this.map[y].length; x++) { 52 | if (this.map[y][x] < 0) { // obstacle 53 | obstacles.push(new Step(x, y, this.map[y][x], this.map[y][x])); 54 | this.map[y][x] = Direction.None; 55 | } 56 | } 57 | } 58 | return obstacles; 59 | } 60 | 61 | public createPathfindingRequestBody(body: PathfindingRequestBody, x: number, y: number): PathfindingRequestStatus { 62 | if (isNaN(this.fromX) && isNaN(this.fromY)) { 63 | this.fromX = x; 64 | this.fromY = y; 65 | 66 | return PathfindingRequestStatus.Initiated; 67 | } 68 | if (this.fromX == x && this.fromY == y) { 69 | this.fromX = NaN; 70 | this.fromY = NaN; 71 | 72 | return PathfindingRequestStatus.None; 73 | } 74 | 75 | body.fromX = this.fromX; 76 | body.fromY = this.fromY; 77 | body.goalX = x; 78 | body.goalY = y; 79 | body.map = this.map; 80 | 81 | this.fromX = NaN; 82 | this.fromY = NaN; 83 | 84 | return PathfindingRequestStatus.Ready; // Ready for sending request. 85 | } 86 | 87 | public assignDirection(step: Step) : Step { 88 | var original = this.map[step.y][step.x]; 89 | var dir = step.direction; 90 | 91 | if (original >= 0) { // less than zero -> Obstacle 92 | dir = original | dir; 93 | step.undo = original ^ dir; // What we should do if we want to undo 94 | } 95 | this.map[step.y][step.x] = dir; 96 | return new Step(step.x, step.y, dir, step.undo); 97 | } 98 | 99 | public assignDirections(solution: Array): ReadonlyArray { 100 | var assigned = new Array(); 101 | 102 | if (solution.length == 0) { 103 | return assigned; 104 | } 105 | for (let i = 0; i < solution.length - 1; i++) { 106 | let x1 = solution[i].x; 107 | let y1 = solution[i].y; 108 | let x2 = solution[i + 1].x; 109 | let y2 = solution[i + 1].y; 110 | 111 | if (typeof solution[i].direction === "undefined" || solution[i].direction == null || solution[i].direction < 0) { // less than zero -> Obstacle 112 | solution[i].direction = Direction.None; 113 | } 114 | if (x1 > x2) { 115 | solution[i].direction = solution[i].direction | Direction.Left; 116 | solution[i + 1].direction = solution[i + 1].direction | Direction.Right; 117 | } 118 | else if (x1 < x2) { 119 | solution[i].direction = solution[i].direction | Direction.Right; 120 | solution[i + 1].direction = solution[i + 1].direction | Direction.Left; 121 | } 122 | if (y1 > y2) { 123 | solution[i].direction = solution[i].direction | Direction.Up; 124 | solution[i + 1].direction = solution[i + 1].direction | Direction.Down; 125 | } 126 | else if (y1 < y2) { 127 | solution[i].direction = solution[i].direction | Direction.Down; 128 | solution[i + 1].direction = solution[i + 1].direction | Direction.Up; 129 | } 130 | assigned.push(this.assignDirection(solution[i])); 131 | } 132 | assigned.push(this.assignDirection(solution[solution.length - 1])); 133 | return assigned; 134 | } 135 | 136 | public removeDirection(step: Step) { 137 | var original = this.map[step.y][step.x]; 138 | 139 | if (original >= 0) { // less than zero -> Obstacle 140 | this.map[step.y][step.x] = original & ~step.undo; 141 | } 142 | step.direction = this.map[step.y][step.x]; 143 | } 144 | 145 | public removeDirections(solution: Array): ReadonlyArray { 146 | for (let i = 0; i < solution.length; i++) { 147 | this.removeDirection(solution[i]); 148 | } 149 | return solution.map(step => new Step(step.x, step.y, step.direction, step.undo)); 150 | } 151 | } 152 | 153 | class Step { 154 | public x: number; // unit: tile 155 | public y: number; // unit: tile 156 | public direction: Direction; 157 | public undo: Direction; 158 | 159 | constructor(x: number, y: number, dir: Direction, undo: Direction) { 160 | this.x = x; 161 | this.y = y; 162 | this.direction = dir; 163 | this.undo = undo; 164 | } 165 | 166 | public getDirectionShortName(): string { 167 | var name = ""; 168 | 169 | if ((this.direction & Direction.Down) == Direction.Down) 170 | name += "d"; 171 | if ((this.direction & Direction.Left) == Direction.Left) 172 | name += "l"; 173 | if ((this.direction & Direction.Right) == Direction.Right) 174 | name += "r"; 175 | if ((this.direction & Direction.Up) == Direction.Up) 176 | name += "u"; 177 | 178 | switch (name) { 179 | case "u": 180 | case "d": 181 | name = "du"; 182 | break; 183 | case "l": 184 | case "r": 185 | name = "lr"; 186 | break; 187 | } 188 | return name; 189 | } 190 | } 191 | 192 | enum PathfindingRequestStatus { 193 | None = 0, 194 | Initiated = 1, 195 | Ready = 2, 196 | } 197 | 198 | enum Direction { 199 | None = 0, 200 | Up = 1, 201 | Down = 2, 202 | Left = 4, 203 | Right = 8 204 | } 205 | 206 | interface Pathfinding { 207 | heuristics: string[]; 208 | algorithm: string; 209 | fromX: number; 210 | fromY: number; 211 | goalX: number; 212 | goalY: number; 213 | 214 | toSelectManyExpression(mapWidth: number, mapHeight: number): string[]; 215 | toExceptExpression(mapWidth: number, mapHeight: number): string[]; 216 | toWhereOnlyExpression(mapWidth: number, mapHeight: number): string[]; 217 | } 218 | 219 | class PathfindingSettings { 220 | 221 | } 222 | 223 | class PathfindingRequestBody implements Pathfinding { 224 | public fromX: number; 225 | public fromY: number; 226 | public goalX: number; 227 | public goalY: number; 228 | public map: number[][]; 229 | public heuristics: string[]; 230 | public algorithm: string; 231 | 232 | public constructor() { 233 | this.fromX = 0; 234 | this.fromY = 0; 235 | this.goalX = 0; 236 | this.goalY = 0; 237 | this.algorithm = "AStar"; 238 | this.heuristics = new Array(); 239 | this.heuristics.push("GetManhattanDistance"); 240 | } 241 | 242 | public toSelectManyExpression(mapWidth: number, mapHeight: number): string[] { 243 | var linq = [ 244 | PathfindingRequestBody.getStartStatement(this.fromX, this.fromY), 245 | PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY), 246 | PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight), 247 | PathfindingRequestBody.getInitializationStatement(this.algorithm) 248 | ]; 249 | 250 | linq.push("var solution = from p in queryable"); 251 | linq.push(" from obstacle in GetMapObstacles()"); 252 | linq.push(" where boundary.Contains(p) && p != obstacle"); 253 | if (this.heuristics.length > 0) { 254 | linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics)); 255 | } 256 | linq.push(" select p;"); 257 | 258 | return linq; 259 | } 260 | 261 | public toExceptExpression(mapWidth: number, mapHeight: number): string[] { 262 | var linq = [ 263 | PathfindingRequestBody.getStartStatement(this.fromX, this.fromY), 264 | PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY), 265 | PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight), 266 | PathfindingRequestBody.getInitializationStatement(this.algorithm) 267 | ]; 268 | 269 | linq.push("var solution = from p in queryable.Except(GetMapObstacles())"); 270 | linq.push(" where boundary.Contains(p)"); 271 | if (this.heuristics.length > 0) { 272 | linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics)); 273 | } 274 | linq.push(" select p;"); 275 | 276 | return linq; 277 | } 278 | 279 | public toWhereOnlyExpression(mapWidth: number, mapHeight: number): string[] { 280 | var linq = [ 281 | PathfindingRequestBody.getStartStatement(this.fromX, this.fromY), 282 | PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY), 283 | PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight), 284 | PathfindingRequestBody.getInitializationStatement(this.algorithm) 285 | ]; 286 | 287 | linq.push("var obstacles = GetMapObstacles();"); 288 | linq.push("var solution = from p in queryable"); 289 | linq.push(" where boundary.Contains(p) && !obstacles.Contains(p)"); 290 | if (this.heuristics.length > 0) { 291 | linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics)); 292 | } 293 | linq.push(" select p;"); 294 | 295 | return linq; 296 | } 297 | 298 | public static getStartStatement(fromX: number, fromY: number): string { 299 | return "var start = new Point(" + fromX + ", " + fromY + ");" 300 | } 301 | 302 | public static getGoalStatement(goalX: number, goalY: number): string { 303 | return "var goal = new Point(" + goalX + ", " + goalY + ");" 304 | } 305 | 306 | public static getBoundaryStatement(mapWidth: number, mapHeight: number): string { 307 | return "var boundary = new Rectangle(0, 0, " + mapWidth + ", " + mapHeight + ");" 308 | } 309 | 310 | public static getInitializationStatement(algorithm: string): string { 311 | switch (algorithm) { 312 | case "AStar": 313 | return "var queryable = HeuristicSearch.AStar(start, goal, (s, i) => s.GetFourDirections(unit));"; 314 | case "BestFirstSearch": 315 | return "var queryable = HeuristicSearch.BestFirstSearch(start, goal, (s, i) => s.GetFourDirections(unit));"; 316 | case "IterativeDeepeningAStar": 317 | return "var queryable = HeuristicSearch.IterativeDeepeningAStar(start, goal, (s, i) => s.GetFourDirections(unit));"; 318 | case "RecursiveBestFirstSearch": 319 | return "var queryable = HeuristicSearch.RecursiveBestFirstSearch(start, goal, (s, i) => s.GetFourDirections(unit));"; 320 | } 321 | return "var queryable = HeuristicSearch.AStar(start, goal, (s, i) => s.GetFourDirections(unit));"; 322 | } 323 | 324 | public static getOrderByThenByStatement(heuristics: ReadonlyArray): string { 325 | var statement = "orderby "; 326 | var statements = new Array(); 327 | 328 | for (var i = 0; i < heuristics.length; i++) { 329 | switch (heuristics[i]) { 330 | case "GetChebyshevDistance": 331 | statements.push("p.GetChebyshevDistance(goal)"); 332 | break; 333 | case "GetEuclideanDistance": 334 | statements.push("p.GetEuclideanDistance(goal)"); 335 | break; 336 | case "GetManhattanDistance": 337 | statements.push("p.GetManhattanDistance(goal)"); 338 | break; 339 | default: 340 | statements.push("p.GetManhattanDistance(goal)"); 341 | break; 342 | } 343 | } 344 | return statement + statements.join(", "); 345 | } 346 | } 347 | 348 | class Detail { 349 | public level: number; 350 | public step: Step; 351 | public candidates: ReadonlyArray; 352 | } 353 | 354 | class PathfindingHistory implements Pathfinding { 355 | public readonly fromX: number; 356 | public readonly fromY: number; 357 | public readonly goalX: number; 358 | public readonly goalY: number; 359 | public readonly steps: ReadonlyArray; 360 | public readonly details: Array; 361 | public readonly path: ReadonlyArray; 362 | public readonly unvisited: ReadonlyArray; 363 | public readonly heuristics: string[]; 364 | public readonly algorithm: string; 365 | public readonly algorithmShortName: string; 366 | public readonly color: string; 367 | 368 | public isVisible: boolean; 369 | 370 | constructor(request: PathfindingRequestBody, steps: Array, details: Array) { 371 | this.fromX = request.fromX; 372 | this.fromY = request.fromY; 373 | this.goalX = request.goalX; 374 | this.goalY = request.goalY; 375 | this.color = PathfindingHistory.getAlgorithmPathColor(request.algorithm); 376 | this.steps = steps.map(step => new Step(step.x, step.y, step.direction, step.undo)); 377 | this.details = details; 378 | this.path = steps.map((p, i) => new PathTile(p.x, p.y, i, this.color)); 379 | this.unvisited = UnvisitedTile.merge(details.map(d => new UnvisitedTile(d.step.x, d.step.y, d.level, this.color))); 380 | this.heuristics = request.heuristics; 381 | this.algorithm = request.algorithm; 382 | this.algorithmShortName = PathfindingHistory.getAlgorithmShortName(request.algorithm); 383 | this.isVisible = false; 384 | } 385 | 386 | public findTileWithStep(s: Step): SolutionTile { 387 | var index = this.path.findIndex(p => p.x === s.x && p.y === s.y); 388 | if (index > -1) { 389 | return this.path[index]; 390 | } 391 | index = this.unvisited.findIndex(u => u.x === s.x && u.y === s.y); 392 | if (index > -1) { 393 | return this.unvisited[index]; 394 | } 395 | return null; 396 | } 397 | 398 | public checkIfStepExists(s: Step): boolean { 399 | return this.path.some(p => p.x === s.x && p.y === s.y) || this.unvisited.some(u => u.x === s.x && u.y === s.y); 400 | } 401 | 402 | public toSelectManyExpression(mapWidth: number, mapHeight: number): string[] { 403 | var linq = [ 404 | PathfindingRequestBody.getStartStatement(this.fromX, this.fromY), 405 | PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY), 406 | PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight), 407 | PathfindingRequestBody.getInitializationStatement(this.algorithm) 408 | ]; 409 | 410 | linq.push("var solution = from p in queryable"); 411 | linq.push(" from obstacle in GetMapObstacles()"); 412 | linq.push(" where boundary.Contains(p) && p != obstacle"); 413 | linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics)); 414 | linq.push(" select p;"); 415 | 416 | return linq; 417 | } 418 | 419 | public toExceptExpression(mapWidth: number, mapHeight: number): string[] { 420 | var linq = [ 421 | PathfindingRequestBody.getStartStatement(this.fromX, this.fromY), 422 | PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY), 423 | PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight), 424 | PathfindingRequestBody.getInitializationStatement(this.algorithm) 425 | ]; 426 | 427 | linq.push("var solution = from p in queryable.Except(GetMapObstacles())"); 428 | linq.push(" where boundary.Contains(p)"); 429 | linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics)); 430 | linq.push(" select p;"); 431 | linq.push(" // --"); // Keeps same number of lines. 432 | 433 | return linq; 434 | } 435 | 436 | public toWhereOnlyExpression(mapWidth: number, mapHeight: number): string[] { 437 | var linq = [ 438 | PathfindingRequestBody.getStartStatement(this.fromX, this.fromY), 439 | PathfindingRequestBody.getGoalStatement(this.goalX, this.goalY), 440 | PathfindingRequestBody.getBoundaryStatement(mapWidth, mapHeight), 441 | PathfindingRequestBody.getInitializationStatement(this.algorithm) 442 | ]; 443 | 444 | linq.push("var obstacles = GetMapObstacles();"); 445 | linq.push("var solution = from p in queryable"); 446 | linq.push(" where boundary.Contains(p) && !obstacles.Contains(p)"); 447 | linq.push(" " + PathfindingRequestBody.getOrderByThenByStatement(this.heuristics)); 448 | linq.push(" select p;"); 449 | 450 | return linq; 451 | } 452 | 453 | public static getAlgorithmShortName(algorithm: string): string { 454 | switch (algorithm) { 455 | case "AStar": 456 | return "A*"; 457 | case "BestFirstSearch": 458 | return "BFS"; 459 | case "IterativeDeepeningAStar": 460 | return "IDA*"; 461 | case "RecursiveBestFirstSearch": 462 | return "RBFS"; 463 | default: 464 | return "A*"; 465 | } 466 | } 467 | 468 | public static getAlgorithmPathColor(algorithm: string): string { 469 | switch (algorithm) { 470 | case "AStar": 471 | return "#17a2b8"; 472 | case "BestFirstSearch": 473 | return "#dc3545"; 474 | case "IterativeDeepeningAStar": 475 | return "#343a40"; 476 | case "RecursiveBestFirstSearch": 477 | return "#ffc107"; 478 | default: 479 | return "#17a2b8"; 480 | } 481 | } 482 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/layer.ts: -------------------------------------------------------------------------------- 1 | 2 | abstract class Layer { 3 | public readonly element: SVGGElement; 4 | public readonly tileWidth: number; // unit: px 5 | public readonly tileHeight: number; // unit: px 6 | public readonly mapWidth: number; // unit: tile 7 | public readonly mapHeight: number; // unit: tile 8 | 9 | constructor(element: SVGGElement, tileWidth: number, tileHeight: number, mapWidth: number, mapHeight: number) { 10 | this.element = element; 11 | this.mapWidth = mapWidth; 12 | this.mapHeight = mapHeight; 13 | this.tileWidth = tileWidth; 14 | this.tileHeight = tileHeight; 15 | } 16 | } 17 | 18 | class CursorLayer extends Layer { 19 | private readonly cursor: SVGRectElement; 20 | 21 | private anchors: Array; 22 | private cursorX: number = 0; 23 | private cursorY: number = 0; 24 | 25 | public readonly histories: Array; 26 | 27 | public showDetailDescription: (tile: SolutionTile) => any; 28 | 29 | constructor(element: SVGGElement, cursor: SVGRectElement, tileWidth: number, tileHeight: number, mapWidth: number, mapHeight: number) { 30 | super(element, tileWidth, tileHeight, mapWidth, mapHeight); 31 | 32 | this.anchors = new Array(); 33 | this.histories = new Array(); 34 | this.cursor = cursor; 35 | this.element.parentElement.addEventListener("mousemove", e => this.onLayerMouseMove(e)); 36 | this.element.parentElement.addEventListener("mouseleave", e => this.onLayerMouseLeave(e)); 37 | this.element.parentElement.addEventListener("mouseenter", e => this.onLayerMouseEnter(e)); 38 | } 39 | 40 | private onLayerMouseMove(event: MouseEvent) { 41 | var rect = this.element.parentElement.getBoundingClientRect(); 42 | var mouseX = Math.floor((event.clientX - rect.left) / this.tileWidth); 43 | var mouseY = Math.floor((event.clientY - rect.top) / this.tileHeight); 44 | var changed = false; 45 | 46 | if (this.cursorX != mouseX) { 47 | this.cursor.x.baseVal.value = mouseX * this.tileWidth; 48 | this.cursorX = mouseX; 49 | 50 | changed = true; 51 | } 52 | if (this.cursorY != mouseY) { 53 | this.cursor.y.baseVal.value = mouseY * this.tileHeight; 54 | this.cursorY = mouseY; 55 | 56 | changed = true; 57 | } 58 | if (changed) { 59 | this.cursor.getElementsByClassName("cursor-x")[0].textContent = `${this.cursorX}`; 60 | this.cursor.getElementsByClassName("cursor-y")[0].textContent = `${this.cursorY}`; 61 | } 62 | } 63 | 64 | private onLayerMouseLeave(event: MouseEvent) { 65 | this.cursor.style.visibility = "hidden"; 66 | } 67 | 68 | private onLayerMouseEnter(event: MouseEvent) { 69 | this.cursor.style.visibility = "inherit"; 70 | } 71 | 72 | public togglePath(index: number): boolean { 73 | var history = this.histories[index]; 74 | if (history == null) return; 75 | 76 | history.isVisible = !history.isVisible; 77 | 78 | if (history.isVisible) { 79 | var begin = 0.3; 80 | var tileElement = null as SVGElement; 81 | var callback = this.showDetailDescription; 82 | 83 | for (let step of history.path) { 84 | tileElement = step.visualize(this.tileWidth, this.tileHeight); 85 | step.updateAnimation(begin); 86 | 87 | if (callback != null) { 88 | tileElement.onmousemove = function (ev) { 89 | callback(step); 90 | }; 91 | } 92 | this.element.appendChild(tileElement); 93 | begin += 0.1; 94 | } 95 | for (let tile of history.unvisited) { 96 | var filtered = history.path.filter(p => p.x === tile.x && p.y === tile.y); 97 | if (filtered.length > 0) { 98 | tile.levels.forEach(level => filtered[0].updateLevels(level)); 99 | } 100 | else { 101 | tileElement = tile.visualize(this.tileWidth, this.tileHeight); 102 | if (callback != null) { 103 | tileElement.onmousemove = function (ev) { 104 | callback(tile); 105 | }; 106 | } 107 | this.element.appendChild(tileElement); 108 | } 109 | } 110 | } 111 | else { 112 | history.path.forEach(p => p.remove()); 113 | history.unvisited.forEach(d => d.remove()); 114 | } 115 | return history.isVisible; 116 | } 117 | 118 | public placeTile(x: number, y: number, color: string) { 119 | if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { 120 | return; 121 | } 122 | let filtered = this.anchors.filter(a => a.x === x && a.y === y); 123 | 124 | if (filtered.length > 0) { 125 | filtered[0].updateColor(color); 126 | } 127 | else { 128 | var anchor = new AnchorTile(x, y, color); 129 | 130 | this.element.appendChild(anchor.visualize(this.tileWidth, this.tileHeight)); 131 | this.anchors.push(anchor); 132 | } 133 | } 134 | 135 | public removeTile(x: number, y: number) { 136 | if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { 137 | return; 138 | } 139 | this.anchors.filter(a => a.x === x && a.y === y).forEach(a => a.remove()); 140 | this.anchors = this.anchors.filter(a => !a.isRemoved()); 141 | } 142 | 143 | public clearAnchors() { 144 | for (let anchor of this.anchors) { 145 | anchor.remove(); 146 | } 147 | this.anchors = new Array(); 148 | } 149 | 150 | public clearTiles() { 151 | for (let history of this.histories) { 152 | history.path.forEach(path => path.remove()); 153 | history.unvisited.forEach(detail => detail.remove()); 154 | } 155 | } 156 | } 157 | 158 | class ForegroundLayer extends Layer { 159 | private readonly assetIds: ReadonlyArray; 160 | 161 | public obstacle: number; 162 | public isPathfindingOnly: boolean; 163 | public objectPracingPredicate: (i: number, j: number, obstacle: number) => boolean; 164 | public pathPlacingCallback: (i: number, j: number) => boolean; 165 | 166 | constructor(sourceLayer: Layer, element: SVGGElement, assetIds: ReadonlyArray) { 167 | super(element, sourceLayer.tileWidth, sourceLayer.tileHeight, sourceLayer.mapWidth, sourceLayer.mapHeight); 168 | 169 | this.element.parentElement.addEventListener("mouseup", e => this.onSourceLayerMouseUp(e)); 170 | this.element.parentElement.addEventListener("contextmenu", e => e.preventDefault()); 171 | this.assetIds = assetIds; 172 | this.obstacle = 1; 173 | this.isPathfindingOnly = false; 174 | 175 | for (let obj of document.querySelectorAll("#obstacle-list > svg")) { 176 | obj.addEventListener("click", e => this.onChangeObstacle(e)); 177 | } 178 | } 179 | 180 | private onSourceLayerMouseUp(event: MouseEvent) { 181 | var rect = this.element.parentElement.getBoundingClientRect(); 182 | var i = Math.floor((event.clientX - rect.left) / this.tileWidth); 183 | var j = Math.floor((event.clientY - rect.top) / this.tileHeight); 184 | 185 | if (this.isPathfindingOnly) { 186 | if (this.pathPlacingCallback != null) { 187 | this.pathPlacingCallback(i, j); 188 | } 189 | return; 190 | } 191 | switch (event.button) { 192 | case 0: 193 | if (this.objectPracingPredicate != null && this.objectPracingPredicate(i, j, this.obstacle)) { 194 | this.placeObject(i, j); 195 | } 196 | else { 197 | this.removeObject(i, j); 198 | } 199 | break; 200 | case 2: 201 | if (this.pathPlacingCallback != null) { 202 | this.pathPlacingCallback(i, j); 203 | } 204 | break; 205 | } 206 | } 207 | 208 | private onChangeObstacle(event: Event) { 209 | this.obstacle = parseInt(event.srcElement.getAttribute("data-obstacle-value")); 210 | } 211 | 212 | public placePath(path: ReadonlyArray, assetIdSelector: (step: Step) => string) { 213 | for (let step of path) { 214 | var id = `step-x-${step.x}-y-${step.y}`; // "step-x-" + step.x.toString() + "-y-" + step.y.toString(); 215 | var existing = this.element.querySelector("#" + id); 216 | var assetId = assetIdSelector(step); 217 | 218 | if (existing != null) { 219 | existing.remove(); 220 | } 221 | if (assetId != null && assetId.length > 0) { 222 | this.placeImage(step.x, step.y, "path-" + assetId).id = id; 223 | } 224 | } 225 | } 226 | 227 | public removePath(path: ReadonlyArray, assetIdSelector: (step: Step) => string) { 228 | for (let step of path) { 229 | var id = this.removeStep(step.x, step.y); 230 | var assetId = assetIdSelector(step); 231 | 232 | if (assetId != null && assetId.length > 0) { 233 | this.placeImage(step.x, step.y, "path-" + assetId).id = id; 234 | } 235 | } 236 | } 237 | 238 | public removeStep(x: number, y: number): string { 239 | var id = `step-x-${x}-y-${y}` // "step-x-" + x.toString() + "-y-" + y.toString(); 240 | 241 | if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { 242 | return id; 243 | } 244 | var existing = this.element.querySelector("#" + id); 245 | 246 | if (existing != null) { 247 | existing.remove(); 248 | } 249 | return id; 250 | } 251 | 252 | public placeStep(x: number, y: number, assertId: string) { 253 | if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { 254 | return; 255 | } 256 | this.placeImage(x, y, assertId); 257 | } 258 | 259 | private placeImage(x: number, y: number, assertId: string): SVGUseElement { 260 | var img = document.createElementNS("http://www.w3.org/2000/svg", "use"); 261 | 262 | img.x.baseVal.value = x * this.tileWidth; 263 | img.y.baseVal.value = y * this.tileHeight; 264 | img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + assertId); 265 | img.classList.add(`image-x-${x}-y-${y}`/*"image-x-" + x.toString() + "-y-" + y.toString()*/); 266 | 267 | this.element.appendChild(img); 268 | return img; 269 | } 270 | 271 | public placeObject(x: number, y: number) { 272 | if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { 273 | return; 274 | } 275 | var id = `object-x-${x}-y-${y}`;// "object-x-" + x.toString() + "-y-" + y.toString(); 276 | var existing = this.element.querySelector("#" + id); 277 | 278 | if (existing != null) { 279 | existing.remove(); 280 | } 281 | // Replace the path with obstacle. 282 | this.removeStep(x, y); 283 | // because the property is not an index so we need to substract the value by one. 284 | this.placeImage(x, y, this.assetIds[this.obstacle - 1]).id = id; 285 | } 286 | 287 | public removeObject(x: number, y: number) { 288 | if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { 289 | return; 290 | } 291 | var id = `object-x-${x}-y-${y}`;// "object-x-" + x.toString() + "-y-" + y.toString(); 292 | var existing = this.element.querySelector("#" + id); 293 | 294 | if (existing != null) { 295 | existing.remove(); 296 | } 297 | } 298 | 299 | public clearMap() { 300 | for (let img of this.element.querySelectorAll("use")) { 301 | img.remove(); 302 | } 303 | } 304 | } -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/site.js: -------------------------------------------------------------------------------- 1 | var tileSize = 32; 2 | var core = typeof mapSettings !== "undefined" ? new Core(mapSettings.width, mapSettings.height) : new Core(40, 20); 3 | var current = new PathfindingRequestBody(); 4 | 5 | $(document).ready(function () { 6 | var cursorLayer = new CursorLayer(document.getElementById('cursor'), document.getElementById('mouse-cursor'), tileSize, tileSize, core.mapWidth, core.mapHeight); 7 | var foregroundLayer = new ForegroundLayer(cursorLayer, document.getElementById('foreground'), [ 8 | "obstacle-0", 9 | "obstacle-1", 10 | "obstacle-2", 11 | "obstacle-3", 12 | "obstacle-4", 13 | "obstacle-5", 14 | "obstacle-6", 15 | "obstacle-7", 16 | "obstacle-8", 17 | "obstacle-9", 18 | "obstacle-10", 19 | "obstacle-11", 20 | "obstacle-12", 21 | "obstacle-13", 22 | "obstacle-14", 23 | "obstacle-15", 24 | "obstacle-16", 25 | "obstacle-17", 26 | "obstacle-18", 27 | "obstacle-19" 28 | ]); 29 | var chart = new Chart(document.getElementById('chart')); 30 | if (typeof mapSettings !== "undefined") { 31 | mapSettings.obstacles.forEach(function (o) { 32 | core.placeObstacle(o.x, o.y, o.value); 33 | foregroundLayer.obstacle = o.value; 34 | foregroundLayer.placeObject(o.x, o.y); 35 | }); 36 | }/* 37 | cursorLayer.showDetailDescription = function(step) { 38 | $("#description").text(step.describes()); 39 | };*/ 40 | foregroundLayer.objectPracingPredicate = (i, j, obstacle) => core.placeObstacle(i, j, obstacle); 41 | foregroundLayer.pathPlacingCallback = function(i, j) { 42 | if (core.isObstacle(i, j)) { 43 | return; 44 | } 45 | switch (core.createPathfindingRequestBody(current, i, j)) { 46 | case PathfindingRequestStatus.Ready: 47 | cursorLayer.placeTile(i, j, PathfindingHistory.getAlgorithmPathColor(current.algorithm)); 48 | $.ajax({ 49 | type: "POST", 50 | url: "api/pathfinding/", 51 | data: JSON.stringify(current), 52 | contentType: "application/json", 53 | success: function (response) { 54 | var solution = response.data.solution; 55 | var assigned = core.assignDirections(solution); 56 | var history = new PathfindingHistory(current, solution, response.data.details); 57 | 58 | chart.updateStatistics(history, showDetail, hideDetail); 59 | foregroundLayer.placePath(assigned, step => step.getDirectionShortName()); 60 | 61 | if (cursorLayer.histories.length > 5) { 62 | $("#histories button:first-child").fadeOut(500, function () { 63 | $(this).remove(); 64 | if (cursorLayer.histories[0].isVisible) { 65 | cursorLayer.togglePath(0); 66 | } 67 | cursorLayer.histories.shift(); 68 | }); 69 | } 70 | cursorLayer.histories.push(history); 71 | cursorLayer.clearAnchors(); 72 | addReplayButton(history, cursorLayer, chart); 73 | if (solution.length === 0) { // Path not found 74 | $("#exampleSelectMany").find("code").text("// No solution is found."); 75 | $("#exampleExcept").find("code").text("// No solution is found."); 76 | $("#exampleWhere").find("code").text("// No solution is found."); 77 | } 78 | updateExpressions(current); 79 | }, 80 | error: function (jqXHR, textStatus, errorThrown) { 81 | var msg = ""; 82 | switch (jqXHR.status) { 83 | case 400: 84 | msg = "// The selected algorithm needs at least one Heuristic function."; 85 | $(':input[name="heuristic"]').parent().css("color", "red"); 86 | break; 87 | case 500: 88 | msg = "// Something went wrong. Please try again later or report an issue at GitHub."; 89 | break; 90 | } 91 | $("#exampleSelectMany").find("code").text(msg); 92 | $("#exampleExcept").find("code").text(msg); 93 | $("#exampleWhere").find("code").text(msg); 94 | }, 95 | complete: function () { 96 | // TODO: 97 | } 98 | }); 99 | break; 100 | case PathfindingRequestStatus.Initiated: 101 | cursorLayer.placeTile(i, j, PathfindingHistory.getAlgorithmPathColor(current.algorithm)); 102 | break; 103 | 104 | case PathfindingRequestStatus.None: 105 | cursorLayer.removeTile(i, j); 106 | break; 107 | } 108 | }; 109 | $('#btnUndo').click(function (event) { 110 | var index = cursorLayer.histories.length - 1; 111 | 112 | if (cursorLayer.histories[index].isVisible) { 113 | cursorLayer.togglePath(index); 114 | } 115 | 116 | var history = cursorLayer.histories.pop(); 117 | var toggled = cursorLayer.histories.filter(h => h.isVisible); 118 | var steps = core.removeDirections(history.steps); 119 | 120 | foregroundLayer.removePath(steps, step => step.getDirectionShortName()); 121 | 122 | if (toggled.length === 0) { 123 | updateOptions(null); 124 | updateExpressions(null); 125 | hideDetail(); 126 | chart.removeStatistics(); 127 | } 128 | else { 129 | updateOptions(toggled[0]); 130 | updateExpressions(toggled[0]); 131 | chart.updateStatistics(toggled[0], showDetail, hideDetail); 132 | } 133 | $("#histories button:last-child").fadeOut(300, function () { 134 | $(this).remove(); 135 | }); 136 | }); 137 | $('#btnClear').click(function (event) { 138 | core.clearObstacles(); 139 | foregroundLayer.clearMap(); 140 | cursorLayer.clearTiles(); 141 | chart.removeStatistics(); 142 | 143 | hideDetail(); 144 | }); 145 | $('#btnFindPath').click(function (event) { 146 | foregroundLayer.isPathfindingOnly = !foregroundLayer.isPathfindingOnly; 147 | }); 148 | $('#btnDelObstacles').click(function (event) { 149 | for (let obstacle of core.clearObstacles()) { 150 | foregroundLayer.removeObject(obstacle.x, obstacle.y); 151 | } 152 | }); 153 | $('a[data-algorithm]').click(function (event) { 154 | current.algorithm = $(this).data('algorithm'); 155 | if (current.fromX !== current.goalX && current.FromY !== current.goalY) { 156 | updateExpressions(current); 157 | } 158 | $("#mouse-cursor rect").attr("fill", PathfindingHistory.getAlgorithmPathColor(current.algorithm)); 159 | $('#algorithm').val(current.algorithm).text($(this).text()); 160 | }); 161 | $(':input[name="heuristic"]').change(function (event) { 162 | if (this.checked) { 163 | current.heuristics.push(this.value); 164 | } 165 | else { 166 | const index = current.heuristics.indexOf(this.value); 167 | if (index !== -1) { 168 | current.heuristics.splice(index, 1); 169 | } 170 | } 171 | if (current.heuristics.length === 0) { 172 | $('a[data-algorithm="AStar"]').text("Dijkstra"); 173 | $('#algorithm[value="AStar"]').text("Dijkstra"); 174 | } 175 | else { 176 | $('a[data-algorithm="AStar"]').text("A*"); 177 | $('#algorithm[value="AStar"]').text("A*"); 178 | } 179 | if (current.fromX !== current.goalX && current.FromY !== current.goalY) { 180 | updateExpressions(current); 181 | } 182 | }).click(function (event) { 183 | $("div.checkbox").children("label").css("color", ""); 184 | return true; 185 | }); 186 | $('[data-toggle="popover"]').popover(); 187 | $('[data-toggle="tooltip"]').tooltip({ 188 | container: "body", 189 | placement: "bottom" 190 | }); 191 | }); 192 | 193 | function addReplayButton(history, cursorLayer, chart) { 194 | var btn = $("#historyTemplate button:first-child").clone(); 195 | 196 | btn.children('[data-field="PathColor"]').css("color", history.color); 197 | btn.children('[data-field="AlgorithmShortName"]').text(history.algorithmShortName); 198 | btn.children('[data-field="Path"]').text("(" + history.path.length + ")"); 199 | btn.appendTo("#histories"); 200 | btn.click(function (e) { 201 | var index = $(this).index(); 202 | if (cursorLayer.togglePath(index)) { 203 | let toggled = cursorLayer.histories[index]; 204 | 205 | updateOptions(toggled); 206 | updateExpressions(toggled); 207 | chart.updateStatistics(toggled, showDetail, hideDetail); 208 | } 209 | else { // Restore to latest state. 210 | let latest = cursorLayer.histories[cursorLayer.histories.length - 1]; 211 | 212 | updateOptions(latest); 213 | updateExpressions(latest); 214 | chart.updateStatistics(latest, showDetail, hideDetail); 215 | } 216 | }); 217 | } 218 | 219 | function updateOptions(pathfinding) { 220 | if (pathfinding != null) { 221 | $(':input[name="heuristic"]').each(function (i, element) { 222 | $(element).prop("checked", pathfinding.heuristics.indexOf($(element).val()) >= 0); 223 | }); 224 | $(':input[name="algorithm"][value="' + pathfinding.algorithm + '"]').prop("checked", true); 225 | } 226 | } 227 | 228 | function updateExpressions(pathfinding) { 229 | if (pathfinding != null) { 230 | $("#exampleSelectMany").find("code").text(pathfinding.toSelectManyExpression(core.mapWidth, core.mapHeight).join('\r\n')); 231 | $("#exampleExcept").find("code").text(pathfinding.toExceptExpression(core.mapWidth, core.mapHeight).join('\r\n')); 232 | $("#exampleWhere").find("code").text(pathfinding.toWhereOnlyExpression(core.mapWidth, core.mapHeight).join('\r\n')); 233 | } 234 | else { 235 | $("#exampleSelectMany").find("code").text("\r\n\r\n\r\n\r\n\r\n\r\n"); 236 | $("#exampleExcept").find("code").text("\r\n\r\n\r\n\r\n\r\n\r\n"); 237 | $("#exampleWhere").find("code").text("\r\n\r\n\r\n\r\n\r\n\r\n"); 238 | } 239 | $("pre code").each(function(i, block) { 240 | hljs.highlightBlock(block); 241 | }); 242 | } 243 | 244 | function showDetail(d, history) { 245 | var texts = $("#description").children("b"); 246 | var spans = $("#description").children("span"); 247 | 248 | if (texts.length > 0) { 249 | texts.eq(0).text("{" + d.step.x + ", " + d.step.y + "}"); 250 | texts.eq(1).text(history.steps.some(s => s.x === d.step.x && s.y === d.step.y) ? "Yes" : "No"); 251 | texts.eq(2).text(d.candidates.length); 252 | texts.eq(3).text(d.candidates.filter(c => !history.checkIfStepExists(c)).length); 253 | } 254 | if (spans.length > 0) { 255 | var descrption = history.findTileWithStep(d.step).describes(); 256 | 257 | spans.eq(0).text(descrption[0]); 258 | spans.eq(1).text(descrption[1]); 259 | } 260 | } 261 | 262 | function hideDetail() { 263 | $("#description").children("span").text(""); 264 | $("#description").children("b").text(""); 265 | } 266 | -------------------------------------------------------------------------------- /src/Heuristic.PathfindingLab/Heuristic.PathfindingLab/wwwroot/js/tile.ts: -------------------------------------------------------------------------------- 1 | abstract class Tile { 2 | public readonly x: number; // unit: tile 3 | public readonly y: number; // unit: tile 4 | 5 | private _color: string; // #007bff 6 | private _element: TElement; 7 | 8 | protected get color() : string { 9 | return this._color; 10 | } 11 | protected set color(value: string) { 12 | this._color = value; 13 | } 14 | protected get element(): TElement { 15 | return this._element; 16 | } 17 | 18 | constructor(x: number, y: number, color: string) { 19 | this.x = x; 20 | this.y = y; 21 | this._color = color; 22 | } 23 | 24 | protected abstract initialize(tileWidth: number, tileHeight: number): TElement; 25 | 26 | public visualize(tileWidth: number, tileHeight: number): TElement { 27 | return this._element = this.initialize(tileWidth, tileHeight); 28 | } 29 | 30 | public hide() { 31 | if (this._element != null) { 32 | this._element.style.display = "none"; 33 | } 34 | } 35 | 36 | public show() { 37 | if (this._element != null) { 38 | this._element.style.display = ""; 39 | } 40 | } 41 | 42 | public remove() { 43 | if (this._element != null) { 44 | this._element.remove(); 45 | this._element = null; 46 | } 47 | } 48 | 49 | public isRemoved(): boolean { 50 | return this._element == null || this._element.parentElement === null; 51 | } 52 | } 53 | 54 | abstract class SolutionTile extends Tile { 55 | public readonly levels: Array; 56 | 57 | constructor(x: number, y: number, level: number, color: string) { 58 | super(x, y, color); 59 | this.levels = [level]; 60 | } 61 | 62 | public updateLevels(level: number) { 63 | if (this.levels.indexOf(level) < 0) { 64 | this.levels.push(level); 65 | } 66 | if (this.element != null) { 67 | this.element.querySelector("text").textContent = this.levels.join(", "); 68 | } 69 | } 70 | 71 | public highlight() { 72 | if (this.element != null) { 73 | this.element.getElementsByTagName("circle")[0].setAttribute("stroke", this.color); 74 | } 75 | } 76 | 77 | public unhighlight() { 78 | if (this.element != null) { 79 | this.element.getElementsByTagName("circle")[0].setAttribute("stroke", "transparent"); 80 | } 81 | } 82 | public describes() : string[] { 83 | var description = new Array(2); 84 | 85 | if (this.levels.length > 1) { 86 | description[0] = `The node has been expanded for ${this.levels.length} times.`; 87 | description[1] = `The depths (levels) of the node are ${this.levels.join(", ")} respectively.`; 88 | } 89 | else { 90 | description[0] = "The node has been expanded for 1 time."; 91 | description[1] = `The depth (level) of the node is ${this.levels.join(", ")}.`; 92 | } 93 | return description; 94 | } 95 | } 96 | 97 | class PathTile extends SolutionTile { 98 | constructor(x: number, y: number, level: number, color: string) { 99 | super(x, y, level, color); 100 | } 101 | 102 | public updateAnimation(begin: number) : SVGElement { 103 | if (this.element != null) { 104 | this.element.querySelector("rect").querySelector("animate").setAttribute("begin", "DOMNodeInsertedIntoDocument+" + begin + "s"); 105 | } 106 | return this.element; 107 | } 108 | 109 | protected initialize(tileWidth: number, tileHeight: number): SVGElement { 110 | let rect = document.getElementById("detail-tile").cloneNode(true) as SVGElement; 111 | let label = rect.getElementsByTagName("text")[0] as SVGTextElement; 112 | 113 | rect.setAttribute("x", (this.x * tileWidth).toString()); 114 | rect.setAttribute("y", (this.y * tileHeight).toString()); 115 | rect.querySelector("rect").setAttribute("stroke", this.color); 116 | rect.querySelector("rect").setAttribute("fill", this.color); 117 | 118 | label.textContent = this.levels.join(", "); 119 | return rect; 120 | } 121 | } 122 | 123 | class UnvisitedTile extends SolutionTile { 124 | public readonly levels: Array; 125 | 126 | constructor(x: number, y: number, level: number, color: string) { 127 | super(x, y, level, color); 128 | } 129 | 130 | protected initialize(tileWidth: number, tileHeight: number): SVGElement { 131 | let rect = document.getElementById("detail-tile").cloneNode(true) as SVGElement; 132 | let label = rect.getElementsByTagName("text")[0] as SVGTextElement; 133 | 134 | rect.setAttribute("x", (this.x * tileWidth).toString()); 135 | rect.setAttribute("y", (this.y * tileHeight).toString()); 136 | rect.querySelector("rect").setAttribute("stroke", this.color); 137 | rect.querySelector("rect").querySelector("animate").remove(); 138 | 139 | label.textContent = this.levels.join(", "); 140 | 141 | return rect; 142 | } 143 | 144 | public static merge(tiles: ReadonlyArray): ReadonlyArray { 145 | var merged = [] as Array; 146 | 147 | for (let tile of tiles) { 148 | let filtered = merged.filter(t => t.x === tile.x && t.y === tile.y); 149 | 150 | if (filtered.length > 0) { 151 | tile.levels.forEach(level => filtered[0].updateLevels(level)); 152 | } 153 | else { 154 | merged.push(tile); 155 | } 156 | } 157 | return merged; 158 | } 159 | } 160 | 161 | class AnchorTile extends Tile { 162 | constructor(x: number, y: number, color: string) { 163 | super(x, y, color); 164 | } 165 | 166 | public updateColor(color: string) { 167 | this.color = color; 168 | this.element.setAttribute("fill", color); 169 | } 170 | 171 | protected initialize(tileWidth: number, tileHeight: number): SVGUseElement { 172 | let rect = document.createElementNS("http://www.w3.org/2000/svg", "use"); 173 | 174 | rect.x.baseVal.value = this.x * tileWidth; 175 | rect.y.baseVal.value = this.y * tileHeight; 176 | rect.width.baseVal.value = tileWidth; 177 | rect.height.baseVal.value = tileHeight; 178 | rect.setAttribute("fill", this.color); 179 | rect.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#cursor-tile"); 180 | 181 | return rect; 182 | } 183 | } 184 | 185 | --------------------------------------------------------------------------------