前回にひき続き困ってます><
タイトル画面→(Enterクリック)→ゲーム画面までできたんですが
ゲーム画面でボールとタイマーを動かしたくてやってみるとタイマーはうまく
いったのにボールが動く速度を変更できず、勝手に動いてしまいます><どう
改善すればいいでしょうか。ソースコードみにくいですが助言お願いします。
import java.awt.Color;
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.JPanel;
import javax.swing.Timer;
public class JavaGame3 {
public static void main(String age[]) {
JFrame frame = new JFrame();
frame.setTitle("ゲームフレーム");
frame.setSize(500, 550);
frame.setLocation(1000, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Testpanel panel = new Testpanel();
frame.add(panel);
frame.setVisible(true);
}
}
class Testpanel extends JPanel implements Runnable{
private Ball[] balls;
static final int TITLE = 0;
static final int GAME = 1;
private int mode;
private int sec;
private Timer timer;
private Thread t;
public Testpanel() {
balls = new Ball[5];
java.util.Random rr = new java.util.Random();
for(int i=0; i<balls.length; i++)
balls[i] = new Ball(10*i+6,10*i+31,rr.nextInt(5)+1,
rr.nextInt(5)+1);
sec = 0;
setBackground(Color.black);
addKeyListener(new JavaKeyListener());
setFocusable(true);
timer = new Timer(1000, new JavaActionListener());
mode = TITLE;
t = new Thread(this);
}
class JavaActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (sec == 30) {
timer.stop();
} else {
sec++;
}
}
}
private void drawTitle(Graphics g) {
g.setColor(Color.blue);
g.drawString("タイトル", 165, 150);
g.setColor(Color.white);
g.drawString("Hit Enter Key!", 150, 350);
}
public void drawGameOver(Graphics g) {
g.setColor(Color.white);
g.setColor(Color.red);
g.drawString(sec + "sec", 230, 300);
repaint();
for (int i=0; i<balls.length; i++)
balls[i].draw(g);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(mode == TITLE) {
drawTitle(g);
} else if(mode == GAME) {
drawGameOver(g);
}
}
class JavaKeyListener implements KeyListener {
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(mode == TITLE) {
switch(key) {
case KeyEvent.VK_ENTER:
mode = GAME;
timer.start();
t.start();
sec = 0;
break;}
} else {
switch (key) {
case KeyEvent.VK_ENTER:
mode = TITLE;
break;
}
}repaint();
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
public void run() {
while(true) {
try {
Thread.sleep(100);
} catch (Exception e) {}
repaint();
}
}
}
class Ball {
private int x, y, vx, vy, r;
public Ball(int x, int y, int vx, int vy) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
r = 30;
}
public void draw(Graphics g) {
g.fillOval(x, y, r, r);
x += vx;
y += vy;
if(x < 0 || x > 457) vx = -vx;
if(y < 0 || y > 433) vy = -vy;
}
}
お礼
解決できました