我正在用一些软件设计模式用Java构建俄罗斯方块游戏基本上,我创建了一个工厂算法,检索一个字符串,以确定当主游戏循环给它一个请求时,要生成什么类型的俄罗斯方块对象,请参见代码:
public class TVShapeFactory {
protected TVShape tvShape = null;
protected GameContainer gc;
TVShapeFactory(GameContainer gc) {
this.gc = gc;
}
public TVShape createShape(String shape) {
if (shape=="TVIShape") {
tvShape = new TVIShape(gc);
}
else if (shape=="TVOShape") {
tvShape = new TVOShape(gc);
}
else if (shape=="TVLShape") {
tvShape = new TVLShape(gc);
}
else if (shape=="TVZShape") {
tvShape = new TVZShape(gc);
}
else if (shape=="TVJShape") {
tvShape = new TVJShape(gc);
}
else if (shape=="TVSShape") {
tvShape = new TVSShape(gc);
}
else if (shape=="TVTShape") {
tvShape = new TVTShape(gc);
}
else {
System.out.println("Error: invalid type of shape");
}
return tvShape;
}
}
如果你不知道gc是什么,它只是slick 2d库的一部分,用于处理整个游戏环境。
无论如何,我创建了一些其他方法来随机生成游戏的形状(这样主游戏循环每次都会收到一个随机形状,但我觉得RNG不会剪切它,我想让它更难我注意到有一个著名的俄罗斯方块算法叫做bastet俄罗斯方块,但对我来说没有意义。你们有什么建议来制作一个硬俄罗斯方块形状生成算法吗?下面是我的简单RNG算法:
public TVShape getRandomShape() {
TVShape[] shapes = new TVShape[7];
shapes[0] = createShape("TVIShape");
shapes[1] = createShape("TVOShape");
shapes[2] = createShape("TVLShape");
shapes[3] = createShape("TVZShape");
shapes[4] = createShape("TVJShape");
shapes[5] = createShape("TVSShape");
shapes[6] = createShape("TVTShape");
int index = new Random().nextInt(shapes.length);
return shapes[index];
}
最佳答案
而不是“==”符号使用.equals()函数来比较字符串。
==用于检查两个字符串是否具有相同的引用。
而.equals()方法用于检查两个字符串是否具有相同的值。
而不是
(shape=="TVIShape")
使用
(shape.equals("TVIShape")