gpt4 book ai didi

java - 为《太空侵略者》游戏移动 2D 阵列

转载 作者:行者123 更新时间:2023-11-30 06:53:45 25 4
gpt4 key购买 nike

所以标题几乎解释了这一切,最近我了解了 2D 数组,但我对如何在我正在创建的这个 Space Invaders 游戏中使 2D 数组正确移动感到有点困惑。

现在我让外星人从左到右移动(反之亦然),但是,它们并不是同时向下移动,而是逐列向下移动。有人知道在哪里编辑代码吗?

这是我的外星人代码:

class Aliens {

int x = 100, y = 75, deltaX = 1;

Aliens (int x, int y) {
this.x = x;
this.y = y;
}

void drawAlien() {
fill(255);
rect(x, y, 25, 25);
}

void moveAlien() {
x = x + deltaX;
if (x >= width) {
y = y + 20;
deltaX = - deltaX;
} else if (x <=0) {
y = y + 20;
deltaX = - deltaX;
}
}

void updateAlien() {
drawAlien();
moveAlien();
}
}

和我的主课:

import ddf.minim.*;

//Global Variables
PImage splash;
PFont roboto;
Defender player;
Aliens[][] alienArray = new Aliens[15][3];
Missile missile;
int gameMode = 0;
int score = 0;

void setup() {
size(1000, 750);
rectMode(CENTER);
textAlign(CENTER, CENTER);
splash = loadImage("Splash.png");
player = new Defender();
for (int row = 0; row < 15; row++) {
for (int column = 0; column < 3; column++) {
alienArray[row][column] = new Aliens((row + 1) * 50, (column + 1) * 50);
}
}
roboto = createFont("Roboto-Regular.ttf", 32);
textFont(roboto);
}

void draw() {
if (gameMode == 0) {
background(0);
textSize(75);
text("Space Invaders", width/2, height/8);
textSize(25);
text("Created by Ryan Simms", width/2, height/4);
textSize(45);
text("Press SPACE to Begin", width/2, height - 100);
image(splash, width/2-125, height/4 + 75);
} else if (gameMode == 1) {
background(0);
score();
player.updateDefender();
for (int row = 0; row < 10; row ++) {
for (int column = 0; column < 3; column++) {
alienArray[row][column].updateAlien();
}
}
if (missile != null) {
missile.updateMissile();
}
if (keyPressed) {
if (key == ' ') {
if (missile == null) {
missile = new Missile(player.x);
}
}
}
if (missile != null) {
if (missile.y <= 0) {
missile = null;
}
}
}
}

void score() {
textSize(20);
text("Score: " + score, 40, 15);
}

void keyPressed() {
if (key == ' ') {
gameMode = 1;
}
}

最佳答案

逻辑缺陷位于 moveAlien()方法。您移动x外星人的位置有一定的增量。如果检测到外星人已通过某些屏幕边界(x >= widthx <=0 检查),则反转增量以反转外星人的移动,并更新 y位置使其向下移动。

由于外星人是按垂直列定向的,因此其中一列总是会到达这样的边界,而其他列还没有到达。这样该柱就会下降,并开始恢复其运动。其他列稍后将“ catch ”。因此,它们不仅每列向下移动,而且这些列最终也会相互移动。

你必须实现一些逻辑,让你的外星人作为一个方 block 移动,通过检测最右边的剩余外星人何时到达右边界,或者最左边的剩余外星人何时到达左边界,然后进行更新所有外星人都向下移动。

让每个外星人都有自己的状态,将控制它的逻辑放在外星人类中并调用,这实际上是很好的面向对象设计。碰巧的是,对于《太空侵略者》来说,外星人都会互相影响,因为他们在一个街区中移动。结果,你的设计导致它们具有太多的个性。也许您可以添加一些类来维护整个入侵者数组的状态(例如最左边和最右边的列仍然有一个外星人,整个 block 的方向),在您的移动循环中控制它并让它更新外星人的位置转。

关于java - 为《太空侵略者》游戏移动 2D 阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42205420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com