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.
Related
Currently I'm studying Computer Science and my teacher want me to make a snake game with array.
I have this code that is exactly same as my friend's but it only grow one body length and won't grow longer and after it eats the food it starts to slow down the speed of moving snake. I'm not sure where I went wrong please help. Thank you.
Here's the code:
public class Main extends JPanel implements KeyListener, ActionListener {
private static final long serialVersionUID = 1L;
static int dir;
static int i;
static int x[] = new int[200]; // Decleare Array of snake on x coordinate
static int y[] = new int[200]; // Decleare Array of snake on y coordinate
static int taillength = 1;
static int sxinc = 20, syinc = 20; // Speed of moving snake
static int fx = 100, fy = 100; // Declare the position of where food at
static int f2x = 300, f2y = 300; // Declare the position of where food2 at
static int fmx = 300, fmy = 100; // Declare the position of where food3 at
static int score = 0; // Create Score Counter
static int width = 745, height = 489; // Declare the size of JPanel
static int nsx, nsy; // The new value of the snake movement
static int csx = 20, csy = 20; // The value to add/minus on the number to
static BufferedImage background = null;
static JFrame f;
static JFrame g;
public Main() {
addKeyListener(this);
}
public void addNotify() {
super.addNotify();
requestFocus();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, width, height, this);
g.setColor(Color.GREEN);
g.fillRect(fx, fy, 20, 20);
g.setFont(new Font("Times New Roman", Font.BOLD, 15));
g.setColor(Color.GREEN);
g.drawString("GREEN - Add 1 body length, add 1 score", 0, 429);
g.setColor(Color.BLUE);
g.fillRect(f2x, f2y, 20, 20);
g.setFont(new Font("Times New Roman", Font.BOLD, 15));
g.setColor(Color.BLUE);
g.drawString("BLUE - Add 2 body length, add 2 score", 0, 444);
g.setColor(Color.CYAN);
g.fillRect(fmx, fmy, 20, 20);
g.setFont(new Font("Times New Roman", Font.BOLD, 15));
g.setColor(Color.CYAN);
g.drawString("CYAN - Minus 1 body length, add 1 score", 0, 459);
g.setColor(Color.RED);
for (int j = 0; j < x.length && j < taillength; j++) {
g.fillRect(x[j], y[j], 20, 20);
g.setColor(Color.ORANGE);
}
g.fillRect(x[0], y[0], 20, 20);
g.setColor(Color.RED);
g.setFont(new Font("Times New Roman", Font.BOLD, 25));
g.setColor(Color.WHITE);
g.drawString("Score : " + score, 305, 459);
}
public void snakenew() {
for (int i = 0; i < x.length; i++) {
x[i] = 0;
y[i] = 0;
}
}
public static void main(String a[]) {
x[0] = 300;
y[0] = 220;
try { // Import Background
background = ImageIO.read(new File("H:/shutterstock_12730534.jpg"));
} catch (IOException e) {
}
Main p = new Main();
g = new JFrame();
g.add(p);
g.setSize(200, 300);
g.setVisible(true);
g.setResizable(false);
f = new JFrame();
f.add(p);
f.setSize(width, height);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer t = new Timer(60, p);
t.start();
}
public void actionPerformed(ActionEvent e) {
if ((x[0] + 20 > width) || (x[0] < 0) || (y[0] + 40 > height)
|| (y[0] < 0)) { // Game over when hit the wall
JOptionPane.showMessageDialog(null, "You hit the wall!", "Game",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
if ((taillength > 1) && (x[i] != x[0]) && (y[i] != y[0])) { // Game over
// when
// touch you
// snake
// body
if ((x[0] == x[i]) & (y[0] == y[i])) {
JOptionPane.showMessageDialog(null, "You ran into yourself!",
"Game", JOptionPane.INFORMATION_MESSAGE);
}
}
if (dir == KeyEvent.VK_UP) {
if (y[0] == y[taillength]) {
y[0] = y[0] - syinc;
}
}
else if (dir == KeyEvent.VK_DOWN) {
if (y[0] == y[taillength]) {
y[0] = y[0] + syinc;
}
}
else if (dir == KeyEvent.VK_LEFT) {
if (x[0] == x[taillength]) {
x[0] = x[0] - sxinc;
}
}
else if (dir == KeyEvent.VK_RIGHT) {
if (x[0] == x[taillength]) {
x[0] = x[0] + sxinc;
}
}
if (dir == KeyEvent.VK_K) {
if ((score > 6) && (taillength > 5)) {
taillength = taillength - 5;
score = score - 7;
}
}
if ((x[0] == fx) && (y[0] == fy)) { // Food Score and random food
fx = (int) (Math.random() * 37) * 20;
fy = (int) (Math.random() * 25) * 20;
taillength++;
score++;
}
if ((x[0] == f2x) && (y[0] == f2y)) {
f2x = (int) (Math.random() * 37) * 20;
f2y = (int) (Math.random() * 25) * 20;
taillength = taillength + 2;
score = score + 2;
}
if ((x[0] == fmx) && (y[0] == fmy)) {
if (taillength > 0) {
fmx = (int) (Math.random() * 37) * 20;
fy = (int) (Math.random() * 25) * 20;
taillength--;
score++;
}
}
for (i = taillength; i > 0; i--) {
x[i] = x[(i - 1)];
y[i] = y[(i - 1)];
}
f.repaint();
}
public void keyPressed(KeyEvent ke) {
dir = ke.getKeyCode();
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
}
A few things:
You are using a timer, but the item you are putting in the timer has no run() method... That's not how a timer works (please reference the last point as to why).
You are redrawing the whole screen every single time you tick. Not only is that ridiculous, it is most likely the cause of your aforementioned lag when you grow the body. Fixing this will ensure that you experience little to now lag between growth (although, you will still need to compensate at later growths by changing the speed of the snake; this, will also make the game more difficult as you go on, just like real Snake). This usage of the paint() method, can be attributed to the same reasoning as the last point.
You took someone elses code. Don't use code that doesn't belong to you--it might work, and you're fine, or you might have the same bug as the other guy, and now you've got a great time explaining why you have the copied code of some other student.
In conclusion: if you want to borrow code, never borrow code from someone who is in the same course as you. Finally, look up some examples of Snake games in Java. I'm sure you'll find some people who have experienced similar problems, from whom you might learn. I hope this helps you, and best of luck!
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();
}
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);
}
}
This is my game project. It's very simple version of "Flappy Bird" and I have some serious problems with how the collisions algorithm works. I wrote 2 separate code fragments for collision, for wall1 and wall2. The problem begins when the ball is trying to go through a hole because somehow the program is detecting a collision with a wall. I'm almost positive that the collision algorithm was written correctly because I have been checking it all day.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends Applet implements KeyListener, Runnable {
Image bground;
Random generator = new Random();
int r1;
int wall1x;
int wall1y;
int wall1long;
int wall2x;
int wall2y;
int wall2long;
Timer timer;
private Image i;
private Graphics doubleG;
int r2;
int blok_x1 = 800;
int blok_y1;
int blok_x = 800;
int blok_y = 0;
int blok_x_v = 2;
int ballX = 20;
int ballY = 20;
int dx = 0;
int dyclimb = 1;
int dyrise = 1;
double gravity = 3;
double jumptime = 0;
int FPS = 100;
public int tab[];
public boolean grounded = true, up = false;
boolean OVER = false;
#Override
public void init() {
bground = getImage(getCodeBase(), "12.png");
this.setSize(600, 400);
tab = new int[100];
for (int t = 0; t < 100; t++) {
tab[t] = generator.nextInt(380) + 1;
}
addKeyListener(this);
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
ballX -= 10;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
ballX += 10;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
ballY -= 10;
up = true;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
ballY += 10;
}
}
#Override
public void paint(Graphics g) {
g.drawImage(bground, 0, 0, this);
if (OVER == false) {
for (int i = 0; i < 100; i++) {
g.setColor(Color.green);
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
g.fillRect(wall1x, wall1y, 20, wall1long);
g.setColor(Color.green);
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
g.fillRect(wall2x, wall2y, 20, wall2long);
g.setColor(Color.green);
}
g.setColor(Color.red);
g.fillOval(ballX, ballY, 20, 20);
} else {
g.drawString("GAME OVER", 300, 300);
}
}
#Override
public void update(Graphics g) {
if (i == null) {
g.setColor(Color.green);
i = createImage(this.getSize().width, this.getSize().height);
doubleG = i.getGraphics();
g.setColor(Color.green);
}
doubleG.setColor(getBackground());
g.setColor(Color.green);
doubleG.fillRect(0, 0, this.getSize().width, this.getSize().height);
doubleG.setColor(getForeground());
g.setColor(Color.green);
paint(doubleG);
g.drawImage(i, 0, 0, this);
}
#Override
public void run() {
int time = 10;
while (true) {
if (up == true) {
ballY -= dyclimb;
time--;
} else {
ballY += dyrise;
}
if (time == 0) {
time = 10;
up = false;
}
blok_x--;
blok_x1--;
if (ballX > 600 || ballX < 0 || ballY > 400 || ballY < 0) {
OVER = true;
}
for (int i = 0; i < 100; i++) { // collision algorithm
wall1x = blok_x + i * 400;
wall1y = blok_y;
wall1long = tab[i];
if (ballX + 20 >= wall1x && ballX <= wall1x + 20 && ballY <= wall1y + wall1long && ballY >= wall1x - 20) { //wall1
OVER = true;
}
}
for (int i = 0; i < 100; i++) {
wall2x = blok_x1 + i * 400;
wall2y = tab[i] + 60;
wall2long = 400 - tab[i];
if (ballX + 20 >= wall2x && ballX <= wall2x + 20 && ballY <= wall2y + wall2long && ballY >= wall2x - 20) { //wall2
OVER = true;
}
}
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException ex) {
Logger.getLogger(NewApplet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Use Rectangle class. There's a method called Intersect or Intersection or something like that.
Say you have one object moving. Make a Rectangle to match the object in position(basically an invisible cover for the object).
Do the same things with another object.
When both are to collide, use the intersection method to check on the collision by using the rectangles.
These might help
http://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html
Java method to find the rectangle that is the intersection of two rectangles using only left bottom point, width and height?
java.awt.Rectangle. intersection()
I need some help figuring out how to capture and store collisions in a frogger game. I've managed to get the game to run fairly smoothly and now want to add collisions to the game. After some research I've found that rectangles seem like a viable option for my game, however, I'm not sure where I should start to actually capture a collision from an "enemy" and a "player". Here is my code so far:
public class myJPanel0 extends JPanel implements KeyListener, ActionListener
//This panel will contain the game
{
JButton menu;
Image myImage;
Graphics g;
myJPanel1 p1;
// Border[] gameBorder = new Border[]{BorderFactory.createTitledBorder("Border types")};
gameOverJPanel gp;
JButton lion = new JButton(new ImageIcon("images/download.jpg"));
JButton yard = new JButton("50 Yardline");
JButton score = new JButton("Touchdown");
JButton start = new JButton("Start");
JButton scoreKeeper = new JButton("Your score is");
JButton lives = new JButton("Lives left = ");
Timer tim;
int delay = 100;
int x = 296;
int y = 685;
int counter = 0;
ButtonObject[] enemies = new ButtonObject[10];
ButtonObject[] enemies1 = new ButtonObject[10];
ImageIcon icon[] = new ImageIcon[10];
public myJPanel0(myJPanel1 informedp1, gameOverJPanel informedgp)
{
super();
setLayout(null);
p1 = informedp1;
gp = informedgp;
setBackground(Color.MAGENTA);
menu = new JButton("Menu");
scoreKeeper.setBounds(16,80,200,55);
lives.setBounds(417, 80,200,55);
lion.setBounds(x,y,40,55);
score.setBounds(16,135,601,55);
yard.setBounds(16,410,601,55);
start.setBounds(16,685,601,55);
menu.setBounds(new Rectangle(250,5,80,30));
add(menu);
add(lives);
add(lion);
add(yard);
add(start);
add(scoreKeeper);
add(score);
setFocusable(true);
addKeyListener(this);
tim = new Timer(delay, this);
tim.start();
for (int i = 0; i <= 3; i++){ // loop that cycles through first half of enemy creation
String text = String.valueOf(i);
int y = 630 - (i * 55);
int x = 16;
enemies[i] = new ButtonObject(text+"??", x, y, 40, 55);
enemies[i].setBounds(new Rectangle(x, y, 40,55));
add(enemies[i]);
}
for (int i = 0; i <= 3; i++){ // second have enemy creation
String text = String.valueOf(i);
int y = 355 - (i * 55);
int x = 16;
enemies1[i] = new ButtonObject(text+"??", x, y, 40, 55);
enemies1[i].setBounds(new Rectangle(x, y, 40,55));
add(enemies1[i]);
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Image myLion = Toolkit.getDefaultToolkit().getImage("images/download.jpg");
g.drawImage(myLion,296,355,40,55,this);
if(p1.myImage1 == 1)
{
super.paintComponent(g);
Image myImage = Toolkit.getDefaultToolkit().getImage("images/snow.jpg");//Place holder for now, we can come up with our own image.
g.drawImage(myImage, 0, 0,680,880, this);
requestFocusInWindow();
}else if(p1.myImage1 == 2)
{
super.paintComponent(g);
Image myImage = Toolkit.getDefaultToolkit().getImage("images/grass.jpg");//Place holder for now, we can come up with our own image.
g.drawImage(myImage, 0, 0,680,880, this);
requestFocusInWindow();
}
else{
super.paintComponent(g);
Image myImage = Toolkit.getDefaultToolkit().getImage("images/stone.jpg");//Place holder for now, we can come up with our own image.
g.drawImage(myImage, 0, 0,680,880, this);
requestFocusInWindow();
}
}
public void keyPressed(KeyEvent evt)
{
System.out.println("Key pressed");
int kk = evt.getKeyCode();
if(kk == evt.VK_LEFT) {x=x-40;}
else if(kk == evt.VK_RIGHT) {x=x+40;}
else if(kk == evt.VK_UP) {y=y-55;}
else if(kk == evt.VK_DOWN) {y=y+55;}
lion.setBounds(x,y,40,55);
System.out.println(x);
System.out.println(y);
if(y <= 135){
counter = counter + 1;
scoreKeeper.setText("Your score is " + counter);
y = 740;
}
}
public void keyReleased(KeyEvent evt) { }
public void keyTyped(KeyEvent evt) { }
public void actionPerformed(ActionEvent event) {
for (int i = 0; i <= 3; i++)
{
enemies[i].move();
}
for (int i = 0; i <= 3; i++)
{
enemies1[i].move();
}
}
}