Java贪吃蛇游戏实现 - 带边界碰撞检测
// Press Shift twice to open the Search Everywhere dialog and type 'show whitespaces', // then press Enter. You can now see whitespace characters in your code. package com.firefor01;
import java.awt.; import javax.swing.; import java.awt.event.; import java.util.;
public class test extends JFrame implements ActionListener { String name; JButton jbn = new JButton('开始'); D jpn = new D();
test() {
Container cn = getContentPane();
cn.setLayout(new BorderLayout());
cn.add(jbn, BorderLayout.NORTH);
cn.add(jpn, BorderLayout.CENTER);
jbn.addActionListener(this);
setSize(600, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗口关闭时退出程序
}
public void actionPerformed(ActionEvent e) {
Thread t1 = new Thread(jpn);
t1.start();
jpn.requestFocus(true);
}
public static void main(String args[]) {
new test();
}
}
class D extends JPanel implements Runnable, KeyListener {
int x = 10;
int direction = 0;
Random r = new Random();
Vector
D() {
v.add(new Point(20, 10));
v.add(new Point(20, 10));
v.add(new Point(20, 10));
v.add(new Point(20, 10));
int t = r.nextInt(20);
food.x = t * 10;
food.y = t * 10;
addKeyListener(this);
}
public void paint(Graphics g) {
super.paint(g);
for (int i = 0; i < v.size(); i++) {
Point p = v.get(i);
int x = p.x;
int y = p.y;
if (i == v.size() - 1) {
g.setColor(Color.blue);
g.fillOval(x, y, 9, 9);
} else {
g.setColor(Color.black);
g.fillOval(x, y, 9, 9);
}
}
int x = food.x;
int y = food.y;
g.setColor(Color.red);
g.fillRect(x, y, 9, 9);
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
direction = 2;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
direction = 3;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
direction = 1;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
direction = 0;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void run() {
try {
while (true) {
Point p = v.get(v.size() - 1);
if (p.x < 0 || p.x >= getWidth() || p.y < 0 || p.y >= getHeight()) { // 判断是否撞墙
JOptionPane.showMessageDialog(this, '游戏结束!', '提示', JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
for (int i = 0; i < v.size() - 1; i++) {
Point p1 = v.get(i);
Point p2 = v.get(i + 1);
p1.x = p2.x;
p1.y = p2.y;
}
if (direction == 0) {
p.x = p.x + 10;
}
if (direction == 1) {
p.x = p.x - 10;
}
if (direction == 2) {
p.y = p.y - 10;
}
if (direction == 3) {
p.y = p.y + 10;
}
for (int i = 0; i < v.size(); i++) {
Point p1 = v.get(i);
if (p1.x == food.x && p1.y == food.y) {
int t = r.nextInt(20);
food.x = t * 10;
food.y = t * 10;
v.add(new Point(p1.x, p1.y));
break;
}
}
repaint();
Thread.sleep(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
原文地址: http://www.cveoy.top/t/topic/oBIz 著作权归作者所有。请勿转载和采集!