뱀 게임을하려고하는데 계속하기 전에이 문제를 해결하고 싶습니다. 음식에 문제가 있습니다. 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