final/src/GamePanel.java

224 lines
8.3 KiB
Java
Raw Normal View History

2022-05-30 19:46:53 +01:00
/* GamePanel class acts as the main "game loop" - continuously runs the game and calls whatever needs to be called
2022-05-30 19:36:18 +01:00
Child of JPanel because JPanel contains methods for drawing to the screen
Implements KeyListener interface to listen for keyboard input
Implements Runnable interface to use "threading" - let the game do two things at once
*/
import java.awt.*;
import java.awt.event.*;
2022-05-31 18:19:23 +01:00
import java.awt.image.BufferedImage;
import java.io.File;
2022-06-02 19:48:44 +01:00
import java.io.FileReader;
import java.io.FileWriter;
2022-06-02 19:48:16 +01:00
import java.io.FileNotFoundException;
2022-05-31 18:19:23 +01:00
import java.io.IOException;
import javax.imageio.ImageIO;
2022-05-31 18:19:41 +01:00
import java.util.ArrayList;
2022-06-02 19:48:44 +01:00
import java.util.Scanner;
2022-05-30 19:36:18 +01:00
import javax.swing.*;
public class GamePanel extends JPanel implements Runnable, KeyListener{
2022-05-30 19:46:53 +01:00
//dimensions of window
2022-06-02 18:33:04 +01:00
public static final int GAME_WIDTH = 1225;
public static final int GAME_HEIGHT = 630;
2022-05-30 19:46:53 +01:00
public Thread gameThread;
public Image image;
public Graphics graphics;
2022-05-31 18:19:23 +01:00
public Player player;
public BackgroundImage background;
2022-05-31 18:19:23 +01:00
public int frame;
// keeps track of how many ticks has elapsed since last frame change
public int frameCounter = 0;
public BufferedImage[][][] spriteArray = new BufferedImage[2][2][11];
2022-05-30 19:46:53 +01:00
2022-05-31 18:19:41 +01:00
public static ArrayList<Tile>map = new ArrayList<Tile>();
2022-05-30 19:46:53 +01:00
2022-06-02 18:21:29 +01:00
public static Camera camera;
// image imports begin here
public BufferedImage backgroundImage = getImage("img/backgrounds/pointyMountains.png");
public BufferedImage box = getImage("img/tiles/boxes/box.png");
public BufferedImage boxCoin = getImage("img/tiles/boxes/boxCoin.png");
public GamePanel() throws IOException, SpriteException {
2022-06-02 18:21:29 +01:00
camera = new Camera(0);
background = new BackgroundImage(0, 0, backgroundImage, GAME_WIDTH, GAME_HEIGHT);
2022-05-31 18:19:23 +01:00
for (int i = 0; i < 11; i++) {
try {
BufferedImage sprite = getImage(String.format("img/walk/p1_walk%s.png", String.format("%1$2s", i+1).replace(' ', '0')));
spriteArray[1][0][i] = sprite;
spriteArray[1][1][i] = sprite;
spriteArray[0][0][i] = flipImageHorizontally(sprite);
spriteArray[0][1][i] = flipImageHorizontally(sprite);
2022-05-31 18:19:23 +01:00
} catch (IOException e) {
e.printStackTrace();
}
}
2022-06-01 19:49:35 +01:00
player = new Player(GAME_WIDTH/2, GAME_HEIGHT/2, 'W', 'A', 'S', 'D', spriteArray); //create a player controlled player, set start location to middle of screenk
// the height of 35 is set because it is half of the original tile height (i.e., 70px)
map.add(new SingleTile(1000, 500, box, 35));
map.add(new SingleTile(700, 400, boxCoin, 35));
map.add(new SingleTile(1000, 300, boxCoin, 35));
2022-06-01 19:39:10 +01:00
map.add(new Tile(700, 200));
2022-05-30 19:46:53 +01:00
this.setFocusable(true); //make everything in this class appear on the screen
this.addKeyListener(this); //start listening for keyboard input
//add the MousePressed method from the MouseAdapter - by doing this we can listen for mouse input. We do this differently from the KeyListener because MouseAdapter has SEVEN mandatory methods - we only need one of them, and we don't want to make 6 empty methods
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
2022-05-31 18:19:23 +01:00
player.mousePressed(e);
2022-05-30 19:46:53 +01:00
}
});
this.setPreferredSize(new Dimension(GAME_WIDTH, GAME_HEIGHT));
//make this class run at the same time as other classes (without this each class would "pause" while another class runs). By using threading we can remove lag, and also allows us to do features like display timers in real time!
gameThread = new Thread(this);
gameThread.start();
}
//paint is a method in java.awt library that we are overriding. It is a special method - it is called automatically in the background in order to update what appears in the window. You NEVER call paint() yourself
public void paint(Graphics g){
//we are using "double buffering here" - if we draw images directly onto the screen, it takes time and the human eye can actually notice flashes of lag as each pixel on the screen is drawn one at a time. Instead, we are going to draw images OFF the screen, then simply move the image on screen as needed.
image = createImage(GAME_WIDTH, GAME_HEIGHT); //draw off screen
graphics = image.getGraphics();
2022-05-31 18:19:23 +01:00
draw(graphics, frame);//update the positions of everything on the screen
2022-05-30 19:46:53 +01:00
g.drawImage(image, 0, 0, this); //move the image on the screen
}
//call the draw methods in each class to update positions as things move
2022-05-31 18:19:23 +01:00
public void draw(Graphics g, int frame){
background.draw(g);
2022-05-31 18:19:23 +01:00
frameCounter += player.draw(g, frame);
2022-05-31 18:19:41 +01:00
for(Tile i: map){
i.draw(g);
}
2022-06-02 18:21:29 +01:00
g.drawString(camera.x+" "+map.get(0).x,100,100);
2022-05-30 19:46:53 +01:00
}
//call the move methods in other classes to update positions
//this method is constantly called from run(). By doing this, movements appear fluid and natural. If we take this out the movements appear sluggish and laggy
public void move(){
2022-05-31 18:19:23 +01:00
player.move();
2022-05-30 19:46:53 +01:00
}
//handles all collision detection and responds accordingly
2022-05-31 18:31:58 +01:00
public void checkCollision() {
player.isGrounded = false;
2022-05-31 18:19:41 +01:00
2022-05-31 18:31:58 +01:00
for (Tile i : map) {
2022-06-01 19:39:10 +01:00
i.collide(player);
2022-05-31 18:19:41 +01:00
}
2022-05-30 19:46:53 +01:00
//force player to remain on screen
2022-05-31 18:31:58 +01:00
if (player.y <= 0) {
2022-05-31 18:19:23 +01:00
player.y = 0;
2022-05-30 19:36:18 +01:00
}
2022-05-31 18:31:58 +01:00
if (player.y >= GAME_HEIGHT - Player.PLAYER_HEIGHT) {
2022-06-01 18:52:13 +01:00
player.y = GAME_HEIGHT - Player.PLAYER_HEIGHT;
2022-05-31 18:31:58 +01:00
player.yVelocity = 0;
player.isGrounded = true;
}
if (player.x <= 0) {
player.x = 0;
2022-06-01 19:39:10 +01:00
}
2022-05-31 18:31:58 +01:00
if (player.x <= 0) {
player.x = 0;
}
2022-06-01 18:52:13 +01:00
if (player.x + Player.PLAYER_WIDTH >= GAME_WIDTH) {
player.x = GAME_WIDTH - Player.PLAYER_WIDTH;
2022-05-31 18:31:58 +01:00
}
2022-05-30 19:36:18 +01:00
}
2022-06-01 19:39:10 +01:00
2022-05-30 19:46:53 +01:00
//run() method is what makes the game continue running without end. It calls other methods to move objects, check for collision, and update the screen
public void run(){
2022-06-03 17:22:05 +01:00
try {
MapReader.inputMap(map, "src/Level1.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
2022-05-30 19:46:53 +01:00
//the CPU runs our game code too quickly - we need to slow it down! The following lines of code "force" the computer to get stuck in a loop for short intervals between calling other methods to update the screen.
long lastTime = System.nanoTime();
double amountOfTicks = 60;
double ns = 1000000000/amountOfTicks;
double delta = 0;
long now;
while(true){ //this is the infinite game loop
now = System.nanoTime();
delta = delta + (now-lastTime)/ns;
lastTime = now;
//only move objects around and update screen if enough time has passed
if(delta >= 1){
move();
checkCollision();
2022-05-30 19:36:18 +01:00
repaint();
2022-06-01 19:48:46 +01:00
if (frameCounter > 5) {
2022-05-31 18:19:23 +01:00
// increment sprite image to be used and keeps it below 12
frame = (frame + 1) % 11;
2022-06-01 19:48:46 +01:00
frameCounter -= 5;
2022-05-31 18:19:23 +01:00
}
2022-05-30 19:46:53 +01:00
delta--;
}
2022-05-30 19:36:18 +01:00
}
2022-05-30 19:46:53 +01:00
}
2022-05-30 19:36:18 +01:00
2022-05-31 18:19:23 +01:00
//if a key is pressed, we'll send it over to the Player class for processing
2022-05-30 19:46:53 +01:00
public void keyPressed(KeyEvent e){
2022-05-31 18:19:23 +01:00
player.keyPressed(e);
2022-05-30 19:46:53 +01:00
}
2022-05-30 19:36:18 +01:00
2022-05-31 18:19:23 +01:00
//if a key is released, we'll send it over to the Player class for processing
2022-05-30 19:46:53 +01:00
public void keyReleased(KeyEvent e){
2022-05-31 18:19:23 +01:00
player.keyReleased(e);
2022-05-30 19:46:53 +01:00
}
2022-05-30 19:36:18 +01:00
2022-05-30 19:46:53 +01:00
//left empty because we don't need it; must be here because it is required to be overridded by the KeyListener interface
public void keyTyped(KeyEvent e){
2022-05-30 19:36:18 +01:00
2022-05-30 19:46:53 +01:00
}
2022-05-31 18:19:23 +01:00
public BufferedImage getImage(String imageLocation) throws IOException {
return ImageIO.read(new File(imageLocation));
}
public BufferedImage flipImageHorizontally(BufferedImage originalImage) {
BufferedImage flippedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
for (int x = 0; x < originalImage.getWidth(); x++) {
for (int y = 0; y < originalImage.getHeight(); y++) {
// -1 is added to prevent off-by-one errors
flippedImage.setRGB(x, y, originalImage.getRGB(originalImage.getWidth()-x-1, y));
}
}
return flippedImage;
}
2022-06-03 17:22:05 +01:00
public static void writeFile(String fileLocation, String writeString) throws IOException {
2022-06-02 19:48:44 +01:00
File newFile = new File(fileLocation);
FileWriter fileWriter = new FileWriter(newFile);
fileWriter.write(writeString);
fileWriter.close();
}
// will create file if it doesn't exist
2022-06-03 17:22:05 +01:00
public static String readFile(String fileLocation) throws IOException {
2022-06-02 19:48:44 +01:00
File newFile = new File(fileLocation);
if (newFile.createNewFile()) {
return null;
} else {
Scanner fileReader = new Scanner(newFile);
// using the delimiter \\Z reads the entire file at once
return fileReader.useDelimiter("\\Z").next();
}
}
2022-05-30 19:36:18 +01:00
}