【问题标题】:Creating the Tetris shapes in Java as classes extending Area or Shape在 Java 中创建俄罗斯方块形状作为扩展区域或形状的类
【发布时间】:2014-03-02 21:29:31
【问题描述】:

我正在使用 Java 自己编写俄罗斯方块游戏。我没有使用任何已经包含代码的教程,因为我想尝试自己分解它,看看我能走多远。

到目前为止,还不是很好。我偶然发现了 Shapes 上的创作。 我的想法是: 1. 将每个基本形状(如 L、立方体、船)作为单独的类扩展或实现区域或形状,以便我可以将其用作g2.fill(LShape) 的参数。 2. 每个类都有某种描述旋转位置的状态变量,但这是下一个挑战,找出旋转..

所以对于第 1 步,到目前为止,我已经编写了以下 LShape 类的草稿:

草案a):

public class LShape implements Shape{
private Rectangle[][] poc;
private int rotationState;  

public LShape() {
    rotationState = 0;
    poc = new Rectangle[3][3];
    poc[0][0] = new Brick(INITIAL_X - BRICK, INITIAL_Y, BRICK); 
    poc[1][0] = new Brick(INITIAL_X - BRICK, INITIAL_Y + BRICK, BRICK);
    poc[2][0] = new Brick(INITIAL_X - BRICK, INITIAL_Y + 2 * BRICK, BRICK);
    poc[2][1] = new Brick(INITIAL_X, INITIAL_Y + 2 * BRICK, BRICK);
}      
}
//.....all the Shape's methods which I'm not overriding cause I don't know how

在我调用paint()方法的主类中: g2.fill(lShape); // where lShape is a LShape object; 问题是关于getPathIterator()的异常抛出

或草案 b):

public class LShape extends Area{

public LShape () {

    add(new Area(new Brick(INITIAL_X - BRICK, INITIAL_Y, BRICK)));
    exclusiveOr(new Area(new Brick(INITIAL_X - BRICK, INITIAL_Y + BRICK, BRICK)));
    exclusiveOr(new Area(new Brick(INITIAL_X - BRICK, INITIAL_Y + 2 * BRICK, BRICK)));
    exclusiveOr(new Area(new Brick(INITIAL_X, INITIAL_Y + 2 * BRICK, BRICK)));
}
}

在这种情况下,当我调用g2.fill(lShape) 时,没有异常并且绘制了形状,只是我不知道如何移动它。 Area 的一部分是 Brick 对象,它们是 Rectangles,所以我可以尝试访问 Area 中每个 Brick 上的 setLocation 方法,但我不知道如何访问它。

所以我想我需要帮助来弄清楚如何使俄罗斯方块形状的形状实现不抛出异常,这意味着实现所有必需的方法并实际显示在 JPanel 上......然后我会担心旋转。 或者弄清楚如何使俄罗斯方块形状的区域扩展移动。

谢谢,

【问题讨论】:

    标签: java shape area tetris


    【解决方案1】:

    渲染形状时,您可以在Graphics2D 实例上使用Graphics#translateAffineTransform 或使用Shape#getPathIterator(AffineTransform),但这需要更多的工作,因为您需要回绕成一个形状

    例如...

    // Call me lazy, this preserves the state of the current Graphics
    // context and makes it easy to "restore" it, simply by disposing
    // of this copy...
    Graphics2D g2d = (Graphics2D)g.create();
    g2d.translate(x, y);
    g2d.fill(shape);
    // Restores the state of the `Graphics` object...
    g2d.dispose();
    

    如果您想继续使用Area,请查看Area#createTransformedArea,它应该允许您使用AffineTransform 来转换Area,但它会返回一个Area,使其更易于使用然后Shape#getPathIterator

    这也意味着您可以生成复合变换(旋转、平移等)并生成代表变换的Area...

    【讨论】:

    • 好的,所以我想我将使用俄罗斯方块形状的区域扩展并依赖 Graphics#translate。我试了一下,它确实移动了它。我会多玩一些并进行实验,但我应该会很好。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多