首先,我们将定义游戏中使用的常量。
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
B_WIDTH 和 B_HEIGHT 常量决定了棋盘的大小。 DOT_SIZE 是苹果的大小和蛇的点。
ALL_DOTS 常量定义板上可能的最大点数 (900 = (300*300)/(10*10))。 RAND_POS 常量用于计算苹果的随机位置。 DELAY 常量决定了游戏的速度。
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
这两个数组存储了蛇所有关节的 x 和 y 坐标。
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
在 loadImages() 方法中,我们获取游戏的图像。 ImageIcon 类用于显示 PNG 图像。
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
在 initGame() 方法中,我们创建了蛇,在棋盘上随机定位一个苹果,并启动计时器。
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
如果苹果与头部发生碰撞,我们会增加蛇的关节数。我们调用 locateApple() 方法随机定位一个新的苹果对象。
在 move() 方法中,我们有游戏的关键算法。要了解它,请查看蛇的移动方式。我们控制蛇的头。我们可以用光标键改变它的方向。其余关节向上移动一个位置。第二个关节移动到第一个关节所在的位置,第三个关节移动到第二个关节所在的位置,依此类推。
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
此代码将关节向上移动链。
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
这条线将头部向左移动。
在 checkCollision() 方法中,我们确定蛇是撞到自己还是撞到其中一堵墙。
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
如果蛇用头撞到其中一个关节,游戏就结束了。
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
如果蛇撞到棋盘底部,游戏就结束了。
完整源代码: http://geekonjava.blogspot.com/2015/07/make-snake-game-in-swing.html