Last active
October 16, 2021 13:09
-
-
Save kishida/2da9361844ee9ba7ee1c511172e20682 to your computer and use it in GitHub Desktop.
Maze Web
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.PrintWriter; | |
import java.net.ServerSocket; | |
import java.nio.charset.Charset; | |
public class MazeWeb { | |
public static void main(String[] args) throws IOException { | |
record Position(int x, int y) {} | |
final int[][] MAP = { | |
{1, 1, 1, 1, 1, 1}, | |
{1, 0, 1, 0, 0, 1}, | |
{1, 0, 0, 0, 1, 1}, | |
{1, 0, 1, 0, 0, 1}, | |
{1, 1, 1, 1, 1, 1} | |
}; | |
final Position GOAL = new Position(4, 3); | |
Position current = new Position(1, 1); | |
var server = new ServerSocket(80); | |
for (;;) { | |
var soc = server.accept(); | |
try(soc; | |
var isr = new InputStreamReader(soc.getInputStream()); | |
var bur = new BufferedReader(isr); | |
var w = new PrintWriter(soc.getOutputStream(), false, | |
Charset.forName("utf-8"))) { | |
String req = bur.readLine(); | |
if (req == null) { | |
continue; | |
} | |
Position dir = switch(req.split(" ")[1]) { | |
case "/l" -> new Position(-1, 0); | |
case "/r" -> new Position( 1, 0); | |
case "/u" -> new Position( 0,-1); | |
case "/d" -> new Position( 0, 1); | |
default -> new Position( 0, 0); | |
}; | |
var next = new Position(current.x() + dir.x(), current.y() + dir.y()); | |
if (MAP[next.y()][next.x()] == 0) { | |
current = next; | |
} | |
while (!bur.readLine().isEmpty()) ; | |
w.println(""" | |
HTTP/1.1 200 | |
content-type: text/html; charset=utf-8 | |
<html><head><title>Hello</title> | |
</head> | |
<body><h1>Hello</h1>It works!<br> | |
<table> | |
"""); | |
for (int i = 0; i < MAP.length; ++i) { | |
w.println("<tr>"); | |
for (int j = 0; j < MAP[0].length; ++j) { | |
w.print("<td>"); | |
if (i == current.y() && j == current.x()) { | |
w.print("o"); | |
} else if (MAP[i][j] == 1) { | |
w.print("*"); | |
} else { | |
w.print("."); | |
} | |
w.print("</td>"); | |
} | |
w.println("</tr>"); | |
} | |
w.println("</table>"); | |
if (current.equals(GOAL)) { | |
w.println("<div>GOAL!!!</div>"); | |
} | |
w.println(""" | |
<a href="/l">←</a> | |
<a href="/r">→</a> | |
<a href="/u">↑</a> | |
<a href="/d">↓</a> | |
</body></html> | |
"""); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bandicam.2021-09-16.02-11-59-364maze_web.mp4