Advertisement
Guest User

Snakegame

a guest
Feb 3rd, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.92 KB | None | 0 0
  1. import java.awt.image.BufferStrategy;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. import java.applet.Applet;
  6. import java.awt.Graphics2D;
  7. import java.util.ArrayList;
  8. import java.util.Random;
  9.  
  10.  
  11.  
  12. public class SnakeGame extends JFrame implements KeyListener{
  13. final static int INGAME=1;
  14. final static int GAMEOVER=2;
  15. int currentState=INGAME;
  16. Canvas c;
  17. Button startButton, stopButton;
  18. boolean animationRunning = true;
  19. private BufferStrategy strategy;
  20. final static int CANVAS_WIDTH =950;
  21. final static int CANVAS_HEIGHT = 950;
  22. int speed, mouseX, mouseY;
  23. int fruitX, fruitY, fruitSize;
  24. int score = 0;
  25. int highscore =0;
  26. String playerwithhighscore = "";
  27. Random randomGen = new Random();
  28. ArrayList<Snake> snake = new ArrayList<Snake>();
  29. Snake player = new Snake();
  30. Fruit fruit = new Fruit();
  31. int FPS = 20 ;
  32.  
  33. public SnakeGame(){
  34. c = new Canvas();
  35. c.setSize(950, 950);
  36.  
  37. //restart();
  38.  
  39. // Add a window listner for close button
  40. this.addWindowListener(new WindowAdapter() {
  41. public void windowClosing(WindowEvent e) {
  42. System.exit(0);
  43. }
  44. });
  45.  
  46. c.addKeyListener(this);
  47. this.getContentPane().add(c, BorderLayout.CENTER);
  48. this.setTitle("Snake Game");
  49. this.pack();
  50. this.setVisible(true);
  51. c.createBufferStrategy(2);
  52. strategy = c.getBufferStrategy();
  53. do{
  54. try{
  55. FPS = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the speed of the snake between 10 and 30", "FPS"));
  56. }catch(NumberFormatException nfe){
  57. FPS=0;
  58. }
  59. }while(FPS<10 || FPS>30);
  60. restartGame();
  61. new AnimationThread(this);
  62.  
  63. }
  64.  
  65.  
  66.  
  67. public static void main(String s[]) {
  68. new SnakeGame();
  69.  
  70. }
  71. public double getDistance(double sx, double sy, double ex, double ey){
  72. double xdiff = sx-ex;
  73. double ydiff = sy-ey;
  74. return Math.sqrt((xdiff*xdiff)+(ydiff*ydiff));
  75. }
  76.  
  77. public int randomInteger(int min, int max){
  78. return min + (int)(Math.random() * ((max - min) + 1));
  79. }
  80.  
  81. public void collisionDetection(){
  82. if(player.x <= 0 || player.x >= c.getWidth() || player.y <= 0 || player.y >= c.getHeight()){
  83.  
  84. gameOver();
  85.  
  86. }
  87. double distance = getDistance (fruit.x,fruit.y, player.x, player.y);
  88. if(distance < 10){
  89. fruit.x = randomInteger(10, c.getWidth()-10);
  90. fruit.x=(fruit.x/10)*10;
  91. fruit.y = randomInteger(10, c.getHeight()-10);
  92. fruit.y=(fruit.y/10)*10;
  93. score++;
  94. snake.add(new Snake());
  95. }
  96.  
  97. for (int i = 0; i < snake.size(); i++) {
  98.  
  99. if ((player.x == snake.get(i).x) && player.y == snake.get(i).y) {
  100. gameOver();
  101. }
  102. }
  103.  
  104.  
  105. //if(fruit.x == player.x && fruit.y == player.y){
  106.  
  107. //}
  108. }
  109.  
  110.  
  111. public void gameOver(){
  112. if (score > highscore){
  113. highscore=score;
  114. playerwithhighscore = JOptionPane.showInputDialog(null, "You beat the highscore!", "Enter your name");
  115.  
  116. }
  117. currentState=GAMEOVER;
  118.  
  119. //score=0;
  120. }
  121.  
  122.  
  123. public void updateGame(){
  124. updateSnake();
  125. player.x += player.xdir;
  126.  
  127. player.y += player.ydir;
  128. collisionDetection();
  129. }
  130.  
  131. public void updateSnake(){
  132. int i=snake.size()-1;
  133. while (i > 0){
  134. snake.get(i).x = snake.get(i-1).x;
  135. snake.get(i).y = snake.get(i-1).y;
  136. i=i-1;
  137. }
  138. snake.get(0).x =player.x;
  139. snake.get(0).y =player.y;
  140. }
  141. public void keyTyped(KeyEvent e) { }
  142. public void keyReleased(KeyEvent e) { }
  143.  
  144. public void keyPressed(KeyEvent e) {
  145. char key = e.getKeyChar();
  146. if((key == 'W' || key == 'w') && player.ydir == 0){
  147. player.ydir=-Snake.SIZE;
  148. player.xdir=0;
  149. }else if((key == 'S' || key == 's') && player.ydir == 0){
  150. player.ydir=Snake.SIZE;
  151. player.xdir=0;
  152. }else if((key == 'A' || key == 'a') && player.xdir == 0){
  153. player.xdir=-Snake.SIZE;
  154. player.ydir=0;
  155. }else if((key == 'D' || key == 'd') && player.xdir == 0){
  156. player.xdir=Snake.SIZE;
  157. player.ydir=0;
  158. }else if ((key == 'r' || key == 'R') && currentState == GAMEOVER){
  159. restartGame();
  160. }
  161. }
  162.  
  163.  
  164. public void restartGame(){
  165. player.x = c.getHeight()/2;
  166. player.y = c.getHeight()/2;
  167. score=0;
  168. snake.clear();
  169. snake.add(new Snake());
  170. snake.add(new Snake());
  171. snake.add(new Snake());
  172. snake.add(new Snake());
  173. player.xdir=Snake.SIZE;
  174. player.ydir=0;
  175. currentState= INGAME;
  176. }
  177.  
  178.  
  179. public void updateCanvas(){
  180. Graphics2D g2= (Graphics2D)strategy.getDrawGraphics();
  181. g2.setColor(Color.pink);
  182. g2.fillRect(0,0,c.getWidth(), c.getHeight());
  183. g2.setColor(Color.red);
  184. for(int i=0; i<snake.size(); i++){
  185. g2.fillOval((int)snake.get(i).x-(Snake.SIZE/2),(int)snake.get(i).y-(Snake.SIZE/2),Snake.SIZE,Snake.SIZE);
  186. }
  187. g2.setColor(Color.blue);
  188. g2.fillOval((int)player.x-(Snake.SIZE/2),(int)player.y-(Snake.SIZE/2),Snake.SIZE,Snake.SIZE);
  189. g2.setColor (Color.black);
  190. if (currentState == GAMEOVER){
  191. g2.setColor (Color.blue);
  192. g2.drawString("Gameover, press 'R' to restart", 405,475);
  193. g2.drawString("This game was made by Anon", 405,500);
  194. System.out.println(" ");
  195. System.out.println("SHAME, You Died");
  196. System.out.println("Need to code in snake hitting itself");
  197. }
  198. g2.setColor(Color.green);
  199. g2.fillOval((int)fruit.x-(Fruit.SIZE/2),(int)fruit.y-(Fruit.SIZE/2),Fruit.SIZE,Fruit.SIZE);
  200.  
  201. g2.setColor(Color.red);
  202. g2.drawString("Score: " + score, 10,20);
  203. g2.setColor(Color.yellow);
  204. g2.drawString("Highscore: " + highscore , 100,20);
  205. g2.drawString("By: " + playerwithhighscore , 180,20);
  206.  
  207.  
  208. //}
  209. g2.dispose();
  210. strategy.show();
  211. Toolkit.getDefaultToolkit().sync();
  212. //}
  213. //}
  214. }
  215.  
  216. class Snake{
  217. int x=-20,y=-20,xdir=0,ydir=0;
  218. final static int SIZE=20;
  219. }
  220.  
  221. class Fruit{
  222. int x=50,y=50,xdir=0,ydir=0;
  223. final static int SIZE=20;
  224. }
  225.  
  226.  
  227.  
  228. class AnimationThread extends Thread{
  229. SnakeGame at;
  230.  
  231. public AnimationThread(SnakeGame _at){
  232. at=_at;
  233. start();
  234. }
  235. public void run(){
  236.  
  237. int SKIP_TICKS = 1000 / FPS;
  238. long next_game_tick = System.currentTimeMillis();
  239. long sleep_time = 0;
  240. while(true){
  241. if(animationRunning){
  242. if(currentState == INGAME){
  243. updateGame();
  244. at.updateCanvas();
  245. next_game_tick += SKIP_TICKS;
  246. sleep_time = next_game_tick - System.currentTimeMillis();
  247. if(sleep_time >= 0 ) {
  248. try{
  249. sleep(sleep_time);
  250. }catch(InterruptedException ie){}
  251. if(player.x >= 950){
  252. currentState = GAMEOVER;
  253. player.x = 20;
  254. }
  255.  
  256.  
  257. System.out.print("Snake: ");
  258. System.out.print(player.x);
  259. System.out.print(", ");
  260. System.out.println(player.y);
  261. System.out.print("Fruit: ");
  262. System.out.print(fruit.x);
  263. System.out.print(", ");
  264. System.out.println(fruit.y);
  265. System.out.print("Score");
  266. System.out.println(score);
  267. }else{
  268. next_game_tick = System.currentTimeMillis();
  269. }
  270. }
  271. }
  272. }
  273. }
  274. }
  275. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement