我正在用Java做一个简单的游戏,它运行得很好。但我希望有更多的敌人出现在屏幕上,而不仅仅是一个。您将在我的代码中看到,我使用了x和y变量来表示敌人的位置。我希望有一种产卵方法,每次你调用这个方法时,都会产生一个敌人(所以有多个敌人)。
代码:
import java.awt.*;
public class Enemy {
static int x = -100;
static int y = -100;
private boolean level2 = false;
private boolean level3 = false;
private boolean level4 = false;
private boolean level5 = false;
private boolean level6 = false;
private boolean level7 = false;
private boolean level8 = false;
private boolean level9 = false;
private boolean level10 = false;
Player player;
public Enemy(Player player) {this.player = player;}
public void update(){
if(player.getX() < x){
x -= 2;
}
if(player.getX() > x){
x += 2;
}
if(player.getY() > y){
y += 2;
}
if(player.getY() < y){
y -= 2;
}
}
public void scoreMethod(){
if(GameClass.score == 500){
level2 = true;
}
if(GameClass.score == 1000){
level3 = true;
}
if(GameClass.score == 1500){
level4 = true;
}
if(GameClass.score == 2000){
level5 = true;
}
if(GameClass.score == 2500){
level6 = true;
}
if(GameClass.score == 3000){
level7 = true;
}
if(GameClass.score == 3500){
level8 = true;
}
if(GameClass.score == 4000){
level9 = true;
}
if(GameClass.score == 4500){
level10 = true;
}
}
public void paint(Graphics g){
g.setColor(Color.ORANGE);
g.fillRect(x, y, 20, 20); //THE ACTUAL SPAWNING OF ONE ENEMY
if(level2)
g.fillRect(x, y, 20, 20); //HERE SHOULD SPAWN THE SECOND ONE(I TRIED)
if(level3)
g.fillRect(x, y, 20, 20);
if(level4)
g.fillRect(x, y, 20, 20);
if(level5)
g.fillRect(x, y, 20, 20);
if(level6)
g.fillRect(x, y, 20, 20);
if(level7)
g.fillRect(x, y, 20, 20);
if(level8)
g.fillRect(x, y, 20, 20);
if(level9)
g.fillRect(x, y, 20, 20);
if(level10)
g.fillRect(x, y, 20, 20);
}}
我很抱歉我的英语不好或问题不清楚。请帮帮我,我不知道该怎么做。提前谢谢。
发布于 2015-08-28 03:45:23
您可能想创建一个敌人“类”,这将是一个单独的.java文件。在这个文件中,您将给敌人矩形和更新方法,一个绘图方法,以及他们自己的适当的x和y位置。然后,您可以使用它们的构造函数来生成它们。我建议你去看看java的“class”(不是你上学时所用的类,它们在java中被称为class)。这些将能够清理你的代码,使其更容易成为你的敌人。
发布于 2015-08-28 03:47:54
要做到这一点,最简单的方法是创建一个敌方类。
public class enemy {
int xpos;
int ypos;
public static draw(Graphics g) {
//draw the enemy at xpos and ypos
}
public enemy() {
//this is called the constructor
//set xpos and ypos to what you want
}
}保持一个敌人的数组列表,并不断循环该列表,以在指定的位置绘制敌人。通过这种方式,你还可以改变敌人的位置(让他们四处移动),以获得更酷的游戏动作。
构造函数就像类的蓝图。把一个类想象成一个对象。构造函数告诉java如何创建该对象。
发布于 2015-08-28 03:49:05
假设你有一个用来玩游戏的主类,并创建了敌人。有没有什么理由让你只做一个敌人的列表?例如,像这样的东西可能会让你的游戏变得更好。
import java.util.ArrayList;
public class Game {
public Game(){
playGame();
}
private void playGame(){
//creates 10 enemies
ArrayList <Enemy> enemies = new ArrayList <Enemy>();
for(int i = 0; i < 10; i++){
Enemy enemy = new Enemy(player);
enemies.add(enemy);
}
}
}https://stackoverflow.com/questions/32257919
复制相似问题