• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
concepts

Rotating an object in a grid

2 posts in this topic

Ok, I have been scratching my head for a while, because I couldn't rotate an object. So here's what I would like to know. How do I access shape (an attribute of the class Piece) and how do I change currentPiece (which is an instance of the class object Piece)

 

Here's what I have done so far for the rotation:

 

 

public static int [][] multiplyMatrix(int [][] m1)
  {
          int [][] m2 =
        {{0,0,0,1},
         {0,0,1,0},
         {0,1,0,0},
         {1,0,0,0},
        };


    int[][] result = new int[4][4];

    // multiply
    for (int i=0; i<4; i++)
      for (int j=0; j<4; j++)
        for (int k=0; k<4; k++)
        if (m1[i][k] * m2[k][j] > 0)
        {
            result[i][j] = 1;
        }
        else
        {
            result[i][j] = 0;
        }


    return result;
  }
 

 

and

 

    synchronized void rotateClockwise() {
        int x = currentX;
        int y = currentY;
        int [][]s = multiplyMatrix(currentPiece.shape);

        currentPiece = new Piece(s, x, y);

        updateLocation();
    }

 

it doesn't work, because I can't get access to currentPiece or any of its attribute it seems, even though it was made public.

 

Here is the full code:

 


 

import java.awt.*;

public class Board extends Grid {
    public static final int COLUMNS = 16;
    public static final int ROWS = 32;
    public static final Color BLUE = new Color(0,0,128,40);
    
    public Board() {
        super(new int[ROWS][COLUMNS]);
        setSize(COLUMNS*Tetris.SQUARE_SIZE,
                ROWS*Tetris.SQUARE_SIZE);
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(BLUE);
        paintStripes(g);
    }
    
    void paintStripes(Graphics g) {
        for (int i = 0; i < COLUMNS; i += 4) {
            g.fillRect(i*Tetris.SQUARE_SIZE,0,
                Tetris.SQUARE_SIZE*2,Tetris.SQUARE_SIZE*ROWS);
        }
    }
    

}

 

 

   
Code:
 

 

  public class PieceFactory {

    public static final int[][] L1 =
        {{1,1,0,0},
         {0,1,0,0},
         {0,1,0,0},
         {0,0,0,0},
        };

    public static final int[][] L2 =
        {{0,1,0,0},
         {0,1,0,0},
         {1,1,0,0},
         {0,0,0,0},
        };

    public static final int[][] T =
        {{0,1,0,0},
         {1,1,0,0},
         {0,1,0,0},
         {0,0,0,0},
        };

    public static final int[][] BOX =
        {{1,1,0,0},
         {1,1,0,0},
         {0,0,0,0},
         {0,0,0,0},
        };

    public static final int[][] BAR =
        {{1,1,1,1},
         {0,0,0,0},
         {0,0,0,0},
         {0,0,0,0},
        };

    public static final int[][] STEP1 =
        {{1,0,0,0},
         {1,1,0,0},
         {0,1,0,0},
         {0,0,0,0},
        };

    public static final int[][] STEP2 =
        {{0,1,0,0},
         {1,1,0,0},
         {1,0,0,0},
         {0,0,0,0},
        };

    public static final int[][][] SHAPES = {L1,L2,T,BOX,BAR,STEP1,STEP2};

    public static Piece createPiece() {
        int[][] s = SHAPES[(int) (Math.random()*SHAPES.length)];
        switch ((int) (Math.random()*10)) {
            case 0:
            case 1:
            case 2:
            case 3:
            default: return new Piece(s);
        }


    }




}


 

 

    
Code:

 

    import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Tetris extends JFrame implements KeyListener {
    public static final int SQUARE_SIZE = 10; // 10 by 10 pixels

    static Board board;
    static Tetris game;

    JPanel mainPanel;
    public Piece currentPiece;
    int score = 0;
    JButton scoreButton;

    public Tetris() {
        super("Tetris");
        game = this;
        Container pane = getContentPane();
        pane.setLayout(new BorderLayout());

        scoreButton = new JButton("0");
        scoreButton.setEnabled(false);
        pane.add(scoreButton,BorderLayout.NORTH);

        board = new Board();
        mainPanel = new JPanel();
        mainPanel.setLayout(null);
        mainPanel.add(board);
        mainPanel.setPreferredSize
            (new Dimension(Board.COLUMNS*SQUARE_SIZE,
                         Board.ROWS*SQUARE_SIZE));
        pane.add(mainPanel);

        addKeyListener(this);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });
        pack();
        show();
        setResizable(false);
    }


    public void addToScore(int v) {
        score += v;
        scoreButton.setText(""+score);
    }

    public int getScore() {
        return score;
    }

    static Board getBoard() {
        return board;
    }

    static Tetris getGame() {
        return game;
    }

    static void sleep(int milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException ie) {
        }
    }

    public static void main(String[] args) {
        Tetris game = new Tetris();
        while (true) {
            game.dropPiece();
        }
    }

    void dropPiece() {
        currentPiece = PieceFactory.createPiece();
        mainPanel.add(currentPiece);
        currentPiece.repaint();
        currentPiece.fall();
        //mainPanel.remove(currentPiece);
        board.repaint();
        addToScore(1);
    }

    public void keyPressed(KeyEvent event) {
        int key = event.getKeyCode();
        switch (key) {
        case KeyEvent.VK_UP: // up arrow
        case KeyEvent.VK_KP_UP:
            currentPiece.rotateCounterclockwise();
            break;
        case KeyEvent.VK_DOWN: // down arrow
        case KeyEvent.VK_KP_DOWN:
            currentPiece.rotateClockwise();
            break;
        case KeyEvent.VK_LEFT: // left arrow
        case KeyEvent.VK_KP_LEFT:
            currentPiece.moveLeft();
            break;
        case KeyEvent.VK_RIGHT: // right arrow
        case KeyEvent.VK_KP_RIGHT:
            currentPiece.moveRight();
            break;
        case KeyEvent.VK_SPACE: // space bar
            currentPiece.drop();
        }
    }

    public void keyReleased(KeyEvent arg0) {
    }

    public void keyTyped(KeyEvent arg0) {
    }


}


    Code:
    public class Piece extends Grid {
    int currentX; // current X location on the board
    double currentY; // current Y location on the board


    public Piece(int shape[][]) {
        super(shape);
        currentX = 7;
        currentY = 2;
        updateLocation();
    }

    public Piece(int shape[][], currentX, currentY) {
        super(shape);
        this.currentX = currentX;
        this.currentY = currentY;
        updateLocation()
    }



    void updateSize() {
        setSize(Tetris.SQUARE_SIZE*getColumns(),
                Tetris.SQUARE_SIZE*getRows());
    }

    void updateLocation() {
        setLocation(Tetris.SQUARE_SIZE*currentX,
                    (int) (Tetris.SQUARE_SIZE*currentY));
    }

    synchronized void moveDown() {

    }

    synchronized void moveLeft() {
        currentX--;
        updateLocation();
    }

    synchronized void moveRight() {
        currentX++;
        updateLocation();
    }

synchronized void rotateClockwise() {
    int x = currentX;
    int y = currentY;

    currentPiece = new Piece(s, x, y);

    updateLocation();
}




    synchronized void rotateCounterclockwise() {
    }

    void fall() {
        // replace the following by your code
        Tetris.sleep(2000);
    }

    synchronized void drop() {
        currentY++;
        updateLocation();
    }

public static int [][] multiplyMatrix(int [][] m1)
{
        int [][] m2 =
        {{0,0,0,1},
         {0,0,1,0},
         {0,1,0,0},
         {1,0,0,0},
        };


int[][] result = new int[4][4];

// multiply
for (int i=0; i<4; i++)
for (int j=0; j<4; j++)
for (int k=0; k<4; k++)
if (m1[i][k] * m2[k][j] > 0)
{
    result[i][j] = 1;
}
else
{
    result[i][j] = 0;
}


return result;
}

}


 

 

I can post the files if you really insist. Thanks for helping.

Edited by concepts
0

Share this post


Link to post
Share on other sites

I'm not 100% on Java so I may be wrong here, hopefully someone can correct me if I am, but although 'currentPiece' is public it is still inside the 'Tetris' class so the 'Piece' class cannot access it directly as you have, but it can access it through a 'Tetris' object. So it would be something like "Tetris.currentPiece", similar to the 'fall()' method where "Tetris.sleep(2000)" is used.

 

On a side note, there is a way of determining the rotation of Tetris pieces without having to store that location as you have in matrices (some people would argue that using tables is better as there is a limited number of shapes, but I prefer the algorithm personally).

  • You define a block in the shape that will be the centre block that will be used to rotate around.
  • Each other block is then defined in "shape space" relative to the centre, i.e. a block one column to the left will be [-1,0] relative to the centre block.
  • When rotating (CW) the new row is the negative of the current column and the new column is the current row. So from the example above would become [0,1]. (This is still in "shape space", so is an offset from the centre block).
  • For CCW rotation the negative is for the new column instead of the new row.

Below is a posting of my code performing the above (note this is in C++ not java);

Vector2 Shape::BlockLocAfterRotate(UINT inBlockNum)
{
    // Get the current location of the block
    Vector2 outLoc = mBlocks[inBlockNum]->mLoc;

    // Location of the centre block for this shape
    Vector2 centreLoc = mBlocks[mID_CentreBlock]->mLoc;

    // The offset of the current block from the centre of the shape
    int offsetRow = centreLoc.y - outLoc.y;
    int offsetCol = centreLoc.x - outLoc.x;

    // The new location (in shape space)...
    int newOffsetRow = -offsetCol; // New row is the negative of the previous col (still in shape space)
    int newOffsetCol = offsetRow;  // New col is the previous row (still in shape space)

    // Convert back to grid space
    outLoc.x = centreLoc.x + newOffsetCol;
    outLoc.y = centreLoc.y + newOffsetRow;

    return outLoc;
}

Edit: Doing the algorithm way means you can just update the x,y components of your piece instead of having to create a new Piece every time and could very solve your problem too!

0

Share this post


Link to post
Share on other sites

synchronized void rotateClockwise()

{ int x = currentX;

int y = currentY;

int [][]s = multiplyMatrix(currentPiece.shape);

currentPiece = new Piece(s, x, y);

updateLocation(); }

 

currentPiece is the variable name you give the piece in the Tetris class.  However, since this method is a member of the Piece class, just replace "currentPiece" with "this".  That will make the method operate on its own instance, which is what you want it to do (and how you're using the method call in the Tetris class, anyway).

 

Quick edit: been a while since I broke Java, but I'm actually unsure if using "this = new Piece()" will be legit.  You might want to move this functionality into the Tetris class instead, or rethink your method of rotation.  Or I could be fretting over nothing and Java will handle this just fine.  I'm rusty there.

 

Either way, you can definitely use the "this" keyword in the multiplyMatrix call.

Edited by BCullis
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0