-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathSnake.java
More file actions
236 lines (207 loc) · 8.96 KB
/
Snake.java
File metadata and controls
236 lines (207 loc) · 8.96 KB
1
2
3
4
5
6
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
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package com.battlesnake.starter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;
import spark.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import static spark.Spark.port;
import static spark.Spark.post;
import static spark.Spark.get;
/**
* This is a simple Battlesnake server written in Java.
*
* For instructions see
* https://github.com/BattlesnakeOfficial/starter-snake-java/README.md
*/
public class Snake {
private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
private static final Handler HANDLER = new Handler();
private static final Logger LOG = LoggerFactory.getLogger(Snake.class);
/**
* Main entry point.
*
* @param args are ignored.
*/
public static void main(String[] args) {
String port = System.getProperty("PORT");
if (port == null) {
LOG.info("Using default port: {}", port);
port = "8080";
} else {
LOG.info("Found system provided port: {}", port);
}
port(Integer.parseInt(port));
get("/", HANDLER::process, JSON_MAPPER::writeValueAsString);
post("/start", HANDLER::process, JSON_MAPPER::writeValueAsString);
post("/move", HANDLER::process, JSON_MAPPER::writeValueAsString);
post("/end", HANDLER::process, JSON_MAPPER::writeValueAsString);
}
/**
* Handler class for dealing with the routes set up in the main method.
*/
public static class Handler {
/**
* For the start/end request
*/
private static final Map<String, String> EMPTY = new HashMap<>();
/**
* Generic processor that prints out the request and response from the methods.
*
* @param req
* @param res
* @return
*/
public Map<String, String> process(Request req, Response res) {
try {
JsonNode parsedRequest = JSON_MAPPER.readTree(req.body());
String uri = req.uri();
LOG.info("{} called with: {}", uri, req.body());
Map<String, String> snakeResponse;
if (uri.equals("/")) {
snakeResponse = index();
} else if (uri.equals("/start")) {
snakeResponse = start(parsedRequest);
} else if (uri.equals("/move")) {
snakeResponse = move(parsedRequest);
} else if (uri.equals("/end")) {
snakeResponse = end(parsedRequest);
} else {
throw new IllegalAccessError("Strange call made to the snake: " + uri);
}
LOG.info("Responding with: {}", JSON_MAPPER.writeValueAsString(snakeResponse));
return snakeResponse;
} catch (JsonProcessingException e) {
LOG.warn("Something went wrong!", e);
return null;
}
}
/**
* This method is called everytime your Battlesnake is entered into a game.
*
* Use this method to decide how your Battlesnake is going to look on the board.
*
* @return a response back to the engine containing the Battlesnake setup
* values.
*/
public Map<String, String> index() {
Map<String, String> response = new HashMap<>();
response.put("apiversion", "1");
response.put("author", ""); // TODO: Your Battlesnake Username
response.put("color", "#888888"); // TODO: Personalize
response.put("head", "default"); // TODO: Personalize
response.put("tail", "default"); // TODO: Personalize
return response;
}
/**
* This method is called everytime your Battlesnake is entered into a game.
*
* Use this method to decide how your Battlesnake is going to look on the board.
*
* @param startRequest a JSON data map containing the information about the game
* that is about to be played.
* @return responses back to the engine are ignored.
*/
public Map<String, String> start(JsonNode startRequest) {
LOG.info("START");
return EMPTY;
}
/**
* This method is called on every turn of a game. It's how your snake decides
* where to move.
*
* Use the information in 'moveRequest' to decide your next move. The
* 'moveRequest' variable can be interacted with as
* com.fasterxml.jackson.databind.JsonNode, and contains all of the information
* about the Battlesnake board for each move of the game.
*
* For a full example of 'json', see
* https://docs.battlesnake.com/references/api/sample-move-request
*
* @param moveRequest JsonNode of all Game Board data as received from the
* Battlesnake Engine.
* @return a Map<String,String> response back to the engine the single move to
* make. One of "up", "down", "left" or "right".
*/
public Map<String, String> move(JsonNode moveRequest) {
try {
LOG.info("Data: {}", JSON_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(moveRequest));
} catch (JsonProcessingException e) {
LOG.error("Error parsing payload", e);
}
/*
* Example how to retrieve data from the request payload:
*
* String gameId = moveRequest.get("game").get("id").asText();
*
* int height = moveRequest.get("board").get("height").asInt();
*
*/
JsonNode head = moveRequest.get("you").get("head");
JsonNode body = moveRequest.get("you").get("body");
ArrayList<String> possibleMoves = new ArrayList<>(Arrays.asList("up", "down", "left", "right"));
// Don't allow your Battlesnake to move back in on it's own neck
avoidMyNeck(head, body, possibleMoves);
// TODO: Using information from 'moveRequest', find the edges of the board and
// don't
// let your Battlesnake move beyond them board_height = ? board_width = ?
// TODO Using information from 'moveRequest', don't let your Battlesnake pick a
// move
// that would hit its own body
// TODO: Using information from 'moveRequest', don't let your Battlesnake pick a
// move
// that would collide with another Battlesnake
// TODO: Using information from 'moveRequest', make your Battlesnake move
// towards a
// piece of food on the board
// Choose a random direction to move in
final int choice = new Random().nextInt(possibleMoves.size());
final String move = possibleMoves.get(choice);
LOG.info("MOVE {}", move);
Map<String, String> response = new HashMap<>();
response.put("move", move);
return response;
}
/**
* Remove the 'neck' direction from the list of possible moves
*
* @param head JsonNode of the head position e.g. {"x": 0, "y": 0}
* @param body JsonNode of x/y coordinates for every segment of a
* Battlesnake. e.g. [ {"x": 0, "y": 0}, {"x": 1, "y": 0},
* {"x": 2, "y": 0} ]
* @param possibleMoves ArrayList of String. Moves to pick from.
*/
public void avoidMyNeck(JsonNode head, JsonNode body, ArrayList<String> possibleMoves) {
JsonNode neck = body.get(1);
if (neck.get("x").asInt() < head.get("x").asInt()) {
possibleMoves.remove("left");
} else if (neck.get("x").asInt() > head.get("x").asInt()) {
possibleMoves.remove("right");
} else if (neck.get("y").asInt() < head.get("y").asInt()) {
possibleMoves.remove("down");
} else if (neck.get("y").asInt() > head.get("y").asInt()) {
possibleMoves.remove("up");
}
}
/**
* This method is called when a game your Battlesnake was in ends.
*
* It is purely for informational purposes, you don't have to make any decisions
* here.
*
* @param endRequest a map containing the JSON sent to this snake. Use this data
* to know which game has ended
* @return responses back to the engine are ignored.
*/
public Map<String, String> end(JsonNode endRequest) {
LOG.info("END");
return EMPTY;
}
}
}