97 lines
2.1 KiB
Java
97 lines
2.1 KiB
Java
import java.util.Random;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.io.*;
|
|
import java.awt.*;
|
|
import java.awt.event.*;
|
|
import java.awt.Graphics;
|
|
import javax.swing.*;
|
|
|
|
public class Platformer extends JPanel implements KeyListener, ActionListener{
|
|
|
|
//finals
|
|
static final int GRAVITY = 10;
|
|
static final Color playerColor = Color.RED;
|
|
static final Color tileColor = Color.BLUE;
|
|
|
|
Player player;
|
|
ArrayList<Tile> tiles;
|
|
//display vars
|
|
int boardWidth;
|
|
int boardHeight;
|
|
int tileSize;
|
|
Timer gameTimer;
|
|
|
|
|
|
public Platformer(int boardWidth, int boardHeight, int tileSize){
|
|
//setup game
|
|
this.boardWidth = boardWidth;
|
|
this.boardHeight = boardHeight;
|
|
this.tileSize = tileSize;
|
|
setPreferredSize(new Dimension(this.boardWidth, this.boardHeight));
|
|
addKeyListener(this);
|
|
this.setFocusable(true);
|
|
gameTimer = new Timer(15,this);
|
|
player = new Player(20,20,20,20);
|
|
tiles = new ArrayList<>();
|
|
tiles.add(new Tile (0,300,tileSize * 20,tileSize));
|
|
}
|
|
|
|
//gameloop
|
|
public void gameLoop(){
|
|
player.moveY(GRAVITY);
|
|
}
|
|
|
|
//paintComponent
|
|
public void paintComponent(Graphics g){
|
|
super.paintComponent(g);
|
|
draw(g);
|
|
}
|
|
|
|
//draw function
|
|
public void draw(Graphics g){
|
|
|
|
//draw player
|
|
g.setColor(playerColor);
|
|
g.fillRect(player.x,player.y,player.width,player.height);
|
|
|
|
//draw tiles
|
|
g.setColor(tileColor);
|
|
for (Tile t : tiles){
|
|
t.draw(g);
|
|
}
|
|
}
|
|
|
|
//every tick
|
|
@Override
|
|
public void actionPerformed(ActionEvent e){
|
|
gameLoop();
|
|
repaint();
|
|
}
|
|
|
|
//check for key presses
|
|
@Override
|
|
public void keyPressed(KeyEvent e){
|
|
if (e.getKeyCode() == KeyEvent.VK_S){
|
|
gameTimer.start();
|
|
}
|
|
|
|
if (e.getKeyCode() == KeyEvent.VK_R){
|
|
gameTimer.stop();
|
|
player.x = 20;
|
|
player.y = 20;
|
|
repaint();
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void keyReleased(KeyEvent e){
|
|
|
|
}
|
|
|
|
//dont need
|
|
@Override
|
|
public void keyTyped(KeyEvent e){
|
|
|
|
}
|
|
} |