PageRenderTime 51ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/spring-boot-samples/spring-boot-sample-websocket-tomcat/src/main/java/samples/websocket/tomcat/snake/SnakeWebSocketHandler.java

https://gitlab.com/perlilja/spring-boot
Java | 112 lines | 81 code | 14 blank | 17 comment | 9 complexity | 4a7349c84bb71bb2b3f210a34f56c7df MD5 | raw file
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package samples.websocket.tomcat.snake;
  18. import java.awt.Color;
  19. import java.util.Iterator;
  20. import java.util.Random;
  21. import java.util.concurrent.atomic.AtomicInteger;
  22. import org.springframework.web.socket.CloseStatus;
  23. import org.springframework.web.socket.TextMessage;
  24. import org.springframework.web.socket.WebSocketSession;
  25. import org.springframework.web.socket.handler.TextWebSocketHandler;
  26. public class SnakeWebSocketHandler extends TextWebSocketHandler {
  27. public static final int PLAYFIELD_WIDTH = 640;
  28. public static final int PLAYFIELD_HEIGHT = 480;
  29. public static final int GRID_SIZE = 10;
  30. private static final AtomicInteger snakeIds = new AtomicInteger(0);
  31. private static final Random random = new Random();
  32. private final int id;
  33. private Snake snake;
  34. public static String getRandomHexColor() {
  35. float hue = random.nextFloat();
  36. // sat between 0.1 and 0.3
  37. float saturation = (random.nextInt(2000) + 1000) / 10000f;
  38. float luminance = 0.9f;
  39. Color color = Color.getHSBColor(hue, saturation, luminance);
  40. return '#' + Integer.toHexString((color.getRGB() & 0xffffff) | 0x1000000)
  41. .substring(1);
  42. }
  43. public static Location getRandomLocation() {
  44. int x = roundByGridSize(random.nextInt(PLAYFIELD_WIDTH));
  45. int y = roundByGridSize(random.nextInt(PLAYFIELD_HEIGHT));
  46. return new Location(x, y);
  47. }
  48. private static int roundByGridSize(int value) {
  49. value = value + (GRID_SIZE / 2);
  50. value = value / GRID_SIZE;
  51. value = value * GRID_SIZE;
  52. return value;
  53. }
  54. public SnakeWebSocketHandler() {
  55. this.id = snakeIds.getAndIncrement();
  56. }
  57. @Override
  58. public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  59. this.snake = new Snake(this.id, session);
  60. SnakeTimer.addSnake(this.snake);
  61. StringBuilder sb = new StringBuilder();
  62. for (Iterator<Snake> iterator = SnakeTimer.getSnakes().iterator(); iterator
  63. .hasNext();) {
  64. Snake snake = iterator.next();
  65. sb.append(String.format("{id: %d, color: '%s'}",
  66. Integer.valueOf(snake.getId()), snake.getHexColor()));
  67. if (iterator.hasNext()) {
  68. sb.append(',');
  69. }
  70. }
  71. SnakeTimer
  72. .broadcast(String.format("{'type': 'join','data':[%s]}", sb.toString()));
  73. }
  74. @Override
  75. protected void handleTextMessage(WebSocketSession session, TextMessage message)
  76. throws Exception {
  77. String payload = message.getPayload();
  78. if ("west".equals(payload)) {
  79. this.snake.setDirection(Direction.WEST);
  80. }
  81. else if ("north".equals(payload)) {
  82. this.snake.setDirection(Direction.NORTH);
  83. }
  84. else if ("east".equals(payload)) {
  85. this.snake.setDirection(Direction.EAST);
  86. }
  87. else if ("south".equals(payload)) {
  88. this.snake.setDirection(Direction.SOUTH);
  89. }
  90. }
  91. @Override
  92. public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
  93. throws Exception {
  94. SnakeTimer.removeSnake(this.snake);
  95. SnakeTimer.broadcast(String.format("{'type': 'leave', 'id': %d}",
  96. Integer.valueOf(this.id)));
  97. }
  98. }