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();
}
Related
I am trying to get a circle to be able to jump and move left and right at the same time, but right now its either only jumping or moving forward at a time. Anyone know how to change my code to solve this? Thanks
float px,py,vx,vy,ax,ay;
boolean canJump = false;
void setup(){
size(600, 400);
ax = 0;
ay = .32;
vx = 0;
vy = 0;
px = 300;
py = 200;
}
int x = 50;
int y = 520;
void draw(){
background(0);
ellipse(px-15, py-30, 60, 60);
vx+=ax;
vy+=ay;
px+=vx;
py+=vy;
if( py > height ){
py = height;
vy = 0;
canJump = true;
}
player();
}
void player(){
fill(255);
rect(0, 550, 1000, 50);
}
void keyPressed(){
if(keyCode == RIGHT || key == 'd'){
px += 10;
}
if(keyCode == LEFT || key == 'a'){
px -= 10;
}
if(keyCode == UP){
if(canJump) {
vy = -10;
canJump = false;
}
}
}
So you can make your ball go both up and right or up and left by checking that both keys are pressed and then you can add to the velocity instead of the position to affect the trajectory of the ball. However, then you must slow down the x component of the velocity when it hits the ground, so I added a friction variable.
float px, py, vx, vy, ax, ay;
boolean canJump = false;
float bounce = 0.2;
float friction = 0.2;
void setup() {
size(600, 400);
ax = 0;
ay = .32;
vx = 0;
vy = 0;
px = 300;
py = 200;
}
int x = 50;
int y = 520;
void draw() {
background(0);
ellipse(px-15, py-30, 60, 60);
vx+=ax;
vy+=ay;
px+=vx;
py+=vy;
if ( py > height ) {
py = height;
vy = -bounce*vy;
vx = friction*vx;
canJump = true;
}
}
void keyPressed() {
if (keyCode == RIGHT && keyCode == UP) {
if (canJump) {
vy = -10;
vx += 5;
canJump = false;
}
} else if (keyCode == LEFT && keyCode == UP) {
if (canJump) {
vy = -10;
vx += -5;
canJump = false;
}
} else {
if (keyCode == RIGHT || key == 'd') {
vx += 5;
}
if (keyCode == LEFT || key == 'a') {
vx -= 5;
}
if (keyCode == UP) {
if (canJump) {
vy = -10;
canJump = false;
}
}
}
}
You can improve the implementation of your program by taking a look at processing's PVector class.
PVector pos;
PVector vel;
PVector acc;
float friction = 0.3;
float bounce = 0.5;
float diameter = 60;
boolean canJump = false;
void setup() {
size(600, 400);
pos = new PVector(300, 200);
vel = new PVector(0, 1);
acc = new PVector(0, 0.32);
}
void draw() {
background(0);
circle(pos.x, pos.y, diameter);
vel.add(acc);
pos.add(vel);
if (pos.y + diameter/2 > height) {
pos.set(pos.x, height-diameter/2);
vel.set(vel.x*friction, -vel.y*bounce);
canJump = true;
}
}
void keyPressed() {
boolean right = keyCode == RIGHT || key == 'd';
boolean left = keyCode == LEFT || key == 'a';
boolean up = keyCode == UP || key == 'w';
if (up && right && canJump) {
vel.add(5, -10);
canJump = false;
} else if (up && left && canJump) {
vel.add(-5, -10);
canJump = false;
} else {
if (up && canJump) {
vel.add(0, -10);
canJump = false;
}
if (right) {
vel.add(5, 0);
}
if (left) {
vel.add(-5, 0);
}
}
}
The problem I'm having is that when I run the game, instead of staying as one random color, the bricks will keep changing color while I'm in game. How do I fix this so that each brick will stay as one color?
public class Game extends JoeApplet implements KeyListener
{
String status;
int ballx = 294; // ball spawn x coordinate
int bally = 640; // ball spawn y coordinate
int batx = 294;
int baty = 654;
int brickx = 32;
int bricky = 50;
double movex = -16; // x speed of ball
double movey = -16; //y speed of ball
int count = 0;
int currentLevel=0;
int score=0; //starts score at 0
int lives=3; //lives start at 3
static boolean right = false;
static boolean left = false;
boolean ballFallDown = false;
boolean bricksOver = false;
Rectangle Ball = new Rectangle(ballx, bally, 12, 12); //creates ball
Rectangle Bat = new Rectangle(batx, baty, 100, 12); //creates bat(paddle)
Rectangle[] Brick = new Rectangle[49]; //creates desired number of bricks
Random random = new Random();
static final float MIN_SAT = 0.8f;
Color color;
public void paint(Graphics art)
{
switch(currentLevel)
{
case 0:
menuScreen(art);
break;
case 1:
game(art);
break;
}
}
public void menuScreen(Graphics art)
{
setSize(700, 700);
art.setColor(Color.BLACK);
art.fillRect(0, 0, 698, 698);
Color ballcolor=new Color(0,0,66);
art.setColor(ballcolor);
art.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
Color batcolor=new Color(0,0,66);
art.setColor(batcolor);
art.fill3DRect(Bat.x, Bat.y, Bat.width, Bat.height, true);
art.setColor(Color.green);
art.drawRect(0, 0, 698, 698);
art.setColor(Color.yellow);
Font menu = new Font("Arial", Font.BOLD, 20);
art.setFont(menu);
art.drawString("Brick Breaker", 100,400);
art.drawString("Press P to Play", 100,425);
art.drawString("Press Q to Quit game", 100,450);
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
Color mycolor=new Color(100,0,0);
art.setColor(mycolor);
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
art.setColor(Color.YELLOW);
if (ballFallDown || bricksOver)
{
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.drawString(status, 294, 349);
ballFallDown = false;
bricksOver = false;
}
}
private Color color;
class Brick {
public Color getColor() { return color; }
public Brick()
{
float hue = random.nextFloat();
float saturation = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
float brightness = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
Color color = Color.getHSBColor(hue, saturation,
brightness);
}
}
public void game(Graphics art)
{
setSize(700, 700);
art.setColor(Color.BLACK);
art.fillRect(0, 0, 698, 698);
Color ballcolor=new Color(0,0,225);
art.setColor(ballcolor);
art.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
Color batcolor=new Color(0,0,139);
art.setColor(batcolor);
art.fill3DRect(Bat.x, Bat.y, Bat.width, Bat.height, true);
art.setColor(Color.green);
art.drawRect(0, 0, 698, 698);
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
art.setColor(Brick[i].getColor());
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
if (ballFallDown || bricksOver)
{
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.drawString(status, 100,425);
ballFallDown = false;
bricksOver = false;
}
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
if (Brick[i].intersects(Ball))
{
score=score+10;
Brick[i] = null;
movey = -movey;
count++;
}
}
}
if (count == Brick.length)
{
bricksOver = true;
movex=0;
movey=0;
art.setColor(Color.green);
status = "YOU BEAT THE LEVEL!!";
art.drawString("Press E to Exit", 100,450);
art.drawString("Press N for Next Level", 100,475);
repaint();
}
repaint();
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.setColor(Color.white);
art.drawString("Score:"+score, 600, 684);
Ball.x += movex;
Ball.y += movey;
if (left == true)
{
Bat.x -= 18;
right = false;
}
if (right == true)
{
Bat.x += 18;
left = false;
}
if (Bat.x <= 4)
{
Bat.x = 4;
}
else if (Bat.x >= 586)
{
Bat.x = 596;
}
if (Ball.intersects(Bat))
{
movey = -movey-.1;
}
if (Ball.x <= 0 || Ball.x + Ball.height >= 698)
{
movex = -movex;
}
if (Ball.y <= 0)
{
movey = -movey;
}
Font f1 = new Font("Arial", Font.BOLD, 20);
art.setFont(f1);
art.setColor(Color.white);
art.drawString("Lives:"+ lives, 5, 684);
if (Ball.y >= 698 && (bricksOver==false) && lives>0)
{
ballFallDown = true;
art.setColor(Color.red);
status = "";
art.drawString("", 100,450);
lives=lives-1;
ballx = 294;
bally = 640;
Ball = new Rectangle(ballx, bally, 12, 12);
movex = -16;
movey = -16;
repaint();
}
if(lives==0 && Ball.y >= 698)
{
art.setColor(Color.red);
art.drawString("You lost!!", 100,425);
art.drawString("Press E to Exit", 100,450);
}
}
public void init()
{
addKeyListener(this);
for (int i = 0; i < Brick.length; i++) //creates bricks
{
Brick[i] = new Rectangle(brickx, bricky, 40, 20);
if (i == 12) //1st row of bricks
{
brickx = 32;
bricky = 84;
}
if (i == 23) //2nd row of bricks
{
brickx = 82;
bricky = 118;
}
if (i == 32) //3rd row of bricks
{
brickx = 132;
bricky = 152;
}
if (i == 39) //4th row of bricks
{
brickx = 182;
bricky = 186;
}
if (i == 44) //5th row of bricks
{
brickx = 232;
bricky = 220;
}
if (i == 47) //6th row of bricks
{
brickx = 282;
bricky = 254;
}
if (i == 48) //7th row of bricks
{
brickx = 144;
bricky = 132;
}
brickx += 50; //spacing between each brick
}
}
public void restart() //if player chooses to exit(E) game will reset back to level one
{
ballx = 294;
bally = 640;
batx = 294;
baty = 654;
brickx = 32;
bricky = 50;
Ball = new Rectangle(ballx, bally, 12, 12);
Bat = new Rectangle(batx, baty, 100, 12);
movex = -16;
movey = -16;
ballFallDown = false;
bricksOver = false;
count = 0;
status = null;
for (int i = 0; i < Brick.length; i++) //recreates bricks
{
Brick[i] = new Rectangle(brickx, bricky, 40, 20);
if (i == 12)
{
brickx = 32;
bricky = 84;
}
if (i == 23)
{
brickx = 82;
bricky = 118;
}
if (i == 32)
{
brickx = 132;
bricky = 152;
}
if (i == 39)
{
brickx = 182;
bricky = 186;
}
if (i == 44)
{
brickx = 232;
bricky = 220;
}
if (i == 47)
{
brickx = 282;
bricky = 254;
}
if (i == 48)
{
brickx = 144;
bricky = 132;
}
brickx += 50;
}
repaint();
}
#Override
public void keyPressed(KeyEvent e) //allows each key to do desired action
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT)
{
left = true;
}
if (keyCode == KeyEvent.VK_RIGHT)
{
right = true;
}
if (keyCode == e.VK_P && currentLevel == 0)
{
currentLevel = 1;
}
else if (keyCode == e.VK_E && currentLevel == 1)
{
currentLevel = 0;
score=0;
lives=3;
restart();
}
else if(keyCode == e.VK_Q)
{
System.exit(0);
}
}
#Override
public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT)
{
left = false;
}
if (keyCode == KeyEvent.VK_RIGHT)
{
right = false;
}
}
#Override
public void keyTyped(KeyEvent e)
{
}
public static void main(String[] args)
{
Game prog = new Game();
prog.init();
}
}
Code where I try to give each brick a random color:
if (Brick[i] != null)
{
float hue = random.nextFloat();
float saturation = MIN_SAT + random.nextFloat() * (1f -
MIN_SAT);
float brightness = MIN_SAT + random.nextFloat() * (1f -
MIN_SAT);
Color color = Color.getHSBColor(hue, saturation,
brightness);
art.setColor(color);
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
You generate a random color for each Brick inside the game-method, which is called from within paintComponent. This means: each time the screen is repainted, all Bricks get a new Color. Instead of going this way, simply apply a random color to each Brick, when it's generated and leave it that way. This requires introducing a Color as variable in the Brick-class. Simplest solution would be to generate the color directly in the constructor:
private Color color;
public Brick(){
...
float hue = random.nextFloat();
float saturation = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
float brightness = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
color = Color.getHSBColor(hue, saturation,
...
}
As use the color stored in Brick in the game-method to render each Brick:
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
art.setColor(Brick[i].getColor());
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width, Brick[i].height, true);
}
}
And some general advice:
Please refactor your code and implement the advice we gave you about your code on the last question you asked. Going further down the path you're currently on, you'll wind up with code that is simply unreadable and can't be debugged. I know we shouldn't introduce any anecdotes here, but when I started coding, I wrote Snake in pretty much the same spaghetti-code style you're using now. In the end I had one small mistake I wanted to fix, so I changed one line of code. Result: the entire code broke, and I wasn't able to fix anything from that point, simply because the code was unusable. Moral of the story: in spaghettic-code fixing one bug introduces 100 new bugs. Write proper code, and live happily.
Here's the fixed code:
public class Game extends JoeApplet implements KeyListener
{
String status;
int ballx = 294; // ball spawn x coordinate
int bally = 640; // ball spawn y coordinate
int batx = 294;
int baty = 654;
int brickx = 32;
int bricky = 50;
double movex = -16; // x speed of ball
double movey = -16; //y speed of ball
int count = 0;
int currentLevel=0;
int score=0; //starts score at 0
int lives=3; //lives start at 3
static boolean right = false;
static boolean left = false;
boolean ballFallDown = false;
boolean bricksOver = false;
Rectangle Ball = new Rectangle(ballx, bally, 12, 12); //creates ball
Rectangle Bat = new Rectangle(batx, baty, 100, 12); //creates bat(paddle)
Brick[] Brick = new Brick[49]; //creates desired number of bricks
Random random = new Random();
static final float MIN_SAT = 0.8f;
public void paint(Graphics art)
{
switch(currentLevel)
{
case 0:
menuScreen(art);
break;
case 1:
game(art);
break;
}
}
public void menuScreen(Graphics art)
{
setSize(700, 700);
art.setColor(Color.BLACK);
art.fillRect(0, 0, 698, 698);
Color ballcolor=new Color(0,0,66);
art.setColor(ballcolor);
art.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
Color batcolor=new Color(0,0,66);
art.setColor(batcolor);
art.fill3DRect(Bat.x, Bat.y, Bat.width, Bat.height, true);
art.setColor(Color.green);
art.drawRect(0, 0, 698, 698);
art.setColor(Color.yellow);
Font menu = new Font("Arial", Font.BOLD, 20);
art.setFont(menu);
art.drawString("Brick Breaker", 100,400);
art.drawString("Press P to Play", 100,425);
art.drawString("Press Q to Quit game", 100,450);
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
art.setColor(Brick[i].getColor());
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
art.setColor(Color.YELLOW);
if (ballFallDown || bricksOver)
{
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.drawString(status, 294, 349);
ballFallDown = false;
bricksOver = false;
}
}
private Color color;
class Brick
extends Rectangle
{
private Color color;
public Color getColor() { return color; }
public Brick(int x, int y, int width, int height)
{
super(x, y, width, height);
float hue = random.nextFloat();
float saturation = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
float brightness = MIN_SAT + random.nextFloat() * (1f - MIN_SAT);
color = Color.getHSBColor(hue, saturation,
brightness);
}
}
public void game(Graphics art)
{
setSize(700, 700);
art.setColor(Color.BLACK);
art.fillRect(0, 0, 698, 698);
Color ballcolor=new Color(0,0,225);
art.setColor(ballcolor);
art.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
Color batcolor=new Color(0,0,139);
art.setColor(batcolor);
art.fill3DRect(Bat.x, Bat.y, Bat.width, Bat.height, true);
art.setColor(Color.green);
art.drawRect(0, 0, 698, 698);
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
art.setColor(Brick[i].getColor());
art.fill3DRect(Brick[i].x, Brick[i].y, Brick[i].width,
Brick[i].height, true);
}
}
if (ballFallDown || bricksOver)
{
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.drawString(status, 100,425);
ballFallDown = false;
bricksOver = false;
}
for (int i = 0; i < Brick.length; i++)
{
if (Brick[i] != null)
{
if (Brick[i].intersects(Ball))
{
score=score+10;
Brick[i] = null;
movey = -movey;
count++;
}
}
}
if (count == Brick.length)
{
bricksOver = true;
movex=0;
movey=0;
art.setColor(Color.green);
status = "YOU BEAT THE LEVEL!!";
art.drawString("Press E to Exit", 100,450);
art.drawString("Press N for Next Level", 100,475);
repaint();
}
repaint();
Font f = new Font("Arial", Font.BOLD, 20);
art.setFont(f);
art.setColor(Color.white);
art.drawString("Score:"+score, 600, 684);
Ball.x += movex;
Ball.y += movey;
if (left == true)
{
Bat.x -= 18;
right = false;
}
if (right == true)
{
Bat.x += 18;
left = false;
}
if (Bat.x <= 4)
{
Bat.x = 4;
}
else if (Bat.x >= 586)
{
Bat.x = 596;
}
if (Ball.intersects(Bat))
{
movey = -movey-.1;
}
if (Ball.x <= 0 || Ball.x + Ball.height >= 698)
{
movex = -movex;
}
if (Ball.y <= 0)
{
movey = -movey;
}
Font f1 = new Font("Arial", Font.BOLD, 20);
art.setFont(f1);
art.setColor(Color.white);
art.drawString("Lives:"+ lives, 5, 684);
if (Ball.y >= 698 && (bricksOver==false) && lives>0)
{
ballFallDown = true;
art.setColor(Color.red);
status = "";
art.drawString("", 100,450);
lives=lives-1;
ballx = 294;
bally = 640;
Ball = new Rectangle(ballx, bally, 12, 12);
movex = -16;
movey = -16;
repaint();
}
if(lives==0 && Ball.y >= 698)
{
art.setColor(Color.red);
art.drawString("You lost!!", 100,425);
art.drawString("Press E to Exit", 100,450);
}
}
public void init()
{
addKeyListener(this);
for (int i = 0; i < Brick.length; i++) //creates bricks
{
Brick[i] = new Brick(brickx, bricky, 40, 20);
if (i == 12) //1st row of bricks
{
brickx = 32;
bricky = 84;
}
if (i == 23) //2nd row of bricks
{
brickx = 82;
bricky = 118;
}
if (i == 32) //3rd row of bricks
{
brickx = 132;
bricky = 152;
}
if (i == 39) //4th row of bricks
{
brickx = 182;
bricky = 186;
}
if (i == 44) //5th row of bricks
{
brickx = 232;
bricky = 220;
}
if (i == 47) //6th row of bricks
{
brickx = 282;
bricky = 254;
}
if (i == 48) //7th row of bricks
{
brickx = 144;
bricky = 132;
}
brickx += 50; //spacing between each brick
}
}
public void restart() //if player chooses to exit(E) game will reset back to level one
{
ballx = 294;
bally = 640;
batx = 294;
baty = 654;
brickx = 32;
bricky = 50;
Ball = new Rectangle(ballx, bally, 12, 12);
Bat = new Rectangle(batx, baty, 100, 12);
movex = -16;
movey = -16;
ballFallDown = false;
bricksOver = false;
count = 0;
status = null;
for (int i = 0; i < Brick.length; i++) //recreates bricks
{
Brick[i] = new Brick(brickx, bricky, 40, 20);
if (i == 12)
{
brickx = 32;
bricky = 84;
}
if (i == 23)
{
brickx = 82;
bricky = 118;
}
if (i == 32)
{
brickx = 132;
bricky = 152;
}
if (i == 39)
{
brickx = 182;
bricky = 186;
}
if (i == 44)
{
brickx = 232;
bricky = 220;
}
if (i == 47)
{
brickx = 282;
bricky = 254;
}
if (i == 48)
{
brickx = 144;
bricky = 132;
}
brickx += 50;
}
repaint();
}
#Override
public void keyPressed(KeyEvent e) //allows each key to do desired action
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT)
{
left = true;
}
if (keyCode == KeyEvent.VK_RIGHT)
{
right = true;
}
if (keyCode == e.VK_P && currentLevel == 0)
{
currentLevel = 1;
}
else if (keyCode == e.VK_E && currentLevel == 1)
{
currentLevel = 0;
score=0;
lives=3;
restart();
}
else if(keyCode == e.VK_Q)
{
System.exit(0);
}
}
#Override
public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT)
{
left = false;
}
if (keyCode == KeyEvent.VK_RIGHT)
{
right = false;
}
}
#Override
public void keyTyped(KeyEvent e)
{
}
public static void main(String[] args)
{
Game prog = new Game();
prog.init();
}
}
Pretty hard to fix stuff already.
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);
}
}
I have a set of sprites that I am calling in a Java game, and when I had 3 sprites it worked fine, but when I add a fourth sprite, the repaint method is only called every other time.
Here is my minimal example,
Main class:
public class Maze extends JPanel implements ActionListener{
/**
* #param args
*/
int stage;
int dir;
int x = 32;
int y = 32;
Rectangle r = new Rectangle(x,y,10,10);
Draw D = new Draw();
public static ArrayList<Rectangle> walls = new ArrayList<Rectangle>();
public ArrayList<Image> spritesl = new ArrayList<Image>();
public ArrayList<Image> spritesd = new ArrayList<Image>();
public ArrayList<Image> spritesr = new ArrayList<Image>();
public ArrayList<Image> spritesu = new ArrayList<Image>();
BufferedImage image;
public Maze() throws IOException{
setBackground(Color.black);
setSize(672,672);
Timer timer = new Timer(2000,this);
timer.addActionListener(this);
timer.start();
//add sprites
for(int i = 1; i<5; i += 1){
spritesl.add(image = ImageIO.read(new File("C:/Users/Dave/Desktop/Sprites/left" + i + ".png")));
}
for(int i = 1; i<5; i += 1){
spritesd.add(image = ImageIO.read(new File("C:/Users/Dave/Desktop/Sprites/down" + i + ".png")));
}
for(int i = 1; i<5; i += 1){
spritesr.add(image = ImageIO.read(new File("C:/Users/Dave/Desktop/Sprites/right" + i + ".png")));
}
for(int i = 1; i<5; i += 1){
spritesu.add(image = ImageIO.read(new File("C:/Users/Dave/Desktop/Sprites/up" + i + ".png")));
}
}
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame();
Maze ate = new Maze();
frame.addKeyListener(new Input());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(ate);
frame.setPreferredSize(new Dimension(688, 709));//16, 37
frame.setVisible(true);
frame.pack();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//call wall drawer
g.setColor(Color.gray);
D.draw(g);
g.setColor(Color.red);
//set animation
if(dir == 1){
g.drawImage(spritesu.get(stage-1),x,y, this);
}else if(dir == 2){
g.drawImage(spritesr.get(stage-1),x,y, this);
}else if(dir == 3){
g.drawImage(spritesd.get(stage-1),x,y, this);
}else if(dir == 4){
g.drawImage(spritesl.get(stage-1),x,y, this);
}
System.out.println("set");
}
#Override
public void actionPerformed(ActionEvent e) {
boolean up =false;
boolean right =false;
boolean down =false;
boolean left =false;
//next part tests each direction for collisions
if(Input.right){
right = true;
x += 4;
if(x>672-32){
x -= 4;
right = false;
}else{
for(int i = 0; i < walls.size(); i += 1){
if(new Rectangle(x, y, 30, 30).intersects(walls.get(i))){
x -= 4;
right = false;
}
}
}
}
if(Input.left){
left = true;
dir=4;
x-=4;
if(x<0){
x += 4;
left = false;
}else{
for(int i = 0; i < walls.size(); i += 1){
if(new Rectangle(x, y, 32, 32).intersects(walls.get(i))){
x += 4;
left = false;
}
}
}
}
if(Input.down){
down = true;
dir=3;
y+=4;
if(y>672-32){
y -= 4;
down = false;
}else{
for(int i = 0; i < walls.size(); i += 1){
if(new Rectangle(x, y, 32, 32).intersects(walls.get(i))){
y -= 4;
down = false;
}
}
}
}
if(Input.up){
up = true;
dir=1;
y-=4;
if(y<0){
y += 4;
up = false;
}else{
for(int i = 0; i < walls.size(); i += 1){
if(new Rectangle(x, y, 32, 32).intersects(walls.get(i))){
y += 4;
up = false;
}
}
}
}
//sets direction of animation
if(left||down||right||up){
if(left){
dir = 4;
}
if(down){
dir = 3;
}
if(right){
dir = 2;
}
if(up){
dir = 1;
}
stage += 1;
if(stage >= 4 || stage <= 0){
stage = 1;
}
System.out.println(stage);
}
repaint();
}
}
My input tester(probably not necessary, but its needed for the game to run):
public class Input implements KeyListener {
public static boolean left = false;
public static boolean right = false;
public static boolean up = false;
public static boolean down = false;
public static boolean space = false;
//test for keys
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
left = true;
if (key == KeyEvent.VK_RIGHT)
right = true;
if (key == KeyEvent.VK_UP)
up = true;
if (key == KeyEvent.VK_DOWN)
down = true;
if (key == KeyEvent.VK_SPACE)
space = true;
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
left = false;
if (key == KeyEvent.VK_RIGHT)
right = false;
if (key == KeyEvent.VK_UP)
up = false;
if (key == KeyEvent.VK_DOWN)
down = false;
if (key == KeyEvent.VK_SPACE)
space = false;
}
#Override
public void keyTyped(KeyEvent e) {}
}
and my Draw class:
public class Draw {
public void draw(Graphics g){
//draw everything
Maze.walls.clear();
g.fillRect(0, 0, 672, 32);
g.fillRect(0, 0, 32, 672);
g.fillRect(0, 640, 320, 32);
g.fillRect(352, 640, 320, 32);
g.fillRect(640, 0, 32, 320);
g.fillRect(640, 352, 32, 320);
Maze.walls.add(new Rectangle(0, 0, 672, 32));
Maze.walls.add(new Rectangle(0, 0, 32, 672));
Maze.walls.add(new Rectangle(0, 640, 320, 32));
Maze.walls.add(new Rectangle(352, 640, 320, 32));
Maze.walls.add(new Rectangle(640, 0, 32, 320));
Maze.walls.add(new Rectangle(640, 352, 32, 320));
}
}
now, this works and cycles three stages, but as soon as I change the stage max to 5, it only paints on stages 2 and 4, which are exactly the same. Can anyone tell me what I am doing wrong?
Swing "Timers coalesce events by default." As noted by #HOFE, re-reading your sprite images is likely slowing things down enough to trigger the effect. Instead, read the images into a List<Image> when the program starts.
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;}