你好,我最近開始開發一款貪吃蛇遊戲。我正處於開始階段,我有一個移動的物體和一個圓點,但我的主要問題是如何檢查蛇是否「吃」了點,以及如何讓它消失?
任何幫助將不勝感激。貪吃蛇Java Gui
這裏是下面的代碼:第一
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);
}
您需要保留對蛇的「頭部」和「目標」的引用。如果頭部和目標位於同一點,則它吃了它,一旦吃完,您將重置「治療」到新位置或將其設置爲「空」,並允許下一個繪製週期更新圖形。您將需要使用類似的技術來檢測蛇是否自行進入。 – MadProgrammer
我讀得很快,看來你讀了蛇的x和y,爲什麼不把它們與點的x和y進行比較?如果它們是相同的,那麼你知道蛇正在通過這個點。 順便說一下,你的代碼有點混亂,我看不到你在哪裏使用pointx和pointy來創建點... 我想你應該停下來,重新考慮一下結構項目。 您可以創建一個類「點」,代表蛇的「食物」。 然後,你需要一個類蛇,由許多點形成,並且將其移動(搭末點,並把它的頭後) 等.. – Gianmarco