old code
目前,我正在尝试制作一个游戏,用鼠标控制一个会移动的方块,收集小球。每次产生球时,都会出现敌人,并以线性路径移动。
我的程序试图实现这一目标,但是敌人都立刻生成,并且只向右移动。食物在食用后不会消失。取而代之的是,当我移动鼠标时,食物会在整个地方闪烁,而敌人则全部移向右侧。我不确定如何使食物出现一次并停留在那儿,然后当玩家吃掉它时,它消失并产卵另一些卵,并产生一个左右移动或上下移动并反弹的敌人离开墙壁。
我想将食物放在一个地方,然后在吃的时候删除食物,然后再随机产生另一个。
我正在尝试make something similar to this.
谢谢你的帮助。
编辑:@AJC的答案中基于psuedocode的新代码
import java.util.ArrayList;
import java.util.Random;
public class Game{
public static void main(String[] args) {
StdDraw.setXscale(0,100);
StdDraw.setYscale(0,100);
int foodX = 0;
int foodY = 0;
ArrayList enemyXPos = new ArrayList();
ArrayList enemyYPos = new ArrayList();
ArrayList enemySpeeds = new ArrayList();
int score = 0;
Random rand = new Random();
while (true) {
double playerX = StdDraw.mouseX();
double playerY = StdDraw.mouseY();
StdDraw.clear();
int enemyX = 0, enemyY = 0;
if (playerX == foodX && playerY == foodY) {
score += 1;
foodX = rand.nextInt(100);
foodY = rand.nextInt(100);
enemyX = rand.nextInt(100);
enemyY = rand.nextInt(100);
enemyXPos.add(enemyX);
enemyYPos.add(enemyY);
int enemySpeed = rand.nextInt(20);
enemySpeeds.add(enemySpeed);
}
for (int j = 0; j < enemyXPos.size()-1; j++) {
if ((int) enemyXPos.get(j) == playerX && (int) enemyYPos.get(j) == playerY) {
break;
}
}
for (int j = 0; j < enemyXPos.size()-1; j++) {
enemyXPos.add(j, (int) enemyXPos.get(j) + (int) enemySpeeds.get(j));
enemyYPos.add(j, (int) enemyXPos.get(j) + (int) enemySpeeds.get(j));
}
StdDraw.setPenColor(StdDraw.BLUE);
StdDraw.filledCircle(playerX, playerY, 5);
StdDraw.setPenColor(StdDraw.GREEN);
StdDraw.filledCircle(foodX, foodY, 2);
for (int j = 0; j < enemyXPos.size()-1; j++) {
StdDraw.setPenColor(StdDraw.RED);
StdDraw.filledCircle(enemyX, enemyY, 2);
}
StdDraw.show();
}
}
}
最佳答案
您的代码中有几个问题
您在每个游戏循环中都将食物设置为随机位置,因此食物不会停留在一处。您需要记住当前食物的位置,并仅在玩家触摸时设置一个新位置
敌人全部由一个变量控制,因此它们显然都将朝同一方向移动
还有其他一些逻辑缺陷,例如当玩家不移动时,其他对象的更新会被跳过
我还建议将代码分为几部分,例如将绘制和更新周期分开
新的伪代码:
Variables:
- Current food position
- List of enemy positions
- List of enemy velocities
Game loop:
//Update stuff
Get mouse location
Set player location to mouse location
If player is touching food then
Increase score
Set food position to random position
Spawn new enemy:
Add new random position to enemy position list
Add new random velocity to enemy velocity list
End if
For each enemy:
If enemy is touching player than
End game
End if
End for
For each enemy:
Update enemy location:
Add velocity of enemy to position of enemy
(posX=posX+velX)
(posY=posY+velY)
End for
//Draw stuff
Draw player
Draw food
For each enemy:
Draw that enemy
End for
End game loop
关于java - 食物闪动,在躲避游戏中不被食用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37821435/