Ocelot5836

Main Game class

Sep 21st, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.09 KB | None | 0 0
  1. package com.ocelot.game;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.Canvas;
  5. import java.awt.Color;
  6. import java.awt.Cursor;
  7. import java.awt.Dimension;
  8. import java.awt.Graphics;
  9. import java.awt.Point;
  10. import java.awt.Toolkit;
  11. import java.awt.image.BufferStrategy;
  12. import java.awt.image.BufferedImage;
  13. import java.awt.image.DataBufferInt;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. import java.util.Random;
  17.  
  18. import javax.swing.JFrame;
  19. import javax.swing.UIManager;
  20.  
  21. import com.ocelot.game.audio.JukeBox;
  22. import com.ocelot.game.entities.Entity;
  23. import com.ocelot.game.entities.EntityBread;
  24. import com.ocelot.game.entities.EntityPlayer;
  25. import com.ocelot.game.entities.EntityProjectile;
  26. import com.ocelot.game.entities.EntityRabbit;
  27. import com.ocelot.game.entities.EntityTree;
  28. import com.ocelot.game.entities.EntityZombie;
  29. import com.ocelot.game.entities.PlayerMP;
  30. import com.ocelot.game.gfx.Font;
  31. import com.ocelot.game.gfx.Screen;
  32. import com.ocelot.game.gfx.SpriteColor;
  33. import com.ocelot.game.gfx.gui.Gui;
  34. import com.ocelot.game.gfx.gui.GuiGameOver;
  35. import com.ocelot.game.gfx.gui.GuiHotbar;
  36. import com.ocelot.game.gfx.gui.GuiInventory;
  37. import com.ocelot.game.gfx.gui.GuiLoading;
  38. import com.ocelot.game.gfx.gui.Hud;
  39. import com.ocelot.game.handlers.Cursors;
  40. import com.ocelot.game.handlers.InputHandler;
  41. import com.ocelot.game.handlers.WindowHandler;
  42. import com.ocelot.game.launcher.Configuration;
  43. import com.ocelot.game.launcher.Launcher;
  44. import com.ocelot.game.level.Level;
  45. import com.ocelot.game.level.tiles.Tile;
  46. import com.ocelot.game.net.GameClient;
  47. import com.ocelot.game.net.GameServer;
  48. import com.ocelot.game.net.packet.Packet00Login;
  49. import com.ocelot.game.utils.LoadingUtils;
  50. import com.ocelot.game.utils.Logger;
  51.  
  52. /**
  53. * @author Ocelot5836
  54. */
  55.  
  56. @SuppressWarnings("serial")
  57. public class Game extends Canvas implements Runnable {
  58.  
  59. public static final int WIDTH = 320;
  60. public static final int HEIGHT = WIDTH / 12 * 9;
  61. public static final int SCALE = 3;
  62.  
  63. private static Configuration config = new Configuration("settings");
  64.  
  65. public static boolean debug = false;
  66. public static int debugSelction = 1;
  67.  
  68. public int fps;
  69. public int updates;
  70. public static int score = 0;
  71. public static double maxUpdates = 60D;
  72. public static long sleeps = 3;
  73.  
  74. private static Toolkit toolkit = Toolkit.getDefaultToolkit();
  75. public static Cursor DefaultCursor;
  76. public static Cursor TyCursor;
  77.  
  78. private JFrame frame;
  79.  
  80. public static boolean paused = false;
  81. public boolean running = false;
  82.  
  83. public int tickCount = 0;
  84. public static int time = 0;
  85. public static int tileSelected = 0;
  86. public static int offTileSelected = 0;
  87.  
  88. public static int musicVolume = 0;
  89. public static int sfxVolume = 0;
  90.  
  91. private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
  92. private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
  93. private int[] colors = new int[6 * 6 * 6];
  94.  
  95. public static int cursorTileX;
  96. public static int cursorTileY;
  97. public static int cursorX;
  98. public static int cursorY;
  99.  
  100. private Screen screen;
  101. public Gui gui;
  102. public InputHandler input;
  103. public WindowHandler window;
  104. public Level level;
  105.  
  106. private static Launcher launcher;
  107.  
  108. public EntityPlayer player;
  109.  
  110. private GameClient socketClient;
  111. private GameServer socketServer;
  112.  
  113. public static List<EntityRabbit> rabbits;
  114. public static List<EntityZombie> zombies;
  115. public static List<EntityBread> breads;
  116.  
  117. public static int difficultySelection;
  118. public static int numRabbits;
  119. public static String worldName;
  120. public static String username;
  121. public static String ip;
  122. public static int port;
  123. public static boolean runServer;
  124.  
  125. public Game() {
  126. frame = new JFrame(Assets.NAME + " " + Assets.VERSION);
  127.  
  128. frame.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
  129. frame.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
  130. frame.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
  131.  
  132. frame.setCursor(Cursors.get(Launcher.selectedCursor));
  133.  
  134. frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  135. frame.setLayout(new BorderLayout());
  136.  
  137. frame.pack();
  138. frame.add(this, BorderLayout.CENTER);
  139.  
  140. frame.setResizable(false);
  141. frame.setLocationRelativeTo(null);
  142. frame.setVisible(true);
  143.  
  144. if (runServer)
  145. socketServer = new GameServer(this, port);
  146. socketClient = new GameClient(this, ip, port);
  147. }
  148.  
  149. public static Launcher getLauncherInstance() {
  150. if (launcher == null) {
  151. launcher = new Launcher();
  152. }
  153. return launcher;
  154. }
  155.  
  156. public void init() {
  157. int index = 0;
  158. for (int r = 0; r < 6; r++) {
  159. for (int g = 0; g < 6; g++) {
  160. for (int b = 0; b < 6; b++) {
  161. int rr = (r * 255 / 5);
  162. int gg = (g * 255 / 5);
  163. int bb = (b * 255 / 5);
  164.  
  165. colors[index++] = rr << 16 | gg << 8 | bb;
  166. }
  167. }
  168. }
  169.  
  170. JukeBox.init();
  171.  
  172. debug = debugSelction == 0 ? true : false;
  173.  
  174. screen = new Screen(WIDTH, HEIGHT);
  175. input = new InputHandler();
  176. window = new WindowHandler(this, frame);
  177. this.addFocusListener(input);
  178. this.addKeyListener(input);
  179. this.addMouseListener(input);
  180. this.addMouseMotionListener(input);
  181. this.addMouseWheelListener(input);
  182. frame.addWindowListener(window);
  183. frame.addWindowFocusListener(window);
  184. Level.name = worldName;
  185. level = new Level(this);
  186. Logger.init(this);
  187. Tile.init();
  188.  
  189. initMobs();
  190.  
  191. gui = new Gui(this, input, level, player);
  192. }
  193.  
  194. public void initMobs() {
  195.  
  196. player = new PlayerMP(level, this, 100, 100, input, username, null, -1);
  197. level.add(player);
  198. Packet00Login loginPacket = new Packet00Login(player.getUsername());
  199. if (socketServer != null) {
  200. socketServer.addConnection((PlayerMP) player, loginPacket);
  201. }
  202. loginPacket.writeData(socketClient);
  203.  
  204. rabbits = new ArrayList<EntityRabbit>();
  205. for (int i = 0; i < numRabbits; i++) {
  206. Random x = new Random();
  207. Random y = new Random();
  208. EntityRabbit temp = new EntityRabbit(level, this, x.nextInt(level.width * 8), y.nextInt(level.height * 8));
  209. rabbits.add(temp);
  210. }
  211.  
  212. breads = new ArrayList<EntityBread>();
  213. if (difficultySelection != 0) {
  214. for (int i = 0; i < 100; i++) {
  215. Random x = new Random();
  216. Random y = new Random();
  217. EntityBread temp = new EntityBread(level, x.nextInt(level.width * 8), y.nextInt(level.height * 8));
  218. breads.add(temp);
  219. }
  220. }
  221.  
  222. zombies = new ArrayList<EntityZombie>();
  223. int numMobRuns = 0;
  224. if (difficultySelection != 0) {
  225. if (difficultySelection == 1) {
  226. numMobRuns = 20;
  227. }
  228.  
  229. if (difficultySelection == 2) {
  230. numMobRuns = 40;
  231. }
  232.  
  233. if (difficultySelection == 3) {
  234. numMobRuns = 60;
  235. }
  236.  
  237. for (int i = 0; i < numMobRuns; i++) {
  238. Random x = new Random();
  239. Random y = new Random();
  240. EntityZombie temp = new EntityZombie(level, this, x.nextInt(level.width * 8), y.nextInt(level.height * 8));
  241. zombies.add(temp);
  242. }
  243. }
  244.  
  245. for (int i = 0; i < 50; i++) {
  246. Random x = new Random();
  247. Random y = new Random();
  248. if (level.getTile(x.nextInt(level.width * 8) / 8, y.nextInt(level.height * 8) / 8) == Tile.GRASS)
  249. level.add(new EntityTree(level, x.nextInt(level.width * 8), y.nextInt(level.height * 8)));
  250. }
  251.  
  252. for (EntityRabbit rabbit : rabbits) {
  253. level.add(rabbit);
  254. }
  255.  
  256. for (EntityZombie zombie : zombies) {
  257. level.add(zombie);
  258. }
  259.  
  260. for (EntityBread bread : breads) {
  261. level.add(bread);
  262. }
  263. }
  264.  
  265. public void start() {
  266. running = true;
  267. new Thread(this, "game").start();
  268.  
  269. if (runServer)
  270. socketServer.start();
  271. socketClient.start();
  272. }
  273.  
  274. public void stop() {
  275. Logger.info("Stopping...");
  276. if (level != null)
  277. level.save();
  278. running = false;
  279.  
  280. System.exit(0);
  281. }
  282.  
  283. public void run() {
  284. long lastTime = System.nanoTime();
  285. double nsPerTick = 1000000000D / maxUpdates;
  286.  
  287. int ticks = 0;
  288. int frames = 0;
  289.  
  290. long lastTimer = System.currentTimeMillis();
  291. double delta = 0;
  292.  
  293. init();
  294. requestFocus();
  295.  
  296. InputHandler.placing = false;
  297.  
  298. renderLoadingScreen();
  299. renderLoadingScreen();
  300.  
  301. JukeBox.load("/audio/music/music", "music");
  302.  
  303. JukeBox.load("/audio/sfx/gunshot", "fire");
  304. JukeBox.load("/audio/sfx/hurt", "hurt");
  305. JukeBox.load("/audio/sfx/pop", "pop");
  306. JukeBox.load("/audio/sfx/fart", "fart");
  307.  
  308. JukeBox.loop("music");
  309.  
  310. while (running) {
  311. long now = System.nanoTime();
  312. delta += (now - lastTime) / nsPerTick;
  313. lastTime = now;
  314.  
  315. while (delta >= 1) {
  316. ticks++;
  317. tick();
  318. delta -= 1;
  319. }
  320.  
  321. try {
  322. Thread.sleep(sleeps);
  323. } catch (InterruptedException e) {
  324. e.printStackTrace();
  325. }
  326.  
  327. frames++;
  328. render();
  329.  
  330. if (System.currentTimeMillis() - lastTimer >= 1000) {
  331. lastTimer += 1000;
  332. fps = frames;
  333. updates = ticks;
  334. level.save();
  335. frames = 0;
  336. ticks = 0;
  337. }
  338. }
  339. }
  340.  
  341. int index = 0;
  342.  
  343. public void tick() {
  344. time++;
  345.  
  346. JukeBox.setVolume("music", musicVolume - 50);
  347. if (musicVolume <= 0)
  348. JukeBox.stop("music");
  349.  
  350. for (String s : JukeBox.clips.keySet()) {
  351. JukeBox.setVolume(s, sfxVolume - 50);
  352. if (sfxVolume <= 0)
  353. JukeBox.stop(s);
  354. }
  355.  
  356. if (!paused) {
  357.  
  358. if (time % 60 == 0) {
  359. if (fps > 120) {
  360. sleeps++;
  361. }
  362.  
  363. if (fps < 110) {
  364. sleeps--;
  365. }
  366.  
  367. if (sleeps <= 0) {
  368. sleeps = 0;
  369. }
  370. }
  371.  
  372. tickCount++;
  373. if (!player.isRemoved()) {
  374. player.tick();
  375. level.tick();
  376. }
  377.  
  378. for (int i = 0; i < level.entities.size(); i++) {
  379. if (level.entities.get(i).isRemoved()) {
  380. level.entities.remove(i);
  381. i--;
  382. }
  383. }
  384.  
  385. for (int i = 0; i < level.projectiles.size(); i++) {
  386. if (level.projectiles.get(i).isRemoved()) {
  387. level.projectiles.remove(i);
  388. i--;
  389. }
  390. }
  391.  
  392. for (int i = 0; i < level.particles.size(); i++) {
  393. if (level.particles.get(i).isRemoved()) {
  394. level.particles.remove(i);
  395. i--;
  396. }
  397. }
  398.  
  399. if (!player.isRemoved())
  400. tileCheck();
  401. }
  402. }
  403.  
  404. private void tileCheck() {
  405. cursorTileX = ((screen.xOffset * SCALE) + InputHandler.mouseCX) / (SCALE * 8);
  406. cursorTileY = ((screen.yOffset * SCALE) + InputHandler.mouseCY) / (SCALE * 8);
  407. cursorX = ((screen.xOffset * SCALE) + InputHandler.mouseCX) / SCALE;
  408. cursorY = ((screen.yOffset * SCALE) + InputHandler.mouseCY) / SCALE;
  409.  
  410. if (InputHandler.mouseButton == 2)
  411. tileSelected = level.getTile(cursorTileX, cursorTileY).getId();
  412.  
  413. if (player.canEditTile(cursorTileX, cursorTileY) && InputHandler.placing && InputHandler.mouseButton == 1)
  414. level.alterTile(cursorTileX, cursorTileY, Tile.tiles[tileSelected]);
  415. }
  416.  
  417. public List<Entity> getEntities(Entity e, int radius) {
  418. List<Entity> result = new ArrayList<Entity>();
  419. double ex = (e.getX());
  420. double ey = (e.getY());
  421. for (int i = 0; i < level.entities.size(); i++) {
  422. Entity entity = level.entities.get(i);
  423. int x = ((int) entity.getX());
  424. int y = ((int) entity.getY());
  425.  
  426. double dx = Math.abs(x - ex);
  427. double dy = Math.abs(y - ey);
  428. double distance = Math.sqrt((dx * dx) + (dy * dy));
  429. if (distance <= radius)
  430. result.add(entity);
  431. }
  432. return result;
  433. }
  434.  
  435. public List<Entity> getEntity(Entity e, int radius) {
  436. List<Entity> entities = getEntities(e, radius);
  437. List<Entity> result = new ArrayList<Entity>();
  438. for (int i = 0; i < entities.size(); i++) {
  439. if (entities.get(i) == e)
  440. result.add(entities.get(i));
  441. }
  442. return result;
  443. }
  444.  
  445. public List<EntityProjectile> getProjectiles(Entity e, int radius) {
  446. List<EntityProjectile> result = new ArrayList<EntityProjectile>();
  447. double ex = (e.getX());
  448. double ey = (e.getY());
  449. for (int i = 0; i < level.projectiles.size(); i++) {
  450. EntityProjectile projectile = level.projectiles.get(i);
  451. int x = ((int) projectile.getProjectileX());
  452. int y = ((int) projectile.getProjectileY());
  453.  
  454. double dx = Math.abs(x - ex);
  455. double dy = Math.abs(y - ey);
  456. double distance = Math.sqrt((dx * dx) + (dy * dy));
  457. if (distance <= radius)
  458. result.add(projectile);
  459. }
  460. return result;
  461. }
  462.  
  463. public List<EntityPlayer> getPlayers(Entity e, int radius) {
  464. List<EntityPlayer> result = new ArrayList<EntityPlayer>();
  465. double ex = (e.getX());
  466. double ey = (e.getY());
  467. for (int i = 0; i < 1; i++) {
  468. EntityPlayer entity = player;
  469. int x = ((int) entity.getX());
  470. int y = ((int) entity.getY());
  471.  
  472. double dx = Math.abs(x - ex);
  473. double dy = Math.abs(y - ey);
  474. double distance = Math.sqrt((dx * dx) + (dy * dy));
  475. if (distance <= radius)
  476. result.add(entity);
  477. }
  478. return result;
  479. }
  480.  
  481. public void renderLoadingScreen() {
  482. BufferStrategy bs = getBufferStrategy();
  483. if (bs == null) {
  484. createBufferStrategy(3);
  485. return;
  486. }
  487. Graphics g = bs.getDrawGraphics();
  488.  
  489. GuiLoading loading = new GuiLoading();
  490. gui.add(loading);
  491. gui.renderGui(screen, loading);
  492.  
  493. for (int y = 0; y < screen.height; y++) {
  494. for (int x = 0; x < screen.width; x++) {
  495. int colorCode = screen.pixels[x + y * screen.width];
  496. if (colorCode < 255)
  497. pixels[x + y * WIDTH] = colors[colorCode];
  498. }
  499. }
  500.  
  501. g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
  502.  
  503. gui.renderGuiOverlays(screen, g);
  504.  
  505. g.dispose();
  506. Gui.guis.clear();
  507. bs.show();
  508. }
  509.  
  510. public void render() {
  511. BufferStrategy bs = getBufferStrategy();
  512. if (bs == null) {
  513. createBufferStrategy(3);
  514. return;
  515. }
  516. Graphics g = bs.getDrawGraphics();
  517.  
  518. int xOffset = ((int) player.x) - (screen.width / 2);
  519. int yOffset = ((int) player.y) - (screen.height / 2);
  520.  
  521. if (!player.isRemoved()) {
  522.  
  523. level.renderTiles(screen, xOffset, yOffset);
  524.  
  525. screen.render(cursorTileX * 8, cursorTileY * 8, screen.entitiesSheet, 1, new SpriteColor(-1, 000, -1, -1), 0x00, 1);
  526.  
  527. level.renderEntities(screen, this);
  528.  
  529. // gui.add(new HudTile());
  530.  
  531. if (input.inventory.isPressed()) {
  532. gui.add(new GuiInventory());
  533. paused = true;
  534. } else {
  535. paused = false;
  536. }
  537.  
  538. Font.render(Assets.VERSION, screen, screen.xOffset + (WIDTH - (Assets.VERSION.length() * 8)), screen.yOffset, new SpriteColor(-1, -1, -1, 000), 1);
  539.  
  540. /**
  541. * Rendering debug info
  542. */
  543. if (debug) {
  544. Font.render(fps + " Frames", screen, screen.xOffset, screen.yOffset + 16, new SpriteColor(-1, -1, -1, 000), 1);
  545. Font.render(updates + " Ticks", screen, screen.xOffset, screen.yOffset + 24, new SpriteColor(-1, -1, -1, 000), 1);
  546. Font.render("Debug Mode", screen, screen.xOffset, screen.yOffset + 32, new SpriteColor(-1, -1, -1, 000), 1);
  547. }
  548.  
  549. if (player.isHurting()) {
  550. Hud.render(screen, 0, 0, 1, new SpriteColor(-1, 555, 222, -1), 20);
  551. } else {
  552. Hud.render(screen, 0, 0, 1, new SpriteColor(-1, 111, 222, -1), 20);
  553. }
  554. Hud.render(screen, 0, 0, 0, new SpriteColor(-1, 200, 300, 433), player.getHealth());
  555.  
  556. Hud.render(screen, 0, 8, 3, new SpriteColor(-1, 111, 222, -1), 20);
  557. Hud.render(screen, 0, 8, 2, new SpriteColor(-1, 210, 300, 444), player.hunger);
  558. }
  559.  
  560. /**
  561. * if the player dies
  562. */
  563. if (player.isRemoved()) {
  564. gui.add(new GuiGameOver());
  565. JukeBox.stopAllSounds();
  566.  
  567. if (input.enter.isPressed()) {
  568. player.setMaxHealth(20);
  569. player.setHealth(20);
  570. player.hunger = 20;
  571. player.x = player.y = 160;
  572. score = 0;
  573. stop();
  574. }
  575. }
  576.  
  577. gui.add(new GuiHotbar());
  578.  
  579. gui.render(screen);
  580.  
  581. for (int y = 0; y < screen.height; y++) {
  582. for (int x = 0; x < screen.width; x++) {
  583. int colorCode = screen.pixels[x + y * screen.width];
  584. if (colorCode < 255)
  585. pixels[x + y * WIDTH] = colors[colorCode];
  586. }
  587. }
  588.  
  589. g.drawImage(image, 0, 0, WIDTH * SCALE, HEIGHT * SCALE, null);
  590.  
  591. g.setColor(Color.WHITE);
  592.  
  593. gui.renderGuiOverlays(screen, g);
  594.  
  595. g.dispose();
  596. bs.show();
  597. }
  598.  
  599. public static Configuration getConfig() {
  600. return config;
  601. }
  602.  
  603. public static void main(String[] args) {
  604. try {
  605. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  606. } catch (Exception e) {
  607. e.printStackTrace();
  608. }
  609.  
  610. config.loadSettings();
  611.  
  612. DefaultCursor = toolkit.createCustomCursor(LoadingUtils.loadImage("/cursor.png"), new Point(0, 0), "Cursor");
  613. TyCursor = toolkit.createCustomCursor(LoadingUtils.loadImage("/tyCursor.png"), new Point(0, 0), "TyCursor");
  614.  
  615. getLauncherInstance().start();
  616. }
  617. }
Add Comment
Please, Sign In to add comment