随机方向 [英] Random directions
问题描述
您好,我正忙于学习 Java,我正忙于创建 pacman 游戏,但现在我需要让幽灵朝着随机"方向移动,因此这个方向必须时不时地垂直/水平改变,反之亦然
Hello I am busy with learning Java and I am busy creating a pacman game but now I need to let the ghosts move in a "Random" direction and so now and then this direction has to change vertically/horizontally and vica versa
此刻鬼从左到右,从右到左.负责这个动作的代码如下:(忽略pacman绘图部分见下文//ghost运动)
at the moment the ghost goes from left to right and right to left. the code that is responsible for this action is as follows: (ignore pacman drawing part see below //ghost movement)
DrawPacMan pacman = new DrawPacMan();
DrawGhost ghost = new DrawGhost();
int g1x = 0;
boolean g1r = true;
public void paintComponent(Graphics g) {
super.paintComponent(g);
// pacman movement
diameter = 25;
pacman.drawPacMan(g, getHorPlaats(), getVerPlaats(), diameter, getView(), Color.yellow);
// ghosts movement
g1x += ghostSpeed * (g1r? 1 : -1);
// check direction
if (g1x >= 500) { g1x = 500; g1r = false; }
else if (g1x <= 0) { g1x = 0; g1r = true; }
ghost.drawGhost(g, g1x, 40, diameter, Color.red);
}
现在我不知道如何创建随机方向或使用什么函数.有人可以给我一些提示/帮助,如果可能的话,我可以提供一个我可以进一步使用的小例子吗?如果您想查看更多代码或其他内容,请询问,我会发布 :)
Now I don't know how to create a random direction or what functions to use. Can someone give me some hints/help and if possible a little example that I can work further with? and if you want to see more code or something please ask and i'll post :)
推荐答案
对于像这样简单的事情,我会生成一个随机数,0、1、2 或 3.这将为您提供所需的所有方向: 上、下、左、右.
For something simple like this, I'd generate a random number, either 0, 1, 2, or 3. This will give you all the directions you need: up, down, left, and right.
import java.util.Random;
// create a random number generator
Random randomGen = new Random();
// generate a random number, between 0 and n-1 (0,1,2,3 in this case)
int theRandomNumber = randomGen.nextInt(4);
public void setRandomGhostDirection() {
switch(theRandomNumber) {
case 0:
moveUp();
break;
case 1:
moveLeft();
break;
case 2:
moveRight();
break;
case 3:
moveDown();
break;
}
}
您可以通过将方向编号定义为类似的东西来清理它final int DIRECTION_UP = 0
等等
You could clean this up by defining the direction numbers as something like
final int DIRECTION_UP = 0
etc.
这篇关于随机方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!