您好我最近开始开发一个蛇游戏。我处于开始阶段,我有一个移动的物体和一个可以吃的点,但我的主要问题是如何检查蛇是否“吃”了这个点,我怎样才能让它消失?
任何帮助将不胜感激。
这是以下代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import java.awt.*;
import java.util.Random;
import javax.swing.JPanel;
public class Gui extends JPanel implements ActionListener,KeyListener{
Random rnd= new Random();
int pointx=100 + (int)(Math.random() * ((400- 100) + 1));;
int pointy=100 + (int)(Math.random() * ((300 - 100) + 1));
private String text;
Timer tm = new Timer(5, this);
int x = 300, y = 178, velx = 0, vely = 0;
public Gui()
{
tm.start();
addKeyListener(this);
setFocusable(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(x, y, 35, 15);
g.setColor(Color.BLACK);
g.fillOval(pointx,pointy, 20,20);
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode();
if (c == KeyEvent.VK_LEFT)
{
velx = -1;
vely = 0;
}
if (c == KeyEvent.VK_UP)
{
velx = 0;
vely = -1;
}
if (c == KeyEvent.VK_RIGHT)
{
velx = 1;
vely = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velx = 0;
vely = 1;
}
}
public void actionPerformed(ActionEvent e)
{
x += velx;
y += vely;
repaint();
borders(e);
}
public void borders(ActionEvent e) {
if (x < 0) {
velx = 0;
x = 0;
JOptionPane
.showMessageDialog(null, "you hit the borders you lost!");
System.exit(0);
}
if (x > 530) {
velx = 0;
x = 530;
JOptionPane
.showMessageDialog(null, "you hit the borders you lost!");
System.exit(0);
}
if (y < 0) {
velx = 0;
y = 0;
JOptionPane
.showMessageDialog(null, "you hit the borders you lost!");
System.exit(0);
}
if (y > 330) {
velx = 0;
y = 330;
JOptionPane
.showMessageDialog(null, "you hit the borders you lost!");
System.exit(0);
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("gui");
frame.add(new Gui());
frame.setVisible(true);
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}