我正在将我编写的Javascript程序转换为Java,并且有一个对象,我不确定如何用Java编写.
tetros.types = new Array();
tetros.types[0] = new Object();
tetros.types[0].color = "green";
tetros.types[0].rotations = new Array();
tetros.types[0].rotations[0] = new Object();
tetros.types[0].rotations[0].blocks = Array([0,0],[1,[2,1]);
tetros.types[0].rotations[0].edges ={
"down" :Array([2,1]),"left" :Array([0,0]),"right" :Array([2,1],[0,"up" :Array([0,1])
}
tetros.types[0].rotations[1] = new Object();
tetros.types[0].rotations[1].blocks = Array([0,2],0]);
tetros.types[0].rotations[1].edges ={
"down" :Array([0,"right" :Array([0,0])
}
tetros.types[0].rotations[2] = new Object();
tetros.types[0].rotations[2].blocks = Array([0,1]);
tetros.types[0].rotations[2].edges ={
"down" :Array([0,1])
}
tetros.types[0].rotations[3] = new Object();
tetros.types[0].rotations[3].blocks = Array([0,2]);
tetros.types[0].rotations[3].edges ={
"down" :Array([1,2]),"left" :Array([1,1])
}
tetros.types[1] = new Object();
tetros.types[1].color = "blue";
tetros.types[1].rotations = new Array();
tetros.types[1].rotations[0] = new Object();
tetros.types[1].rotations[0].blocks = Array([0,1]);
tetros.types[1].rotations[0].edges ={
"down" :Array([1,1])
}
tetros.types[1].rotations[1] = new Object();
tetros.types[1].rotations[1].blocks = tetros.types[1].rotations[0].blocks;
tetros.types[1].rotations[1].edges = tetros.types[1].rotations[0].edges;
tetros.types[1].rotations[2] = new Object();
tetros.types[1].rotations[2].blocks = tetros.types[1].rotations[0].blocks;
tetros.types[1].rotations[2].edges = tetros.types[1].rotations[0].edges;
tetros.types[1].rotations[3] = new Object();
tetros.types[1].rotations[3].blocks = tetros.types[1].rotations[0].blocks;
tetros.types[1].rotations[3].edges = tetros.types[1].rotations[0].edges;
这大约占整个物体的1/4,但其余部分则相同.
我怎么能用Java写这个呢?
最佳答案
我会从最深层开始,从那里开始向后工作,考虑如何将每组属性转换为类的实例变量,例如:
原文链接:https://www.f2er.com/java/437865.htmlint[][] blocks;
int[][] edges;
(请注意,Java不支持关联数组,例如“向下”,“向上”等).
然后你可以把它们放到课堂上.从你的代码中,这些似乎是旋转的属性,所以我建议像:
class Rotation {
// Instance variables
private int[][] blocks;
private int[][] edges;
// Constructor
public Rotation(int[][] blocks,int[][] edges) {
this.blocks = blocks;
this.edges = edges;
}
// Accessors and mutators here if applicable
}
然后像:
class Type {
private Rotation[] rotations;
private String color;
// etc etc
}
等等.虽然你似乎对某些正式的面向对象概念不熟悉(例如封装),所以我建议你在尝试将它移植到Java之前阅读一些涵盖类和对象基础知识的Java教程.