java applet game jumping - java

I'm quite new with Java and at the moment I'm making a super meat boy kinda game but I just can't figure out how to make him jump.
Here is the code I have so far, can anyone please describe me how to make him jump? Thanks.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
public class meatboy extends Applet implements KeyListener{
public int x = 10, y = 300, gravity = 3;
public int xs = 380, ys = 230;
double jumptime = 0;
public boolean right, left, up, jump, start, grounded;
public void init(){
setSize(800,400);
setBackground(Color.black);
addKeyListener(this);
/////Movement//////
Timer t = new Timer();
t.schedule(new TimerTask(){public void run(){
if (start == true){
if (right == true){
x = x + 3;
}if (left == true){
x = x - 3;
}if(up == true && grounded == true){
while(jumptime < 50){
y--;
jumptime = jumptime + 0.5;
}
grounded = false;
jumptime = 0;
}
/////GRAVITY//////
y = y + gravity;
///////Collision Dectection/////
if(x > 790){//right of screen stop
x = 10;
}if(x < 10){// left stop
x = 789;
}if(y > 352){
y = y - 3;
grounded = true;
}
////////////End of collision///////////
repaint();
}}},10,10);
///////movement end////////
}
public void paint(Graphics g){
////////CREATES MEATBOY///////////////
if (start == false){
x = 10;
y = 300;
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 800, 400);
g.setColor(Color.white);
g.drawString("MeatBoy 4K", 358, 180);
g.drawString("Press Z to start!!!!", 350, 200);
g.setColor(Color.RED);
g.fillRect(xs, ys, 16, 16);//meatboys body
g.fillRect(xs + 16, ys + 6, 4, 4);//arm
g.fillRect(xs - 4, ys + 6, 4, 4);//arm
g.fillRect(xs, ys + 12, 4, 6);//leg
g.fillRect(xs + 12, ys + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(xs + 2, ys + 2, 5, 5);//eye
g.fillRect(xs + 10, ys + 2, 5, 5);//eye
}
if (start == true){
g.setColor(Color.RED);
g.fillRect(x, y, 16, 16);//meatboys body
g.fillRect(x + 16, y + 6, 4, 4);//arm
g.fillRect(x - 4, y + 6, 4, 4);//arm
g.fillRect(x, y + 12, 4, 6);//leg
g.fillRect(x + 12, y + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(x + 2, y + 2, 5, 5);//eye
g.fillRect(x + 10, y + 2, 5, 5);//eye
///////////END OF MEATBOY//////////////////
////////Creates Floor///////////////////
g.setColor(Color.GRAY);
g.fillRect(0, 370, 800, 30);
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_Z){
//right = true;
start = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = true;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = true;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = true;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = false;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = false;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = false;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = false;
}
}
public void keyTyped(KeyEvent e) {
}
}

When you jump you make a vertical change of 1 (up), however, your gravity makes a vertical change of -3 (down) and if getting too far down you reset the vertical position to ground level.
What you need to do is compensate for gravity when "jumping" and one way of doing it would be to use
while(jumptime < 50){
y -= 1 + gravity;
jumptime = jumptime + 0.5;
}

Related

Move game screen diagonally using arrow keys

I'm creating a car game where it creates a 3D pseudo effect by moving the screen backwards and the car itself just stays still on the map, using the arrow keys. It only takes in one input at a time, meaning you have to let go of an arrow key first. I have some code that I've got to show what I'm aiming for the screen to do as well, as the screen only moves forwards, backwards, left, and right.
Example of what I want the screen to do:
public class Main extends JFrame {
private static final long serialVersionUID = 7722803326073073681L;
private boolean left = false;
private boolean up = false;
private boolean down = false;
private boolean right = false;
public JLabel lbl = new JLabel ("mn");
public Main() {
// Just setting up the window and objects
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
lbl.setBounds(100, 100, 20, 20);
add(lbl);
setLocationRelativeTo(null);
// Key listener, will not move the JLabel, just set where to
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) left = false;
if (e.getKeyCode() == KeyEvent.VK_RIGHT) right = false;
if (e.getKeyCode() == KeyEvent.VK_UP) up = false;
if (e.getKeyCode() == KeyEvent.VK_DOWN) down = false;
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) left = true;
if (e.getKeyCode() == KeyEvent.VK_RIGHT) right = true;
if (e.getKeyCode() == KeyEvent.VK_UP) up = true;
if (e.getKeyCode() == KeyEvent.VK_DOWN) down = true;
}
});
// This thread will read the 4 variables left/right/up/down at every 30 milliseconds
// It will check the combination of keys (left and up, right and down, just left, just up...)
// And move the label 3 pixels
new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
if (left && up) {
lbl.setBounds(lbl.getX() - 10, lbl.getY() - 10, 20, 20);
} else if (left && down) {
lbl.setBounds(lbl.getX() - 10, lbl.getY() + 10, 20, 20);
} else if (right && up) {
lbl.setBounds(lbl.getX() + 10, lbl.getY() - 10, 20, 20);
} else if (right && down) {
lbl.setBounds(lbl.getX() + 10, lbl.getY() + 10, 20, 20);
} else if (left) {
lbl.setBounds(lbl.getX() - 10, lbl.getY(), 20, 20);
} else if (up) {
lbl.setBounds(lbl.getX(), lbl.getY() - 10, 20, 20);
} else if (right) {
lbl.setBounds(lbl.getX() + 10, lbl.getY(), 20, 20);
} else if (down) {
lbl.setBounds(lbl.getX(), lbl.getY() + 10, 20, 20);
}
Thread.sleep(30);
}
} catch (Exception ex) {
ex.printStackTrace();
System.exit(0);
}
}
}).start();
}
public static void main(String[] args) {
new Main();
}
}
However, since the code above only moves the letters, I'm having a lot of difficulty in implementing it in the game as well. This is what I'm currently using to move the screen. (If I were to delete this method, nothing would appear).
What is currently happening:
public class RoadAppMain extends JFrame {
private static final int D_W = 1920; //Window dimension
private static final int D_H = 1280; //Window height
int grassWidth = 1920; //Width of grass
int vanishHeight = 768; // Height of vanishing point
int roadWidth = 900; //Width of the road
int rumbleLen = 800; //Length of each track stripe
double camDist = 0.8; //Camera distance
int N; //Size of each row or line
int playerPosX = 0; //Movement of player left and right
int playerPosY = 0; //Movement of player up and down
List<Line> lines = new ArrayList<RoadAppMain.Line>();
List<Integer> listValues = new ArrayList<Integer>();
DrawPanel drawPanel = new DrawPanel();
public RoadAppMain() {
for (int i = 0; i < 1600; i++) {
Line line = new Line();
line.z = i * rumbleLen;
int curveAngle = (int) (Math.random() * 15 + 1);
if (i > 20 && i < 70) {
line.curve = curveAngle;
}
else if (i > 100 && i < 150) {
line.curve = -curveAngle;
}
else if (i > 180 && i < 230) {
line.curve = curveAngle;
}
else if (i > 260 && i < 310) {
line.curve = -curveAngle;
}
else if (i > 340 && i < 390) {
line.curve = curveAngle;
}
else if (i > 400 && i < 420) {
}
lines.add(line);
}
N = lines.size();
//Handles action events by user
ActionListener listener = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
drawPanel.repaint();
}
};
Timer timer = new Timer(1, listener);
timer.start();
add(drawPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
//Moves screen using arrow keys - THIS IS THE PART IM TALKING ABOUT
private class DrawPanel extends JPanel {
public DrawPanel() {
String VK_LEFT = "VK_LEFT";
KeyStroke W = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW); //necessary
inputMap.put(W, VK_LEFT);
ActionMap actionMap = getActionMap(); //necessary
actionMap.put(VK_LEFT, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosX -= 200;
drawPanel.repaint();
}
});
String VK_RIGHT = "VK_RIGHT";
KeyStroke WVK_RIGHT = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
inputMap.put(WVK_RIGHT, VK_RIGHT);
actionMap.put(VK_RIGHT, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosX += 200;
drawPanel.repaint();
}
});
String VK_UP = "VK_UP";
KeyStroke WVK_UP = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
inputMap.put(WVK_UP, VK_UP);
actionMap.put(VK_UP, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosY += 200;
drawPanel.repaint();
}
});
String VK_DOWN = "VK_DOWN";
KeyStroke WVK_DOWN = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
inputMap.put(WVK_DOWN, VK_DOWN);
actionMap.put(VK_DOWN, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosY -= 200;
drawPanel.repaint();
}
});
}
//Drawing components feature
protected void paintComponent(Graphics g) {
drawValues(g);
g.setColor(Color.black);
g.fillRect(0, 0, 1920, 395);
}
}
private void drawValues(Graphics g) {
int startPos = playerPosY / rumbleLen;
double x = 0; //Initial X position of screen on road
double dx = 0; //Correlation between the angle of the road and player
double maxY = vanishHeight;
int camH = 1700 + (int) lines.get(startPos).y; //Height of the camera
//Starting position
for (int n = startPos; n < startPos + 300; n++) {
Line l = lines.get(n % N); //Position of line
l.project(playerPosX - (int) x, camH, playerPosY);
x += dx;
dx += l.curve;
if (l.Y > 0 && l.Y < maxY) {
maxY = l.Y;
Color grass = ((n / 2) % 2) == 0 ? new Color(21, 153, 71) : new Color(22, 102, 52); //Color for grass (first is for lighter, second for darker)
Color rumble = ((n / 2) % 2) == 0 ? new Color(255, 255, 255) : new Color(222, 4, 4); // Color for rumble (first is white, second is red)
Color road = new Color(54, 52, 52); // Color of road or asphalt
Color midel = ((n / 2) % 2) == 0 ? new Color(255, 255, 255) : new Color(54, 52, 52); //Color of hashed lines (first for white lines, second for gap)
Color car = new Color(104, 104, 104);
Color tire = new Color(0, 0, 0);
Color stripe = new Color(0, 0, 0);
Color light = new Color(253, 0, 0);
Color hood = new Color(0, 0, 0);
Color frame = new Color(0,0,255);
Line p = null;
if (n == 0) {
p = l;
} else {
p = lines.get((n - 1) % N);
}
draw(g, grass, 0, (int) p.Y, grassWidth, 0, (int) l.Y, grassWidth); //(Graphics g, Color c, int x1, int y1, int w1, int x2, int y2, int w2)
draw(g, rumble, (int) p.X, (int) p.Y, (int) (p.W * 2.03), (int) l.X, (int) l.Y, (int) (l.W * 2.03)); //Affects width of rumble
draw(g, road, (int) p.X, (int) p.Y, (int) (p.W * 1.8), (int) l.X, (int) l.Y, (int) (l.W * 1.8));
draw(g, midel, (int) p.X, (int) p.Y, (int) (p.W * 0.78), (int) l.X, (int) l.Y, (int) (l.W * 0.78)); //ADD HERE
draw(g, road, (int) p.X, (int) p.Y, (int) (p.W * 0.7), (int) l.X, (int) l.Y, (int) (l.W* 0.7)); //To cover the gap in between each midel. Must be after to allow it to colour over it
draw(g, car, 965, 927, 125, 965, 1005, 125);
draw(g, tire, 875, 1005, 35, 875, 1050, 35);
draw(g, tire, 1055, 1005, 35, 1055, 1050, 35);
draw(g, stripe, 1050, 965, 30, 870, 980, 30);
draw(g, stripe, 1050, 950, 30, 870, 965, 30);
draw(g, hood, 965, 880, 90, 965, 927, 125);
draw(g, light, 875, 950, 5, 875, 980, 5);
draw(g, light, 890, 950, 5, 890, 980, 5);
draw(g, light, 905, 950, 5, 905, 980, 5);
draw(g, light, 1025, 950, 5, 1025, 980, 5);
draw(g, light, 1040, 950, 5, 1040, 980, 5);
draw(g, light, 1055, 950, 5, 1055, 980, 5);
draw(g, frame, 965, 874, 86, 965, 880, 90);
draw(g, light, 965, 874, 35, 965, 880, 45);
}
}
}
void draw(Graphics g, Color c, int x1, int y1, int w1, int x2, int y2, int w2) {
Graphics g9d = g;
int[] x9Points = { x1 - w1, x2 - w2, x2 + w2, x1 + w1 };
int[] y9Points = { y1, y2, y2, y1 };
int n9Points = 4;
g9d.setColor(c);
g9d.fillPolygon(x9Points, y9Points, n9Points);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new RoadAppMain();
}
});
}
class Line {
double x, y, z;
double X, Y, W;
double scale, curve;
public Line() {
curve = x = y = z = 0;
}
void project(int camX, int camY, int camZ) {
scale = camDist / (z - camZ);
X = (1 + scale * (x - camX)) * grassWidth / 2;
Y = (1 - scale * (y - camY)) * vanishHeight / 2;
W = scale * roadWidth * grassWidth / 2;
}
}
}
How could I implement that movement into my game as well?

How to fix this NullPointerException from my Platformer Game?

I am trying to make a Platformer game where you can run around and jump off the base of rectangles and off the sides of them.
I am compiling this in Processing 2.2.1. The program does not run. I am also looking for help on how to implement a jump and when to change the character's image.
speed = 0;
int numrects = 9;
Player player1 = new Player();
//Rectangle[] platforms = new Rectangle[16];
public static Rectangle[] platforms = new Rectangle[16];
class Player{
PImage[] images = new PImage[10];
int xMove, yMove, xSpeed, ySpeed, gravity, jumpheight, xSize, ySize;
boolean a = true;
boolean d = true;
boolean w = true;
int x, y;
int numFrames = 7; // The number of animation frames
int frame = 0; // The frame to display
PImage img;
Player (){
xSpeed = 10;
ySpeed = 10;
xSize = 24;
ySize = 51;
x = width/2;
y = height/2;
}
void jump() {
for (int x = 0; x <= jumpheight; x++){
y = y + gravity;
image(images[frame], x, y);
}
for (int x = 0; x <= jumpheight; x++){
y = y - gravity;
image(images[frame], x, y);
}
}
};
class Rectangle{
int x, y, xSize, ySize;
//.fill(127);
Rectangle(){
x = 1;
y = 1;
xSize = 10;
ySize = 10;
}
void build(int newx, int newy, int newxSize, int newySize){
x = newx;
y = newy;
xSize = newxSize;
ySize = newySize;
rect (x, y, xSize, ySize);
}
};
void setup() {
size(1920, 1080);
frameRate(30);
player1.images[0] = loadImage("Staticl.png");
player1.images[3] = loadImage("Staticr.png");
player1.images[1] = loadImage("step1left.png");
player1.images[4] = loadImage("step1right.png");
player1.images[2] = loadImage("step2left.png");
player1.images[5] = loadImage("step2right.png");
//images[3] = loadImage("1.jpg");
//images[7] = loadImage("2.jpg");
player1.xSpeed = 10;
player1.x = 500;
player1.y = 500;
platforms[0].build(0, 837, 1920, 244);
platforms[1].build(0, 765, 294, 23);
platforms[2].build(733, 725, 734, 39);
platforms[3].build(0, 765, 294, 23);
platforms[4].build(0, 765, 294, 23);
platforms[5].build(1306, 569, 161, 195);
platforms[6].build(558, 607, 653, 33);
platforms[7].build(0, 522, 496, 34);
platforms[8].build(477, 360, 173, 37);
platforms[9].build(690, 288, 445, 34);
platforms[10].build(1149, 174, 217, 40);
platforms[11].build(1390, 298, 243, 33);
platforms[12].build(1488, 490, 167, 30);
platforms[13].build(1690, 301, 138, 31);
platforms[14].build(1693, 426, 227, 27);
platforms[15].build(1866, 226, 54, 199);
}
void checkforcollision(){
for (int x = 0; x <= numrects; x++){
if (player1.x + player1.xSize == platforms[x].x && player1.y <= platforms[x].y + platforms[x].ySize && player1.y + player1.ySize >= platforms[x].y){
// right side of box hits left side of platform
player1.d = false;
player1.w = true;
}
else if(player1.x == platforms[x].x + platforms[x].xSize && player1.y <= platforms[x].y + platforms[x].ySize && player1.y + player1.ySize >= platforms[x].y){
// left side of box hits right side of platform
player1.a = false;
player1.w = true;
}
else if(player1.y + player1.ySize == platforms[x].y && player1.x <= platforms[x].x + platforms[x].xSize && player1.x + player1.xSize >= platforms[x].x){
// bottom of player hits top of box
player1.w = false;
}
else if(player1.y == platforms[x].y + platforms[x].ySize && player1.x <= platforms[x].x + platforms[x].xSize && player1.x + player1.xSize >= platforms[x].x){
// top of player hits bottom of box
player1.w = true;
player1.a = true;
player1.d = true;
}
else {
player1.w = false;
player1.a = true;
player1.d = true;
}
}
}
void draw() {
checkforcollision();
if (player1.d == true)
player1.x = player1.x + player1.xSpeed;
image(player1.images[player1.frame], player1.x, player1.y);
if (player1.a == true)
player1.x = player1.x - player1.xSpeed;
image(player1.images[player1.frame], player1.x, player1.y);
if (player1.w == true)
player1.jump();
//image(images[frame], player1.x, player1.y);
}
void keyPressed() {
if ((key == 'a') || (key == 'A')){
player1.a = true;
}
else if ((key == 'd') || (key == 'D')){
player1.d = true;
}
else if ((key == 'w') || (key == 'W')){
player1.w = true;
}
}
void keyReleased() {
if ((key == 'a') || (key == 'A')){
player1.a = false;
}
else if ((key == 'd') || (key == 'D')){
player1.d = false;
}
}
The NullPointerException is because you haven't initialized the Rectangles in the array yet. So this line causes an error:
platforms[0].build(0, 837, 1920, 244);
First, you need to run something like this:
for (int i=0; i<platforms.length; i++) {
platforms[i] = new Rectangle();
}

Incorporating random maze generation into my game (Java)

I am currently making a maze solving game in Java, and I am currently running into a snag. All of the random maze generation algorithms that I could find output in a way that I couldn't figure out how to implement into my current code. I was considering using the Depth First Search, Recursive Backtracker, or Prim's Algorithm, since I thought they would be the easiest to implement while still generating good mazes. What would be a working use of one of those algorithms that works with my current program? This is my Game Class: (Feel free to point out any bad practices as well, I am pretty new to Java)
package game;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Game extends JPanel implements ActionListener, KeyListener {
private boolean upPressed = false;
private boolean downPressed = false;
private boolean rightPressed = false;
private boolean leftPressed = false;
private final int playerDiam = 100;
private final int playerSpeed = 15;
private final int tileSize = 400;
private int[][] maze = {{1, 1, 1, 1, 1, 1},
{1, 2, 1, 1, 3, 1},
{1, 0, 1, 0, 0, 1},
{1, 0, 1, 0, 1, 1},
{1, 0, 0, 0, 1, 1},
{1, 1, 1, 1, 1, 1},
};
private int[][] initX = new int[maze.length][maze.length];
private int[][] initY = new int[maze.length][maze.length];
private int deltaX = -210;
private int deltaY = -210;
private String screen = "menu";
public Game() {
setFocusable(true);
addKeyListener(this);
setUpInitialCoordinates();
Timer timer = new Timer(1000 / 60, this);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
tick();
}
private void setUpInitialCoordinates() {
int x = 0;
int y;
for (int[] rowData : maze) {
y = 0;
for (int ignored : rowData) {
initX[x][y] = x * tileSize;
initY[x][y] = y * tileSize;
y++;
}
x++;
}
}
private void generateMaze() {
}
private void tick() {
if (screen.equals("playing")) {
if (upPressed) {
deltaY += playerSpeed;
} else if (downPressed) {
deltaY -= playerSpeed;
}
if (rightPressed) {
deltaX -= playerSpeed;
} else if (leftPressed) {
deltaX += playerSpeed;
}
}
repaint();
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_W) {
upPressed = true;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_S) {
downPressed = true;
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) {
rightPressed = true;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) {
leftPressed = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if (screen.equals("menu") && e.getKeyCode() == KeyEvent.VK_ENTER) {
upPressed = false;
downPressed = false;
rightPressed = false;
leftPressed = false;
screen = "playing";
} else if (screen.equals("playing")) {
if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_W) {
upPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_S) {
downPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D) {
rightPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A) {
leftPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_P) {
screen = "paused";
}
} else if (screen.equals("paused" ) && e.getKeyCode() == KeyEvent.VK_P) {
upPressed = false;
downPressed = false;
rightPressed = false;
leftPressed = false;
screen = "playing";
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(new Font("Aharoni", Font.PLAIN, 36));
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
switch (screen) {
case "menu":
g.setColor(Color.BLACK);
g.drawString("Labyrinth", 300, 200);
g.drawString("Press Enter to Play!", getWidth() / 3, 500);
break;
case "playing":
int x = 0;
int y = 0;
for (int[] rowData : maze) {
for (int cellData : rowData) {
if (cellData == 1) {
g.setColor(Color.DARK_GRAY);
g.fillRect(x + deltaX, y + deltaY, tileSize, tileSize);
} else if (cellData == 2) {
g.setColor(Color.GREEN);
g.fillRect(x + deltaX, y + deltaY, tileSize, tileSize);
} else if (cellData == 3) {
g.setColor(Color.YELLOW);
g.fillRect(x + deltaX, y + deltaY, tileSize, tileSize);
}
x += tileSize;
if (x == maze.length * tileSize) {
x = 0;
y += tileSize;
}
}
} g.setColor(Color.RED);
g.fillOval(getWidth() / 2, getHeight() / 2, playerDiam, playerDiam);
break;
case "gameOver":
g.setColor(Color.BLACK);
g.drawString("Game Over",getWidth() / 3 ,50 );
break;
case "paused":
g.setColor(Color.BLACK);
g.drawString("Paused", getWidth() / 3, 50);
break;
}
}
}
as start I would
clear maze
randomly add walls
create random path for all entry/exit points pairs present
clear the maze cells along them.
If you just need maze solver (some algos for maze generation needs them)
then look here How to speed up A* algorithm at large spatial scales?
with use of solver you can change algorithm to
clear maze
add random wall
if adding it still provides solution
loop bullet(2) N times
You need to be careful about how to add the walls
for example if you add just simple lines then the maze will look like this:
This is the code for it (uses the class from linked answer)
// generate random maze with path from x0,y0 to x1,y1 present, n walls
void A_star::generate(int x0,int y0,int x1,int y1,int n)
{
int x,y,i,j,dx,dy,l,*p;
// [clear map]
for (y=0;y<ys;y++)
for (x=0;x<xs;x++)
map[y][x]=A_star_space;
// temp space
p=new int [xs>>1]; if (p==NULL) return;
// generate n walls
for (i=0;i<n;i++)
{
// random start pos,dir,length
x =Random(xs);
y =Random(ys);
dx=Random(4);
l =Random(xs>>2)+2;
if (dx==0) { dx=+1; dy= 0; }
else if (dx==1) { dx=-1; dy= 0; }
else if (dx==2) { dx= 0; dy=+1; }
else if (dx==3) { dx= 0; dy=-1; }
// add wall to maze remember set cells (for remowal if needed)
for (j=0;l;l--,x+=dx,y+=dy)
if ((x>=0)&&(x<xs))
if ((y>=0)&&(y<ys))
if (map[y][x]!=A_star_wall)
{
p[j]=x; j++;
p[j]=y; j++;
map[y][x]=A_star_wall;
}
// is there solution?
compute(x0,y0,x1,y1);
// if not remowe last added wall
if (ps==0) for (;j;)
{
j--; y=p[j];
j--; x=p[j];
map[y][x]=A_star_space;
}
}
delete[] p;
}
generated by this code:
A_star map;
map.resize(256,256);
map.generate(5,5,250,250,500);

JFrame won't call paint method?

So I made Pong in a applet for a project in school but I realized that I can't hand in the project without creating an HTML file, so I'm attempting to change all my code from a applet to a JFrame. It all works, but my paint method isn't being called, any help will be great. Thanks for the help but to be honest im new to programming so if someone could make the changes to my code and then explain what you did, that would be great
package pong;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Main extends JPanel implements Runnable, KeyListener{//whatever class holds you main method
private static final long serialVersionUID = 1L;
int width = 600;
int height = width *9/16;
int Pwidth = 10, Pheight = 50, Px = 30, Py = height / 2-Pwidth, Pv = 3;
int Ewidth = 10, Eheight = 50, Ex = width - Ewidth - 30, Ey = height / 2-Ewidth - 50;
double Ev = 2.7;
int Bwidth = 10, Bheight = 10, Bx = width / 2 + 50, By = height / 2, Bvx = 3, Bvy = 3;
int TimeD = 0;
int Ms = 0, sec = 0, min = 0;
int Pscore = 0, Escore = 0, Pwinx = 800, Pwiny = height / 2, Ewinx = 800, Ewiny = height / 2;
boolean Bleft = true, Bright = false, Bup = true, Bdown = false;
boolean Pup = false, Pdown = false;
boolean Pa = false;
String string = new String();
public static JFrame frame;//public and static so other classes can access it. Might want to use a getter and setter here
public Main(){
frame=new JFrame("Pong, A game re-made by Camron Warren");// Create new JFrame
frame.setSize(width,height);//Set the size of the window
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);//Make sure all processes are closed when the window is closed
frame.setLocationRelativeTo(null);//Centers window
frame.setVisible(true);//Make the window visible
Thread th = new Thread(this);
addKeyListener(this);
th.start();
}
public static void main(String[] args){
new Main();//instantiate the Main class, this has to happen
}
#Override
public void run() {
while(true){
if(Pscore >= 5){
Pwinx = 100;
Py = height / 2 - Pheight / 2;
Bx = width / 2 - Bwidth;
By = height /2 - Bheight /2;
}
if(Escore >= 5){
Ewinx = 400;
Py = height / 2-Pwidth;
Bx = width / 2 - Bwidth;
By = height /2;
}
if(Escore >= 5 && Pa == true){
Pscore = 0;
Escore = 0;
Ewinx = 800;
Ms = 0;
sec = 0;
min = 0;
}
if(Pscore >= 5 && Pa == true){
Pscore = 0;
Escore = 0;
Pwinx = 800;
Ms = 0;
sec = 0;
min = 0;
}
//ball movement class
ballMovement();
//TIME COUNTER
Ms++;
if(Ms >= 60){
sec++;
Ms = 0;
}
if(sec >= 60){
min++;
sec = 0;
}
//BALLMOVEMENT
if(Bleft == true){
Bx-=Bvx;
}
if(Bright == true){
Bx+=Bvx;
}
if(Bup == true){
By-=Bvy;
}
if(Bdown == true){
By+=Bvy;
}
//BALLHITBOX
if(By <= 0){
Bup = false;
Bdown = true;
}
if(By + Bheight >= height){
Bdown = false;
Bup = true;
}
//SCORE SYSTEM
if(Bx <= 0){
Escore++;
Bx = width / 2 - Bwidth;
By = height / 2;
}
if(Bx+Bwidth >= width){
Pscore++;
Bx = width /2 - Bwidth;
By = height / 2;
}
//PHITBOX
if(Bx+Bwidth >= Px && Bx <= Px+Pwidth && By+Bheight >= Py && By <= Py+Pheight){
System.out.println("Phit");
Bleft = false;
Bright = true;
}
//EHITBOX
if(Bx+Bwidth >= Ex && Bx <= Ex + Ewidth && By+Bheight >= Ey && By <= Ey + Eheight){
System.out.println("Ehit");
Bright = false;
Bleft = true;
}
//PMOVEMENT
if(Pup == true){
Py-=Pv;
}
if(Pdown == true){
Py+=Pv;
}
//PHITBOX/APPLETHITBOX
if(Py <= 0){
Py = 0;
}
if(Py + Pheight >= height){
Py = height - Pheight;
}
//EHITBOX/APPLETHITBOX
if(Ey <= 0){
Ey = 0;
}
if(Ey + Eheight >= height){
Ey = height - Eheight;
}
//REPAINT
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
public void ballMovement()
{
if(By >= Ey)
{
Ey += Ev;
}
if(By <= Ey)
{
Ey -= Ev;
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W){
Pup = true;
}
if(key == KeyEvent.VK_S){
Pdown = true;
}
if(key == KeyEvent.VK_UP){
Pup = true;
}
if(key == KeyEvent.VK_DOWN){
Pdown = true;
}
if(key == KeyEvent.VK_F1){
Pa = true;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_W){
Pup = false;
}
if(key == KeyEvent.VK_S){
Pdown = false;
}
if(key == KeyEvent.VK_UP){
Pup = false;
}
if(key == KeyEvent.VK_DOWN){
Pdown = false;
}
if(key == KeyEvent.VK_F1){
Pa = false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {}
#SuppressWarnings("deprecation")
public void update(Graphics g) {
Graphics offgc;
Image offscreen = null;
Dimension d = size();
offscreen = createImage(d.width, d.height);
offgc = offscreen.getGraphics();
offgc.setColor(getBackground());
offgc.fillRect(0, 0, d.width, d.height);
offgc.setColor(getForeground());
paint(offgc);
g.drawImage(offscreen, 0, 0, this);
}
#Override
public void paint(Graphics g){
g.setColor(Color.green);
g.fillRect(Px, Py, Pwidth, Pheight);
g.setColor(Color.RED);
g.fillRect(Ex, Ey, Ewidth, Eheight);
g.setColor(Color.BLACK);
g.fillOval(Bx, By, Bwidth, Bheight);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
g.drawString("Score: " + Pscore, 20, 20);
g.drawString("Score " + Escore , width - 60, 20);
g.drawString("Time played: " + min + ": " + sec, width / 2 - 50, 20);
g.setColor(Color.BLACK);
g.fillRect(width / 2, height, 1, height);
g.setColor(Color.BLACK);
g.drawLine(width / 2, 0, width / 2, height);
g.setColor(Color.BLACK);
g.drawString("Pong: a game re-made by Camron Warren", 10, height - 10);
g.drawString("Congrat's, you win!", Pwinx, Pwiny);
g.drawString("Press F1 to play again!", Pwinx, Pwiny + 10);
g.drawString("Enemy win's", Ewinx, Ewiny);
g.drawString("Press F1 to play again!", Ewinx, Ewiny + 10);
}
}

java applet game jumping bug

I'm currently making a java game and I just managed to make the character jump but it only works half the time.
Sometimes he will jump perfectly but other times he will get stuck in the air. I think its something to do with the gravity variable changing but I'm not sure Please can you have a look?
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
public class meatboy extends Applet implements KeyListener{
public int x = 10, y = 300, gravity = 3;
public int xs = 380, ys = 230 , jump_count, jump_move;
double jumptime = 0;
public boolean right, left, up, jump = true, start, grounded, grav = true;
public void init(){
setSize(800,400);
setBackground(Color.black);
addKeyListener(this);
/////Movement//////
Timer t = new Timer();
t.schedule(new TimerTask(){public void run(){
if (start == true){
if (right == true){
x = x + 3;
}if (left == true){
x = x - 3;
}if(up == true && jump == true){
jump_count++;
if (jump_count >= 100){
jump_count = 0;
}
if (jump_count >= 0 && jump_count <= 25){
//jump_move = 1;
y = y - 5;
}
if (jump_count >= 25 && jump_count <= 50){
//jump_move = 2;
y = y - 5;
}
if (jump_count >= 50 && jump_count <= 75){
//jump_move = 3;
y = y - 5;
}
if (jump_count >= 75 && jump_count <= 100){
//jump_move = 0;
y = y - 5;
jump = false;
}
}
/////GRAVITY//////
if (grav == true){y = y + gravity;}
///////Collision Dectection/////
if(x > 790){//right of screen stop
x = 10;
}if(x < 10){// left stop
x = 789;
}if(y > 350){
//y = y - 3;
grav = false;
jump = true;
}else{grav = true;}
////////////End of collision///////////
repaint();
}}},10,10);
///////movement end////////
}
public void paint(Graphics g){
////////CREATES MEATBOY///////////////
if (start == false){
x = 10;
y = 300;
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, 800, 400);
g.setColor(Color.white);
g.drawString("MeatBoy 4K", 358, 180);
g.drawString("Press Z to start!!!!", 350, 200);
g.setColor(Color.RED);
g.fillRect(xs, ys, 16, 16);//meatboys body
g.fillRect(xs + 16, ys + 6, 4, 4);//arm
g.fillRect(xs - 4, ys + 6, 4, 4);//arm
g.fillRect(xs, ys + 12, 4, 6);//leg
g.fillRect(xs + 12, ys + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(xs + 2, ys + 2, 5, 5);//eye
g.fillRect(xs + 10, ys + 2, 5, 5);//eye
}
if (start == true){
g.setColor(Color.RED);
g.fillRect(x, y, 16, 16);//meatboys body
g.fillRect(x + 16, y + 6, 4, 4);//arm
g.fillRect(x - 4, y + 6, 4, 4);//arm
g.fillRect(x, y + 12, 4, 6);//leg
g.fillRect(x + 12, y + 12, 4, 6);//leg
g.setColor(Color.black);
g.fillRect(x + 2, y + 2, 5, 5);//eye
g.fillRect(x + 10, y + 2, 5, 5);//eye
///////////END OF MEATBOY//////////////////
////////Creates Floor///////////////////
g.setColor(Color.GRAY);
g.fillRect(0, 370, 800, 30);
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_Z){
//right = true;
start = true;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = true;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = true;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = true;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
//right = true;
right = false;
}if (e.getKeyCode() == KeyEvent.VK_LEFT){
left = false;
}if (e.getKeyCode() == KeyEvent.VK_UP){
up = false;
}if (e.getKeyCode() == KeyEvent.VK_SPACE){
up = false;
}
}
public void keyTyped(KeyEvent e) {
}
}
Where does the player get stuck in the air?
If it's close to the ground, make sure that the y coordinate is right on the ground.
On this block of code:
}if(y > 350){
//y = y - 3;
grav = false;
jump = true;
}else{grav = true;}
Add
}if(y > 350){
//y = y - 3;
grav = false;
jump = true;
//I'm on the ground all right
y = 350;
}else{grav = true;}

Categories

Resources