소스 파일 최초 업로드
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package websocket.snake;
|
||||
|
||||
public enum Direction {
|
||||
NONE, NORTH, SOUTH, EAST, WEST
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package websocket.snake;
|
||||
|
||||
public class Location {
|
||||
|
||||
public int x;
|
||||
public int y;
|
||||
|
||||
public Location(int x, int y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public Location getAdjacentLocation(Direction direction) {
|
||||
switch (direction) {
|
||||
case NORTH:
|
||||
return new Location(x, y - SnakeAnnotation.GRID_SIZE);
|
||||
case SOUTH:
|
||||
return new Location(x, y + SnakeAnnotation.GRID_SIZE);
|
||||
case EAST:
|
||||
return new Location(x + SnakeAnnotation.GRID_SIZE, y);
|
||||
case WEST:
|
||||
return new Location(x - SnakeAnnotation.GRID_SIZE, y);
|
||||
case NONE:
|
||||
// fall through
|
||||
default:
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Location location = (Location) o;
|
||||
|
||||
if (x != location.x) {
|
||||
return false;
|
||||
}
|
||||
if (y != location.y) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = x;
|
||||
result = 31 * result + y;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package websocket.snake;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Collection;
|
||||
import java.util.Deque;
|
||||
|
||||
import javax.websocket.CloseReason;
|
||||
import javax.websocket.CloseReason.CloseCodes;
|
||||
import javax.websocket.Session;
|
||||
|
||||
public class Snake {
|
||||
|
||||
private static final int DEFAULT_LENGTH = 5;
|
||||
|
||||
private final int id;
|
||||
private final Session session;
|
||||
|
||||
private Direction direction;
|
||||
private int length = DEFAULT_LENGTH;
|
||||
private Location head;
|
||||
private final Deque<Location> tail = new ArrayDeque<>();
|
||||
private final String hexColor;
|
||||
|
||||
public Snake(int id, Session session) {
|
||||
this.id = id;
|
||||
this.session = session;
|
||||
this.hexColor = SnakeAnnotation.getRandomHexColor();
|
||||
resetState();
|
||||
}
|
||||
|
||||
private void resetState() {
|
||||
this.direction = Direction.NONE;
|
||||
this.head = SnakeAnnotation.getRandomLocation();
|
||||
this.tail.clear();
|
||||
this.length = DEFAULT_LENGTH;
|
||||
}
|
||||
|
||||
private synchronized void kill() {
|
||||
resetState();
|
||||
sendMessage("{\"type\": \"dead\"}");
|
||||
}
|
||||
|
||||
private synchronized void reward() {
|
||||
length++;
|
||||
sendMessage("{\"type\": \"kill\"}");
|
||||
}
|
||||
|
||||
|
||||
protected void sendMessage(String msg) {
|
||||
try {
|
||||
session.getBasicRemote().sendText(msg);
|
||||
} catch (IOException ioe) {
|
||||
CloseReason cr =
|
||||
new CloseReason(CloseCodes.CLOSED_ABNORMALLY, ioe.getMessage());
|
||||
try {
|
||||
session.close(cr);
|
||||
} catch (IOException ioe2) {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void update(Collection<Snake> snakes) {
|
||||
Location nextLocation = head.getAdjacentLocation(direction);
|
||||
if (nextLocation.x >= SnakeAnnotation.PLAYFIELD_WIDTH) {
|
||||
nextLocation.x = 0;
|
||||
}
|
||||
if (nextLocation.y >= SnakeAnnotation.PLAYFIELD_HEIGHT) {
|
||||
nextLocation.y = 0;
|
||||
}
|
||||
if (nextLocation.x < 0) {
|
||||
nextLocation.x = SnakeAnnotation.PLAYFIELD_WIDTH;
|
||||
}
|
||||
if (nextLocation.y < 0) {
|
||||
nextLocation.y = SnakeAnnotation.PLAYFIELD_HEIGHT;
|
||||
}
|
||||
if (direction != Direction.NONE) {
|
||||
tail.addFirst(head);
|
||||
if (tail.size() > length) {
|
||||
tail.removeLast();
|
||||
}
|
||||
head = nextLocation;
|
||||
}
|
||||
|
||||
handleCollisions(snakes);
|
||||
}
|
||||
|
||||
private void handleCollisions(Collection<Snake> snakes) {
|
||||
for (Snake snake : snakes) {
|
||||
boolean headCollision = id != snake.id && snake.getHead().equals(head);
|
||||
boolean tailCollision = snake.getTail().contains(head);
|
||||
if (headCollision || tailCollision) {
|
||||
kill();
|
||||
if (id != snake.id) {
|
||||
snake.reward();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized Location getHead() {
|
||||
return head;
|
||||
}
|
||||
|
||||
public synchronized Collection<Location> getTail() {
|
||||
return tail;
|
||||
}
|
||||
|
||||
public synchronized void setDirection(Direction direction) {
|
||||
this.direction = direction;
|
||||
}
|
||||
|
||||
public synchronized String getLocationsJson() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(String.format("{\"x\": %d, \"y\": %d}",
|
||||
Integer.valueOf(head.x), Integer.valueOf(head.y)));
|
||||
for (Location location : tail) {
|
||||
sb.append(',');
|
||||
sb.append(String.format("{\"x\": %d, \"y\": %d}",
|
||||
Integer.valueOf(location.x), Integer.valueOf(location.y)));
|
||||
}
|
||||
return String.format("{\"id\":%d,\"body\":[%s]}",
|
||||
Integer.valueOf(id), sb.toString());
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getHexColor() {
|
||||
return hexColor;
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package websocket.snake;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.io.EOFException;
|
||||
import java.util.Iterator;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import javax.websocket.OnClose;
|
||||
import javax.websocket.OnError;
|
||||
import javax.websocket.OnMessage;
|
||||
import javax.websocket.OnOpen;
|
||||
import javax.websocket.Session;
|
||||
import javax.websocket.server.ServerEndpoint;
|
||||
|
||||
@ServerEndpoint(value = "/websocket/snake")
|
||||
public class SnakeAnnotation {
|
||||
|
||||
public static final int PLAYFIELD_WIDTH = 640;
|
||||
public static final int PLAYFIELD_HEIGHT = 480;
|
||||
public static final int GRID_SIZE = 10;
|
||||
|
||||
private static final AtomicInteger snakeIds = new AtomicInteger(0);
|
||||
private static final Random random = new Random();
|
||||
|
||||
|
||||
private final int id;
|
||||
private Snake snake;
|
||||
|
||||
public static String getRandomHexColor() {
|
||||
float hue = random.nextFloat();
|
||||
// sat between 0.1 and 0.3
|
||||
float saturation = (random.nextInt(2000) + 1000) / 10000f;
|
||||
float luminance = 0.9f;
|
||||
Color color = Color.getHSBColor(hue, saturation, luminance);
|
||||
return '#' + Integer.toHexString(
|
||||
(color.getRGB() & 0xffffff) | 0x1000000).substring(1);
|
||||
}
|
||||
|
||||
|
||||
public static Location getRandomLocation() {
|
||||
int x = roundByGridSize(random.nextInt(PLAYFIELD_WIDTH));
|
||||
int y = roundByGridSize(random.nextInt(PLAYFIELD_HEIGHT));
|
||||
return new Location(x, y);
|
||||
}
|
||||
|
||||
|
||||
private static int roundByGridSize(int value) {
|
||||
value = value + (GRID_SIZE / 2);
|
||||
value = value / GRID_SIZE;
|
||||
value = value * GRID_SIZE;
|
||||
return value;
|
||||
}
|
||||
|
||||
public SnakeAnnotation() {
|
||||
this.id = snakeIds.getAndIncrement();
|
||||
}
|
||||
|
||||
|
||||
@OnOpen
|
||||
public void onOpen(Session session) {
|
||||
this.snake = new Snake(id, session);
|
||||
SnakeTimer.addSnake(snake);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator();
|
||||
iterator.hasNext();) {
|
||||
Snake snake = iterator.next();
|
||||
sb.append(String.format("{\"id\": %d, \"color\": \"%s\"}",
|
||||
Integer.valueOf(snake.getId()), snake.getHexColor()));
|
||||
if (iterator.hasNext()) {
|
||||
sb.append(',');
|
||||
}
|
||||
}
|
||||
SnakeTimer.broadcast(String.format("{\"type\": \"join\",\"data\":[%s]}",
|
||||
sb.toString()));
|
||||
}
|
||||
|
||||
|
||||
@OnMessage
|
||||
public void onTextMessage(String message) {
|
||||
if ("west".equals(message)) {
|
||||
snake.setDirection(Direction.WEST);
|
||||
} else if ("north".equals(message)) {
|
||||
snake.setDirection(Direction.NORTH);
|
||||
} else if ("east".equals(message)) {
|
||||
snake.setDirection(Direction.EAST);
|
||||
} else if ("south".equals(message)) {
|
||||
snake.setDirection(Direction.SOUTH);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@OnClose
|
||||
public void onClose() {
|
||||
SnakeTimer.removeSnake(snake);
|
||||
SnakeTimer.broadcast(String.format("{\"type\": \"leave\", \"id\": %d}",
|
||||
Integer.valueOf(id)));
|
||||
}
|
||||
|
||||
|
||||
@OnError
|
||||
public void onError(Throwable t) throws Throwable {
|
||||
// Most likely cause is a user closing their browser. Check to see if
|
||||
// the root cause is EOF and if it is ignore it.
|
||||
// Protect against infinite loops.
|
||||
int count = 0;
|
||||
Throwable root = t;
|
||||
while (root.getCause() != null && count < 20) {
|
||||
root = root.getCause();
|
||||
count ++;
|
||||
}
|
||||
if (root instanceof EOFException) {
|
||||
// Assume this is triggered by the user closing their browser and
|
||||
// ignore it.
|
||||
} else {
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||
* contributor license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright ownership.
|
||||
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||
* (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package websocket.snake;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import org.apache.juli.logging.Log;
|
||||
import org.apache.juli.logging.LogFactory;
|
||||
|
||||
/**
|
||||
* Sets up the timer for the multi-player snake game WebSocket example.
|
||||
*/
|
||||
public class SnakeTimer {
|
||||
|
||||
private static final Log log =
|
||||
LogFactory.getLog(SnakeTimer.class);
|
||||
|
||||
private static Timer gameTimer = null;
|
||||
|
||||
private static final long TICK_DELAY = 100;
|
||||
|
||||
private static final ConcurrentHashMap<Integer, Snake> snakes =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
protected static synchronized void addSnake(Snake snake) {
|
||||
if (snakes.size() == 0) {
|
||||
startTimer();
|
||||
}
|
||||
snakes.put(Integer.valueOf(snake.getId()), snake);
|
||||
}
|
||||
|
||||
|
||||
protected static Collection<Snake> getSnakes() {
|
||||
return Collections.unmodifiableCollection(snakes.values());
|
||||
}
|
||||
|
||||
|
||||
protected static synchronized void removeSnake(Snake snake) {
|
||||
snakes.remove(Integer.valueOf(snake.getId()));
|
||||
if (snakes.size() == 0) {
|
||||
stopTimer();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected static void tick() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator();
|
||||
iterator.hasNext();) {
|
||||
Snake snake = iterator.next();
|
||||
snake.update(SnakeTimer.getSnakes());
|
||||
sb.append(snake.getLocationsJson());
|
||||
if (iterator.hasNext()) {
|
||||
sb.append(',');
|
||||
}
|
||||
}
|
||||
broadcast(String.format("{\"type\": \"update\", \"data\" : [%s]}",
|
||||
sb.toString()));
|
||||
}
|
||||
|
||||
protected static void broadcast(String message) {
|
||||
for (Snake snake : SnakeTimer.getSnakes()) {
|
||||
try {
|
||||
snake.sendMessage(message);
|
||||
} catch (IllegalStateException ise) {
|
||||
// An ISE can occur if an attempt is made to write to a
|
||||
// WebSocket connection after it has been closed. The
|
||||
// alternative to catching this exception is to synchronise
|
||||
// the writes to the clients along with the addSnake() and
|
||||
// removeSnake() methods that are already synchronised.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void startTimer() {
|
||||
gameTimer = new Timer(SnakeTimer.class.getSimpleName() + " Timer");
|
||||
gameTimer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
tick();
|
||||
} catch (RuntimeException e) {
|
||||
log.error("Caught to prevent timer from shutting down", e);
|
||||
}
|
||||
}
|
||||
}, TICK_DELAY, TICK_DELAY);
|
||||
}
|
||||
|
||||
|
||||
public static void stopTimer() {
|
||||
if (gameTimer != null) {
|
||||
gameTimer.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user