私は蛇の試合をしようとしています。私はこの問題を解決したいと思います。私は食べ物に問題があります。 snakeheadの座標が食物の座標と一致するときにスコアが増分されません。私の疑問は 'foodPhysics()'メソッドにあります。私は初心者ですから、良い説明が参考になるかもしれません。食べ物に影響を与えない蛇とのコリソン
public class Game2 extends JComponent implements ActionListener, KeyListener {
public int x = 350, y = 350;
public static Game2 game;
public boolean up, down, left, right;
public int vx, vy, fx, fy, score;
public Random generator;
public static void main(String[] args) {
game = new Game2();
}
public Game2() {
generator = new Random();
fx = 7 + generator.nextInt(780);
fy = 7 + generator.nextInt(780);
JFrame window = new JFrame("Game");
window.setSize(700, 700);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer t = new Timer(10, this);
window.add(this);
window.addKeyListener(this);
window.setVisible(true);
head = new Point(x, y);
t.start();
}
@Override
public void actionPerformed(ActionEvent e) {
if (up) {
vy = -10;
y = y + vy;
}
if (down) {
vy = 10;
y = y + vy;
}
if (left) {
vx = -10;
x = x + vx;
}
if (right) {
vx = 10;
x = x + vx;
}
if (x == 0 && vx == -10) {
x = 800;
vy = 0;
}
if (x == 800 && vx == 10) {
x = 0;
vy = 0;
}
if (y == 0 && vy == -10) {
y = 800;
vx = 0;
}
if (y == 800 && vy == 10) {
y = 0;
vx = 0;
}
repaint();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
if (c == KeyEvent.VK_UP) {
up = true;
down = false;
left = false;
right = false;
}
if (c == KeyEvent.VK_DOWN) {
up = false;
down = true;
left = false;
right = false;
}
if (c == KeyEvent.VK_LEFT) {
up = false;
down = false;
left = true;
right = false;
}
if (c == KeyEvent.VK_RIGHT) {
up = false;
down = false;
left = false;
right = true;
}
if (foodPhysics() == true) {
score++;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(x, y, 15, 15);
foodRender(g);
g.setFont(new Font("Arial", 25, 25));
g.drawString(Integer.toString(score), 500, 500);
}
public void foodRender(Graphics g) {
g.setColor(Color.RED);
g.fillRect(fx, fy, 15, 15);
}
public boolean foodPhysics() {
if (x == fx && y == fy) {
return true;
}
return false;
}
}
コードを再フォーマットして読み込めますか? – xenteros
私はそれらのコードを編集し、再フォーマットしました。すぐに表示されるはずです。 @xenteros – byxor