I am making a game in java in which a disc is thrown through a hoop. The hoop's Y position is a random number and i would like to make this number change every time another hoop is generated.
Here is my code:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.util.Random;
@
SuppressWarnings("serial")
public class DiscHoopToss extends JPanel {
int x = 40;
int y = 150;
int xm = 0;
int ym = 0;
Random rng = new Random();
int r = rng.nextInt((220 - 20) + 1) + 20;
public DiscHoopToss() {
addKeyListener(new KeyListener() {
@
Override
public void keyTyped(KeyEvent e) {}
@
Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
ym = -4;
xm = 3;
}
}
@
Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
ym = 2;
xm = 3;
}
}
});
setFocusable(true);
}
private void moveDisc() {
x = x + xm;
y = y + ym;
if (y == 0) {
JOptionPane.showMessageDialog(this, "Don't let the disc go off the screen!", "Game Over", JOptionPane.ERROR_MESSAGE);
y = 150;
x = 40;
xm = 0;
ym = 0;
}
if (y == getHeight() - 20) {
JOptionPane.showMessageDialog(this, "Don't let the disc go off the screen!", "Game Over", JOptionPane.ERROR_MESSAGE);
y = 150;
x = 40;
ym = 0;
xm = 0;
}
}
@
Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawOval(x, r, 25, 55);
g2d.fillOval(650, y, 50, 20);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Toss the disc into the hoop!");
DiscHoopToss game = new DiscHoopToss();
frame.add(game);
frame.setSize(750, 350);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.moveDisc();
game.repaint();
Thread.sleep(10);
}
}
}
Aucun commentaire:
Enregistrer un commentaire