Java Applet MouseListener not working - java

I thought I programmed it so that when I click on the 'Start' button that appears when it is not level 1 or higher, it would go to level 1. But nothing happens when I click it.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.awt.Font;
public class Move extends Applet implements KeyListener, MouseListener {
private Rectangle rect;
private ArrayList<Integer> keysDown;
Random randomGenerator = new Random();
int speed = 4;
int level = 0;
int xpos;
int ypos;
boolean startClicked;
Image block;
Image start;
URL base;
MediaTracker mt;
int randomx = randomGenerator.nextInt(560);
int randomy = randomGenerator.nextInt(360);
public void init() {
this.addKeyListener(this);
this.addMouseListener(this);
keysDown = new ArrayList<Integer>();
rect = new Rectangle(0, 0, 50, 50); ///////////////////////////////////you can use rect.getX();
mt = new MediaTracker(this);
try {
base = getDocumentBase();
}
catch (Exception e) {}
block = getImage(base, "block.gif");
start = getImage(base, "start_button.png");
mt.addImage(block, 1);
try {
mt.waitForAll();
}
catch (InterruptedException e) {}
}
public void paint(Graphics g) {
setSize(600, 400);
Graphics2D g2 = (Graphics2D)g;
if (level != 0) {
g2.fill(rect);
//g.drawImage(block, randomx, randomy, this); ###############################fhjvhfjvkjerhgvgf
Font font = new Font("Arial", Font.BOLD, 18);
g.setFont(font);
String text = "Speed: " + speed;
FontMetrics fm = g.getFontMetrics();
int x = (getWidth() - fm.stringWidth(text)) / 2;
int y = (getHeight() - fm.getHeight()) + fm.getAscent();
g.drawString(text, x, y);
}
else { // start menu
g.drawImage(start, 160, 160, this);
}
}
#Override
public void keyPressed(KeyEvent e) {
if (!keysDown.contains(e.getKeyCode()))
keysDown.add(new Integer(e.getKeyCode()));
moveRect();
}
#Override
public void keyReleased(KeyEvent e) {
keysDown.remove(new Integer(e.getKeyCode()));
}
public void moveRect() {
if (level != 0) {
int x = rect.x;
int y = rect.y;
if (keysDown.contains(KeyEvent.VK_UP)) {
y -= speed;
}
if (keysDown.contains(KeyEvent.VK_DOWN)) {
y += speed;
}
if (keysDown.contains(KeyEvent.VK_LEFT)) {
x -= speed;
}
if (keysDown.contains(KeyEvent.VK_RIGHT)) {
x += speed;
}
rect.setLocation(x, y);
repaint();
if (x-32 > randomx-72 && y+64 > randomy && x-32 < randomx+72 && y-64 < randomy) { /// will be flag
randomx = randomGenerator.nextInt(560);
randomy = randomGenerator.nextInt(360);
speed += 4;
}
}
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void mouseClicked(MouseEvent me) {
if (level == 0) {
xpos = me.getX();
ypos = me.getY();
if (xpos > 160 && ypos > 96 && xpos < 400 && ypos < 160) {
level = 1;
}
}
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
}
#Override
public void mousePressed(MouseEvent me) {
}
}
Thanks again for all the help! This will HOPEFULLY turn out to be a maze game...
PS: ignore the pointless comments.

You are drawing at
g.drawImage(start, 160, 160, this);
But checking for
if (xpos > 160 && ypos > 96 && xpos < 400 && ypos < 160) {
Change that to
if (xpos >= 160 && ypos > 159 && xpos < 400 && ypos < 190) {
Better yet make constants of these numbers or use an ImageIcon and add a listener to it.
public static final int START_X_POS = 160;
public static final int START_Y_POS = 160;
public static final int START_WIDTH = 30;
public static final int START_HEIGHT = 150;
//...
if (xpos >= (START_X_POS ) && ypos >= START_Y_POS && xpos <= ( START_X_POS + START_WIDTH) && ypos <= (START_X_POS + START_HEIGHT )) {

Related

Putting a border for moving square

So basically im just playing around with movement systems for different purposes and having trouble making square stop right at the edge. Square moves off the side of screen by around 50% of the square it self and i cannot figure out why it is like that.
package SnakeMovement;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class SnakeMovement extends Canvas implements ActionListener, KeyListener {
Timer timer = new Timer(5, this);
int width, height;
int xSize = 50, ySize = 50;
int yPos = 0, xPos = 0, yVel = 0, xVel = 0;
public SnakeMovement(int w, int h) {
timer.start();
width = w;
height = h;
addKeyListener(this);
setFocusTraversalKeysEnabled(false);
setFocusable(true);
}
public void paint(Graphics g) {
super.paint(g);
g.fillRect(xPos, yPos, xSize, ySize);
}
public void actionPerformed(ActionEvent e) {
xPos += xVel;
yPos += yVel;
if (xPos >= width - xSize) {
xPos = width - xSize;
xVel = 0;
}
repaint();
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
yVel = -10;
xVel = 0;
}
if (key == KeyEvent.VK_S) {
yVel = 10;
xVel = 0;
}
if (key == KeyEvent.VK_A) {
xVel = -10;
yVel = 0;
}
if (key == KeyEvent.VK_D) {
xVel = 10;
yVel = 0;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
I just want so square stops at each side of screen perfectly on the edge.
Try:
private static final int BORDER_SIZE = 1;
private static final Color RECT_COLOR = Color.BLUE, BORDER_COLOR = Color.RED;
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(BORDER_COLOR);
g.fillRect(xPos, yPos, xSize, ySize);
g.setColor(RECT_COLOR);
g.fillRect(xPos+BORDER_SIZE, yPos+BORDER_SIZE, xSize-2*BORDER_SIZE, ySize-2*BORDER_SIZE);
}
The idea is to paint a full size rectangular using the border color.
Then painting a smaller one (smaller by 2*BORDER_SIZE) using the rectangular color.
The following is mre of the above:
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class SnakeMovement extends Canvas implements ActionListener, KeyListener {
private static final int BORDER_SIZE = 1, DELAY = 100;
private static final Color RECT_COLOR = Color.BLUE, BORDER_COLOR = Color.RED;
private final int xSize = 50, ySize = 50;
private int yPos = 0, xPos = 0, yVel = 5, xVel = 5;
private final Timer timer = new Timer(DELAY, this);
public SnakeMovement(int width, int height) {
timer.start();
addKeyListener(this);
setFocusTraversalKeysEnabled(false);
setFocusable(true);
setPreferredSize(new Dimension(width, height));
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(BORDER_COLOR);
g.fillRect(xPos, yPos, xSize, ySize);
g.setColor(RECT_COLOR);
g.fillRect(xPos+BORDER_SIZE, yPos+BORDER_SIZE, xSize-2*BORDER_SIZE, ySize-2*BORDER_SIZE);
}
#Override
public void actionPerformed(ActionEvent e) {
xPos += xVel;
yPos += yVel;
checkLimits();
repaint();
}
//when canvas edge is reached emerge from the opposite edge
void checkLimits(){
//check x and y limits
if (xPos >= getWidth()) {
xPos = -xSize;
}
if (xPos < -xSize ) {
xPos = getWidth();
}
if (yPos >= getHeight() ) {
yPos = -ySize;
}
if (yPos < -ySize ) {
yPos = getHeight();
}
}
//two other behaviors when hitting a limit. uncomment the desired behavior
/*
//when canvas edge is reached change direction
void checkLimits(){
//check x and y limits
if ( xPos >= getWidth() - xSize || xPos <= 0) {
xVel = - xVel;
}
if ( yPos >= getHeight() - ySize || yPos <= 0) {
yVel = - yVel;
}
}
*/
/*
//when canvas edge is reached stop movement
void checkLimits(){
//check x and y limits
if ( xPos >= getWidth() - xSize || xPos <= 0 || yPos >= getHeight() - ySize || yPos <= 0) {
timer.stop();
}
}
*/
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_W) {
yVel = -10;
xVel = 0;
}
if (key == KeyEvent.VK_S) {
yVel = 10;
xVel = 0;
}
if (key == KeyEvent.VK_A) {
xVel = -10;
yVel = 0;
}
if (key == KeyEvent.VK_D) {
xVel = 10;
yVel = 0;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args0) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SnakeMovement(500, 500));
frame.pack();
frame.setVisible(true);
}
}

How do you sense if a key is pressed and held in Java?

I have been working on a singleplayer pong game in which you currently use the mouse to control the paddle. I have added key listeners to the frame, and you can move the paddle by hitting the 'a' and 'd' keys, but you cannot hold them down. Here is the code which I have now, and I'd appreciate any help that you can offer!
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.concurrent.*;
import java.util.*;
public class Experiment extends JApplet {
public static final int WIDTH = BallRoom.WIDTH;
public static final int HEIGHT = BallRoom.HEIGHT;
public PaintSurface canvas;
public void init()
{
this.setSize(WIDTH, HEIGHT);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
canvas.requestFocusInWindow();
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3);
executor.scheduleAtFixedRate(new AnimationThread(this), 0L, 20L, TimeUnit.MILLISECONDS);
}
}
class AnimationThread implements Runnable
{
JApplet c;
public AnimationThread(JApplet c)
{
this.c = c;
}
public void run()
{
c.repaint();
}
}
class PaintSurface extends JComponent implements KeyListener
{
int paddle_x = 0;
int paddle_y = 360;
public boolean aDown;
public boolean dDown;
int score = 0;
float english = 1.0f;
Ball ball;
Color[] color = {Color.RED, Color.ORANGE, Color.MAGENTA, Color.ORANGE, Color.CYAN, Color.BLUE};
boolean aheld = false;
boolean dheld = false;
int colorIndex;
#Override
public void keyTyped(KeyEvent e)
{
System.out.println("Pressed " + e.getKeyChar());
}
#Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyChar() == 'd')
paddle_x += 10;
if (e.getKeyChar() == 'a')
paddle_x -= 10;
}
#Override
public void keyReleased(KeyEvent e)
{
}
public PaintSurface()
{
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent e)
{
if (e.getX() - 30 - paddle_x > 5)
english = 1.5f;
else if (e.getX() - 30 - paddle_x < 5)
english = -1.5f;
else
english = 1.0f;
paddle_x = e.getX() - 30;
}
});
addKeyListener(this);
ball = new Ball(20);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
Shape paddle = new Rectangle2D.Float(paddle_x, paddle_y, 60, 8);
g2.setColor(color[colorIndex % 6]);
if (ball.intersects(paddle_x, paddle_y, 60, 8) && ball.y_speed > 0)
{
ball.y_speed = -ball.y_speed * 1.1;
ball.x_speed = ball.x_speed * 1.1;
if (english != 1.0f)
{
colorIndex++;
}
score += Math.abs(ball.x_speed * 10);
}
if (ball.getY() + ball.getHeight() >= BallRoom.HEIGHT)
{
ball = new Ball(20);
score -= 1000;
colorIndex = 0;
}
ball.move();
g2.fill(ball);
g2.setColor(Color.BLACK);
g2.fill(paddle);
g2.drawString("Score: " + score, 250, 20);
}
}
class Ball extends Ellipse2D.Float{
public double x_speed, y_speed;
private int d;
private int width = BallRoom.WIDTH;
private int height = BallRoom.HEIGHT;
public Ball(int diameter)
{
super((int) (Math.random() * (BallRoom.WIDTH - 20) + 1), 0, diameter, diameter);
this.d = diameter;
this.x_speed = (int) (Math.random() * 5) + 1;
this.y_speed = (int) (Math.random() * 5) + 1;
}
public void move()
{
if (super.x < 0 || super.x > width - d)
x_speed = -x_speed;
if (super.y < 0 || super.y > height - d)
y_speed = -y_speed;
super.x += x_speed;
super.y += y_speed;
}
}
runningUse the following code for KeyPressed() and KeyReleased()
#Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyChar() == 'd')
dheld = true;
if (e.getKeyChar() == 'a')
aheld = true;
}
#Override
public void keyReleased(KeyEvent e)
{
if (e.getKeyChar() == 'd')
dheld = false;
if (e.getKeyChar() == 'a')
aheld = false;
}
Then have method running on a timer that moves the paddle if dheld or aheld are true.

how to space out random circles across a JPanel when using an array

I am trying to draw 7 random circles across a JPanel using an array. I managed to get the array to work but now I am having trouble spacing out the circles. When i run the program i see multiple circles being drawn but they are all on the same spot. All the circles are of different size and color. The other problem i have is making the circles move towards the bottom of the screen.
public class keyExample extends JPanel implements ActionListener, KeyListener{
private Circle[] circles = new Circle[7];
Timer t = new Timer(5,this);
//current x and y
double x = 150, y = 200;
double changeX = 0, changeY = 0;
private int circlex = 0,circley = 0; // makes initial starting point of circles 0
private javax.swing.Timer timer2;
public keyExample(){
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
NewCircle();
timer2 = new javax.swing.Timer(33,new MoveListener());
timer2.start();
}
public void NewCircle(){
Random colors = new Random();
Color color = new Color(colors.nextInt(256),colors.nextInt(256),colors.nextInt(256));
Random num= new Random();
int radius = num.nextInt(45);
for (int i = 0; i < circles.length; i++)
circles[i] = new Circle(circlex,circley,radius,color);
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.fill(new Rectangle2D.Double(x,y,40,40));
for (int i = 0; i < circles.length; i++)
circles[i].fill(g);
}
public void actionPerformed(ActionEvent e){
repaint();
x += changeX;
y += changeY;
changeX = 0;
changeY = 0;
}
public void up() {
if (y != 0){
changeY = -3.5;
changeX = 0;
}
}
public void down() {
if (y <= 350){
changeY = 3.5;
changeX = 0;
}
}
public void left() {
if (x >= 0) {
changeX = -3.5;
changeY = 0;
}
}
public void right() {
if (x <= 550) {
changeX = 3.5;
changeY = 0;
}
}
private class MoveListener implements ActionListener{
public void actionPerformed(ActionEvent e){
repaint();
Random speed = new Random();
int s = speed.nextInt(8);
}
}
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
up();
}
if (code == KeyEvent.VK_DOWN){
down();
}
if (code == KeyEvent.VK_RIGHT){
right();
}
if (code == KeyEvent.VK_LEFT){
left();
}
}
public void keyTyped(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
}
Circle class
import java.awt.*;
public class Circle{
private int centerX, centerY, radius, coord;
private Color color;
public Circle(int x, int y, int r, Color c){
centerX = x;
centerY = y;
radius = r;
color = c;
}
public void draw(Graphics g){
Color oldColor = g.getColor();
g.setColor(color);
g.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
g.setColor(oldColor);
}
public void fill(Graphics g){
Color oldColor = g.getColor();
g.setColor(color);
g.fillOval(centerX - radius, centerY - radius, radius *2, radius * 2);
g.setColor(oldColor);
}
public boolean containsPoint(int x, int y){
int xSquared = (x - centerX) * (x - centerX);
int ySquared = (y - centerY) * (y - centerY);
int RadiusSquared = radius * radius;
return xSquared + ySquared - RadiusSquared <=0;
}
public void move(int xAmount, int yAmount){
centerX = centerX + xAmount;
centerY = centerY + yAmount;
}
}
This is one of the problems with relying on borrowed code that you don't understand...
Basically, all you need to do is change the creation of the circles, for example...
for (int i = 0; i < circles.length; i++) {
circles[i] = new Circle(circlex, circley, radius, color);
circlex += radius;
}
You may wish to re-consider the use of KeyListener, in favour of Key Bindings before you discover that KeyListener doesn't work the way you expect it to...
For some strange reason, you're calling NewCirlces from within the MoveListener's actionPerfomed method, meaning that the circles are simply being re-created on each trigger of the Timer...instead, call it first in the constructor
You're also calling within your paintComponent method...this should mean that the circles never move and instead, random change size...
Updated with runnable example...
I modified your paint code NewCircle and the MoveListener a little...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class CircleExample extends JPanel implements ActionListener, KeyListener {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CircleExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private Circle[] circles = new Circle[7];
Timer t = new Timer(5, this);
//current x and y
double x = 150, y = 200;
double changeX = 0, changeY = 0;
private int circlex = 0, circley = 0; // makes initial starting point of circles 0
private javax.swing.Timer timer2;
public CircleExample() {
NewCircle();
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer2 = new javax.swing.Timer(33, new MoveListener());
timer2.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
public void NewCircle() {
for (int i = 0; i < circles.length; i++) {
Random colors = new Random();
Color color = new Color(colors.nextInt(256), colors.nextInt(256), colors.nextInt(256));
Random num = new Random();
int radius = num.nextInt(90);
circles[i] = new Circle(circlex, circley, radius, color);
circlex += radius;
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.fill(new Rectangle2D.Double(x, y, 40, 40));
for (int i = 0; i < circles.length; i++) {
circles[i].fill(g);
}
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
x += changeX;
y += changeY;
changeX = 0;
changeY = 0;
}
public void up() {
if (y != 0) {
changeY = -3.5;
changeX = 0;
}
}
public void down() {
if (y <= 350) {
changeY = 3.5;
changeX = 0;
}
}
public void left() {
if (x >= 0) {
changeX = -3.5;
changeY = 0;
}
}
public void right() {
if (x <= 550) {
changeX = 3.5;
changeY = 0;
}
}
private class MoveListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Random speed = new Random();
for (Circle circle : circles) {
int s = speed.nextInt(8);
circle.move(0, s);
}
repaint();
}
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP) {
up();
}
if (code == KeyEvent.VK_DOWN) {
down();
}
if (code == KeyEvent.VK_RIGHT) {
right();
}
if (code == KeyEvent.VK_LEFT) {
left();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
public class Circle {
private int centerX, centerY, radius, coord;
private Color color;
public Circle(int x, int y, int r, Color c) {
centerX = x;
centerY = y;
radius = r;
color = c;
}
public void draw(Graphics g) {
Color oldColor = g.getColor();
g.setColor(color);
g.drawOval(centerX, centerY, radius, radius);
g.setColor(oldColor);
}
public void fill(Graphics g) {
Color oldColor = g.getColor();
g.setColor(color);
g.fillOval(centerX, centerY, radius, radius);
g.setColor(oldColor);
}
public boolean containsPoint(int x, int y) {
int xSquared = (x - centerX) * (x - centerX);
int ySquared = (y - centerY) * (y - centerY);
int RadiusSquared = radius * radius;
return xSquared + ySquared - RadiusSquared <= 0;
}
public void move(int xAmount, int yAmount) {
centerX = centerX + xAmount;
centerY = centerY + yAmount;
}
}
}

Java call function in a loop without stackoverflowerror

I know I have asked a question like this before, but none of the answers in the old question worked for me. I am trying to make a little single-player pong game (It is in a Java applet). I already have a moveBall() function, as you can see below. But I don't know where to call it. I can't call it in the paint() method because it is double buffered.
public class Main extends Applet implements KeyListener, MouseListener {
private Rectangle paddle;
private Rectangle ball;
private ArrayList<Integer> keysDown;
private Image dbImage;
private Graphics dbg;
public int time = 300000;
Random randomGenerator = new Random();
int speed = 10;
int level = 1; // change to 0 once start menu works
int xpos, ypos;
int ballx, bally;
int width = 1024;
int height = 768;
int paddleWidth = 96;
int ballSize = 16;
String version = "0.0.1";
public static final int START_X_POS = 160;
public static final int START_Y_POS = 160;
public static final int START_WIDTH = 256;
public static final int START_HEIGHT = 64;
boolean startClicked;
boolean falling = true;
public void init() {
setSize(width, height);
addKeyListener(this);
addMouseListener(this);
setBackground(Color.black);
Frame c = (Frame)getParent().getParent();
c.setTitle("Asteroid Attack - Version " + version);
keysDown = new ArrayList<Integer>();
paddle = new Rectangle(getWidth()/2-paddleWidth, getHeight()-96, paddleWidth, 12);
ball = new Rectangle(getWidth()/2-ballSize, 96, ballSize, ballSize);
}
public void update(Graphics g) {
dbImage = createImage(getSize().width, getSize().height);
dbg = dbImage.getGraphics ();
if (dbImage == null) {}
dbg.setColor(getBackground ());
dbg.fillRect(0, 0, getSize().width, getSize().height);
dbg.setColor(getForeground());
paint(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
if (level != 0) {
g2.setPaint(Color.gray);
g2.fill(paddle);
g2.setPaint(Color.darkGray);
g2.fill(ball);
moveBall();
}
}
public void moveBall() {
bally = ball.y;
ballx = ball.x;
if (bally < paddle.y-32 && falling) {
bally += 12;
}
if (bally < paddle.y-32 && falling && paddle.x <= ballx && paddle.getMaxX() >= ball.x) { // collides with paddle
falling = false;
}
else { // does not collide with paddle
}
ball.setLocation(ballx, bally);
}
#Override
public void keyPressed(KeyEvent e) {
if (!keysDown.contains(e.getKeyCode()))
keysDown.add(new Integer(e.getKeyCode()));
key();
}
#Override
public void keyReleased(KeyEvent e) {
keysDown.remove(new Integer(e.getKeyCode()));
}
public void key() {
if (level != 0) {
int x = paddle.x;
int y = paddle.y;
if (keysDown.contains(KeyEvent.VK_ESCAPE)) {System.exit(0);}
if (x > 0 && x+paddleWidth < this.getWidth()) {
if (keysDown.contains(KeyEvent.VK_LEFT)) {x -= speed;}
if (keysDown.contains(KeyEvent.VK_RIGHT)) {x += speed;}
}
else { // so paddle doesn't exit room
if (x <= 0) {x += 4;}
else {x -= 4;}
}
paddle.setLocation(x, y);
repaint();
}
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void mouseClicked(MouseEvent me) {
if (level == 0) {
xpos = me.getX();
ypos = me.getY();
if (xpos >= START_X_POS && ypos >= START_Y_POS && xpos <= START_X_POS + START_WIDTH && ypos <= START_X_POS + START_HEIGHT ) {
level = 1;
}
}
}
#Override
public void mouseEntered(MouseEvent me) {}
#Override
public void mouseExited(MouseEvent me) {}
#Override
public void mouseReleased(MouseEvent me) {}
#Override
public void mousePressed(MouseEvent me) {}
}
Any help would be greatly appreciated!
You'll probably want a separate Thread to move the ball which keeps track of time while in a in a loop - that way if frame rates drop, or speed up, you can try ensure consistency in the ball movement speed.
e.g. here on using a thread in a applet http://www.realapplets.com/tutorial/threadexample.html

SubKiller game not firing properly when press my fire key

I have the following program, it's a SubKiller game and I have one question. How do I make the boat launch the bomb anytime I press the down key? So far I have made to launch it multiple times. I can launch the first bomb but when I'm trying to launch the second one, the first one disappears and it doesn't continue it's way. I am stuck on this matter for almost two days, help me please.
I am going to provide you the SSCCE code.
This is the class called SubKillerPanel, basically everything is here, the boat is here, the bomb is here, the submarine is here.
import java.awt.event.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Color;
public class SubKillerPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Timer timer;
private int width, height;
private Boat boat;
private Bomb bomb;
private Submarine sub;
public SubKillerPanel() {
setBackground(Color.WHITE);
ActionListener action = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (boat != null) {
boat.updateForNewFrame();
bomb.updateForNewFrame();
sub.updateForNewFrame();
}
repaint();
}
};
timer = new Timer( 20, action );
addMouseListener( new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
requestFocus();
}
}
);
addFocusListener( new FocusListener() {
public void focusGained(FocusEvent evt) {
timer.start();
repaint();
}
public void focusLost(FocusEvent evt) {
timer.stop();
repaint();
}
}
);
addKeyListener( new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int code = evt.getKeyCode(); // ce tasta a fost apasata
if (code == KeyEvent.VK_LEFT) {
boat.centerX -= 15;
}
else
if (code == KeyEvent.VK_RIGHT) {
boat.centerX += 15;
}
else
if (code == KeyEvent.VK_DOWN) {
if (bomb.isFalling == false)
bomb.isFalling = true;
bomb.centerX = boat.centerX;
bomb.centerY = boat.centerY;
}
}
}
);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (boat == null) {
width = getWidth();
height = getHeight();
boat = new Boat();
sub = new Submarine();
bomb = new Bomb();
}
if (hasFocus())
g.setColor(Color.CYAN);
else {
g.setColor(Color.RED);
g.drawString("CLICK TO ACTIVATE", 20, 30);
g.setColor(Color.GRAY);
}
g.drawRect(0,0,width-1,height-1);
g.drawRect(1,1,width-3,height-3);
g.drawRect(2,2,width-5,height-5);
boat.draw(g);
sub.draw(g);
bomb.draw(g);
}
private class Boat {
int centerX, centerY;
Boat() {
centerX = width/2;
centerY = 80;
}
void updateForNewFrame() {
if (centerX < 0)
centerX = 0;
else
if (centerX > width)
centerX = width;
}
void draw(Graphics g) {
g.setColor(Color.blue);
g.fillRoundRect(centerX - 40, centerY - 20, 80, 40, 20, 20);
}
}
private class Bomb {
int centerX, centerY;
boolean isFalling;
Bomb() {
isFalling = false;
}
void updateForNewFrame() {
if (isFalling) {
if (centerY > height) {
isFalling = false;
}
else
if (Math.abs(centerX - sub.centerX) <= 36 && Math.abs(centerY - sub.centerY) <= 21) {
sub.isExploding = true;
sub.explosionFrameNumber = 1;
isFalling = false; // Bomba reapare in barca
}
else {
centerY += 10;
}
}
}
void draw(Graphics g) {
if ( !isFalling ) {
centerX = boat.centerX;
centerY = boat.centerY + 23;
}
g.setColor(Color.RED);
g.fillOval(centerX - 8, centerY - 8, 16, 16);
}
}
private class Submarine {
int centerX, centerY;
boolean isMovingLeft;
boolean isExploding;
int explosionFrameNumber;
Submarine() {
centerX = (int)(width*Math.random());
centerY = height - 40;
isExploding = false;
isMovingLeft = (Math.random() < 0.5);
}
void updateForNewFrame() {
if (isExploding) {
explosionFrameNumber++;
if (explosionFrameNumber == 30) {
centerX = (int)(width*Math.random());
centerY = height - 40;
isExploding = false;
isMovingLeft = (Math.random() < 0.5);
}
}
else {
if (Math.random() < 0.04) {
isMovingLeft = ! isMovingLeft;
}
if (isMovingLeft) {
centerX -= 5;
if (centerX <= 0) {
centerX = 0;
isMovingLeft = false;
}
}
else {
centerX += 5;
if (centerX > width) {
centerX = width;
isMovingLeft = true;
}
}
}
}
void draw(Graphics g) {
g.setColor(Color.BLACK);
g.fillOval(centerX - 30, centerY - 15, 60, 30);
if (isExploding) {
g.setColor(Color.YELLOW);
g.fillOval(centerX - 4*explosionFrameNumber, centerY - 2*explosionFrameNumber,
8*explosionFrameNumber, 4*explosionFrameNumber);
g.setColor(Color.RED);
g.fillOval(centerX - 2*explosionFrameNumber, centerY - explosionFrameNumber/2,
4*explosionFrameNumber, explosionFrameNumber);
}
}
}
}
The SubKiller class, where the main method is located.
import javax.swing.JFrame;
public class SubKiller {
public static void main(String[] args) {
JFrame window = new JFrame("Sub Killer Game");
SubKillerPanel content = new SubKillerPanel();
window.setContentPane(content);
window.setSize(700, 700);
window.setLocation(0,0);
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);
window.setVisible(true);
}
}
You only have a single Bomb being tracked by the graphics at any time. You should build a collection of Bombs and instantiate a new one whenever the down key is pressed, then iterate through all the collection of Bombs and draw them as needed.
So, instead of private Bomb bomb;
You would have private List<Bomb> bombs;
Afterwards, anywhere you update the single bomb you can use a for loop to go through the list of bombs and have them all update, and then if they are no longer being drawn, remove them from the list.

Categories

Resources