我开始研究我的第一个java项目,它是一种非常基本的角色扮演游戏(当然没有gui)。现在我正在处理咒语。我创造了#34; Spell"类(包括名称,效果和成本)。我创建了SpellsList类,应该包括所有法术。我有"效果"描述法术效果的类(它仅适用于现在的测试)。当一个施法者施放一个咒语然后我想获得相关的法术效果时,相关的效果将会影响法术的效果(我以后会对这些效果起作用,现在它就是'仅用于测试)。我有一个骰子,但现在不重要。
我有几个问题:
你会以更好的方式实施法术吗?
public class Spell {
private String name;
private String effect;
private int cost;
Spell(String name, String effect, int cost){
this.name = name;
this.effect = effect;
this.cost = cost;
}
String getSpellName(){
return name;
}
String getEffect(){
return effect;
}
int getCost(){
return cost;
}
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SpellsList {
public static void main(String[] args) {
List<Spell> spellsList = new ArrayList<Spell>();
spellsList.add(new Spell("Fireball", "damage", 5));
spellsList.add(new Spell("Ice Storm", "damage", 8));
spellsList.add(new Spell("Heal", "heal", 8));
static String getSpellEffect(String spellName) {
for (Iterator iter = spellsList.iterator(); iter.hasNext(); ) {
if (iter.next().equals(spellName)) {
iter.next().Spell.getEffect();
break;
}
}
}
}
}
public class Effects {
int damage(int n, int dice, int bonus){
int damage = Dice.roll(n,dice,bonus);
System.out.println("You dealt" + damage + "damage to the enemy!");
return damage;
}
int heal(int n, int dice, int bonus){
int heal = Dice.roll(n,dice,bonus);
System.out.println("You healed" + heal + " hit points!");
return heal;
}
}
public class Dice {
public static int roll(int dice){
int sum = 1 + (int)(Math.random() * ((dice - 1) + 1));
return sum;
}
public static int roll(int n, int dice){
int sum = 0;
for (int i = 0; i < n; i++) {
sum += 1 + (int)(Math.random() * ((dice - 1) + 1));
}
return sum;
}
public static int roll(int n, int dice, int bonus){
int sum = 0;
for (int i = 0; i < n; i++) {
sum += 1 + (int)(Math.random() * ((dice - 1) + 1));
}
return (sum + n*bonus);
}
}
答案 0 :(得分:0)
你在main()方法中有一个名为getSpellEffect()的方法。你不能在方法中使用方法。查看Methods inside methods
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SpellsList {
static List<Spell> spellsList = new ArrayList<Spell>();
static {
spellsList.add(new Spell("Fireball", "damage", 5));
spellsList.add(new Spell("Ice Storm", "damage", 8));
spellsList.add(new Spell("Heal", "heal", 8));
}
static String getSpellEffect(String spellName) {
String spellEffect = "";
for (Iterator<Spell> iter = spellsList.iterator(); iter.hasNext();) {
Spell spell = iter.next();
if (spellName.equals(spell.getSpellName())) {
spellEffect = spell.getEffect();
break;
}
}
return spellEffect;
}
}
<强> Main.java 强>
public class Main {
public static void main(String[] args) {
System.out.println(SpellsList.getSpellEffect("Fireball"));
}
}