Advertisement
erzis

Untitled

Dec 1st, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. package com.game.main;
  2.  
  3. import java.awt.Canvas;
  4. import java.awt.Color;
  5. import java.awt.Graphics;
  6. import java.awt.image.BufferStrategy;
  7.  
  8. public class Game extends Canvas implements Runnable{
  9.  
  10. private static final long serialVersionUID = -473349850293143017L;
  11.  
  12. public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
  13.  
  14. private Thread thread;
  15. private boolean running = false;
  16.  
  17. public Game() {
  18. new Window(WIDTH, HEIGHT, "Snake", this);
  19. }
  20.  
  21. public synchronized void start() {
  22. thread = new Thread(this);
  23. thread.start();
  24. running = true;
  25. }
  26.  
  27. public synchronized void stop() {
  28. try{
  29. thread.join();
  30. running = false;
  31. }catch(Exception e) {
  32. e.printStackTrace();
  33. }
  34. }
  35.  
  36. public void run() {
  37. long lastTime = System.nanoTime();
  38. double amountOfTicks = 60.0;
  39. double ns = 1000000000 / amountOfTicks;
  40. double delta = 0;
  41. long timer = System.currentTimeMillis();
  42. int frames = 0;
  43. while(running) {
  44. long now = System.nanoTime();
  45. delta += (now - lastTime) / ns;
  46. lastTime = now;
  47. while(delta >= 1) {
  48. tick();
  49. delta--;
  50. }
  51. if(running)
  52. render();
  53. frames++;
  54.  
  55. if(System.currentTimeMillis() - timer > 1000) {
  56. timer+= 1000;
  57. System.out.println("FPS: " + frames);
  58. frames = 0;
  59. }
  60. }
  61. stop();
  62. }
  63.  
  64. private void tick() {
  65.  
  66. }
  67.  
  68. private void render() {
  69. BufferStrategy bs = this.getBufferStrategy();
  70. if(bs == null) {
  71. this.createBufferStrategy(3);
  72. return;
  73. }
  74.  
  75. Graphics g = bs.getDrawGraphics();
  76.  
  77. g.setColor(Color.black);
  78. g.fillRect(0, 0, WIDTH, HEIGHT);
  79.  
  80. g.dispose();
  81. bs.show();
  82. }
  83.  
  84. public static void main(String args[]) {
  85. new Game();
  86. }
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement