What is wrong with this simple circle/rectangle collision detection? - java

I have an issue with simple 2d collision detection with a circle and a rectangle. All the checker does is see if the center of the circle overlaps with any point on the rectangle.
Heres the checker:
boolean overlaps(Circle circle) {
for (double i = topLeft.x; i < (topLeft.x + width); i++)
{
for (double j = topLeft.y; j < (topLeft.y + height); j++)
{
if (circle.center.x == i && circle.center.y == j)
{
return true;
}
}
}
return false;
}`
Very simple, and to the point. The error comes into play at the if statement, with my circle.center.x, and/or circle.center.y.
Here is the code for my Circle class:
public class Circle {
Point center;
double radius;
/**
* Constructor.
*
* #param center the center Point of the circle
* #param radius the radius of the circle
*/
public Circle(Point center, double radius) {
center = this.center;
radius = this.radius;
}
/**
* Get the current center point of the circle.
*
* #return the center point of the circle
*/
public Point getCenter() {
return center;
}
/**
* Set the center point of the circle.
*
* #param center the (new) center point of the circle
*/
public void setCenter(Point center) {
this.center = center;
}
/**
* Get the current radius.
*
* #return the current radius
*/
public double getRadius() {
return radius;
}
/**
* Set the radius.
*
* #param radius the (new) radius of the circle
*/
public void setRadius(double radius) {
this.radius = radius;
}
}`
Where am i going wrong? It certainly cannot be an issue with my Point class, as that would mean plenty of other things would've gone wrong by now. Thanks in advance.

Your method should just be:
boolean overlaps( Circle circle )
{
return topLeft.x <= circle.center.x && circle.center.x <= topLeft.x + width &&
topLeft.y <= circle.center.y && circle.center.y <= topLeft.y + height;
}

Related

Did I do this UML Diagram Properly?

Problem: Did I properly make this UML Diagram?
UML Diagram:
Circle
-radius : double
+PI : double
+setRadius(rad: double) : void
+getRadius(rad: double) : void
+getArea() : double
+getDiameter() : double
+getCircumference() : double
Code:
public class Circle
{
//Declaration
private double radius;
public static final double PI = 3.14159;
public Circle()
{
radius = 0.0;
}
public Circle(double rad)
{
radius = rad;
}
/**
The setRadius method stores a value in the
radius field.
#param rad The value to store in radius.
*/
public void setRadius(double rad)
{
radius = rad;
}
/**
The getRadius method returns a Radius
for the Circle.
#return The entered radius in the radius field.
*/
public double getRadius(double rad)
{
return radius;
}
/**
The getArea method returns an Area
for the Circle.
#return The Area for the Circle.
*/
public double getArea()
{
return PI * (radius * radius);
}
/**
The getDiameter method returns a diameter
for the Circle.
#return The diameter for the Circle.
*/

Calculating perimeter of a polygon in Java

I have a method called perimeter that is supposed to take in some points and return the perimeter of the polygon based upon the points provided. I keep getting the wrong answer for perimeter when I use a tester to run the program.
import java.util.ArrayList;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;
/**A class that represents a geometric polygon. Methods are provided for adding
* a point to the polygon and for calculating the perimeter and area of the
* polygon.
*/
class MyPolygon {
//list of the points of the polygon
private ArrayList<Point2D.Double> points;
/**Constructs a polygon with no points in it.
*/
public MyPolygon() {
points = new ArrayList<Point2D.Double>();
}
/**Adds a point to the end of the list of points in the polygon.
* #param x The x coordinate of the point.
* #param y The y coordinate of the point.
*/
public void add(double x, double y) {
points.add(new Point2D.Double(x,y));
}
/**Calculates and returns the perimeter of the polygon.
* #return 0.0 if < 2 points in polygon, otherwise returns the
* sum of the lengths of the line segments.
*/
public double perimeter() {
if (points.size() < 2){
return 0.0;
}
int i = 0;
double d = 0;
double total = 0;
while (i < points.size() - 1 )
{
Point2D.Double point1 = points.get(i);
double x = point1.x;
double y = point1.y;
Point2D.Double point2 = points.get(i+1);
double x1 = point2.x;
double y1 = point2.y;
d = point1.distance(point2);
System.out.println(d);
//d = Math.sqrt(Math.pow(x1 - x,2) + Math.pow(y1 - y, 2));
total = total + d;
i++;
}
return total;
}
/**Calculates and returns the area of the polygon.
* #return 0.0 if < 3 points in the polygon, otherwise returns
* the area of the polygon.
*/
public double area() {
return 0;
}
}
The Tester class:
class PolygonTester {
public static void main(String args[]) {
MyPolygon poly = new MyPolygon();
poly.add(1.0,1.0);
poly.add(3.0,1.0);
poly.add(1.0,3.0);
System.out.println(poly.perimeter());
System.out.println(poly.area());
}
}
you should initialize total variable with lenght of last edge:
double total = points.get(0).distance(poinsts.get(points.size() - 1));

part of code not executing properly

I'm learning about queues in school and an having an issue with one of our labs i believe the issue is here the problem is that it will not erase the circles after reaching 50
public void paint(Graphics g)
{
int incX = 5; // initial x increment for circle locations
int incY = 5; // initial y increment for circle locations
Coord temp = new Coord(0,0);
Queue<Coord> q = new LinkedList<Coord>();
Circle c = new Circle(g,circleSize,incX,incY,TIME_DELAY);
try
{
for(int i = 1; i <= TOTAL_NUM_CIRCLES; i++)
{
if(q.size() >= 50)
{
temp = q.remove();
c.eraseCircle(g,temp.getX(),temp.getY());
}
temp = new Coord(getX(),getY());
q.add(temp);
c.drawCircle(g);
c.hitEdge();
}
}
catch(InterruptedException e){}
}
if you need the whole thing to run or test here is all of it with comments saying what everything is and what I'm trying to do
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/**
* Creates an instance of the GfxApp class, which uses the Circle class, Coord class, and
* a queue to create a screen saver.
* #param args not used
*/
public class ScreenSaver
{
public static void main(String args[])
{
GfxApp gfx = new GfxApp();
}
}
/**
* Creates a Screen Saver by placing Circle coordinates in a queue
*/
class GfxApp extends JFrame
{
private int circleCount, circleSize;
public static final int TIME_DELAY = 10; // controls the speed
public static final int TOTAL_NUM_CIRCLES = 1000; // controls how long it goes
/**
* Creates a GfxApp with 50 circles with diameter 30
*/
public GfxApp()
{
circleCount = 50;
circleSize = 30;
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* Draws a stream of circleCount circles of size circleSize. Uses a queue to erase circles
* at the end of the stream. The total number of circles that will be drawn is 2000.
* #param g the Graphics object
*/
public void paint(Graphics g)
{
int incX = 5; // initial x increment for circle locations
int incY = 5; // initial y increment for circle locations
Coord temp = new Coord(0,0);
Queue<Coord> q = new LinkedList<Coord>();
Circle c = new Circle(g,circleSize,incX,incY,TIME_DELAY);
try
{
for(int i = 1; i <= TOTAL_NUM_CIRCLES; i++)
{
if(q.size() >= 50)
{
temp = q.remove();
c.eraseCircle(g,temp.getY(),temp.getX());
}
temp = new Coord(getX(),getY());
q.add(temp);
c.drawCircle(g);
c.hitEdge();
}
}
catch(InterruptedException e){}
}
}
/**
* A class to represent Circle objects. Circles can be drawn and erased.
*/
class Circle
{
private int tlX; // top-left X coordinate
private int tlY; // top-left Y coordinate
private int incX; // increment movement of X coordinate
private int incY; // increment movement of Y coordinate
private boolean addX; // flag to determine add/subtract of increment for X
private boolean addY; // flag to determine add/subtract of increment for Y
private int size; // diameter of the circle
private int timeDelay; // time delay until next circle is drawn
/**
* Creates a Circle with a specified Graphics, size, x increment, y increment and time delay
*/
public Circle(Graphics g, int s, int x, int y, int td)
{
incX = x;
incY = y;
size = s;
addX = true;
addY = false;
tlX = 400;
tlY = 300;
timeDelay = td;
}
/**
* returns the top left X of this circle
* #return tlX
*/
public int getTLX() { return tlX;}
/**
* returns the top left Y of this circle
* #return tlY
*/
public int getTLY() { return tlY;}
/**
* delays the program for a specified number of miliseconds
* #param n number of miliseconds
*/
public void delay(int n) throws InterruptedException
{
Thread.sleep(n);
}
/**
* draws a blue circle and sets the tlX and tlY for the next drawing
* #param g Graphics object
*/
public void drawCircle(Graphics g) throws InterruptedException
{
g.setColor(Color.blue);
g.drawOval(tlX,tlY,size,size);
delay(timeDelay);
if (addX)
tlX+=incX;
else
tlX-=incX;
if (addY)
tlY+=incY;
else
tlY-=incY;
}
/**
* Randomly sets a new direction for the circle by randomly setting
* the x increment and y increment
*/
public void newData()
{
incX = (int) Math.round(Math.random() * 7 + 5);
incY = (int) Math.round(Math.random() * 7 + 5);
}
/**
* Determines if any of the four edges have been hit, and if so, reverses the
* appropriate flags (addX and addY) and calls newData
*/
public void hitEdge()
{
boolean a = false;
if (tlX < incX)
{
addX = true;
a = true;
}
if (tlX > 800 - (30 + incX))
{
addX = false;
a = true;
}
if (tlY < incY + 30)
{
addY = true;
a = true;
}
if (tlY > 600 - (30 + incY))
{
addY = false;
a = true;
}
if (a)
newData();
}
// add an eraseCircle method
public void eraseCircle(Graphics g, int x, int y)
{
g.setColor(Color.black);
g.drawOval(x,y,size,size);
}
}
// Create a Coord class, so that coordinates of drawn circles can be placed in the queue.
// As coordinates are removed from the queue, circles are erased with eraseCircle.
class Coord
{
private int x;
private int y;
public Coord(int a, int b)
{
x=a;
y=b;
}
public int getX(){return x;}
public int getY(){return y;}
public int setX(int a){x=a; return x;}
public int setY(int b){y=b; return y;}
}
your coordinates are backwards:
-public void eraseCircle(Graphics g, int x, int y)
-c.eraseCircle(g,temp.getY(),temp.getX());
switch around x and y and it should work.
Edit:
Ok so the problem is the x and y in your coords are always 0 so I modified your drawCircle method to return the proper coordinates, and your paint method to store them, so this is what you get:
Paint:
public void paint(Graphics g)
{
int incX = 5; // initial x increment for circle locations
int incY = 5; // initial y increment for circle locations
Coord temp = new Coord(0,0);
Queue<Coord> q = new LinkedList<Coord>();
Circle c = new Circle(g,circleSize,incX,incY,TIME_DELAY);
try
{
for(int i = 1; i <= TOTAL_NUM_CIRCLES; i++)
{
if(q.size() >= 50)
{
temp = q.remove();
c.eraseCircle(g,temp.getX(),temp.getY());
}
temp = new Coord(getX(),getY());
//q.add(temp);
q.add(c.drawCircle(g));
c.hitEdge();
}
}
catch(InterruptedException e){}
}
drawCircle:
/**
* draws a blue circle and sets the tlX and tlY for the next drawing
* #param g Graphics object
* #return
*/
public Coord drawCircle(Graphics g) throws InterruptedException
{
g.setColor(Color.blue);
g.drawOval(tlX,tlY,size,size);
delay(timeDelay);
if (addX)
tlX+=incX;
else
tlX-=incX;
if (addY)
tlY+=incY;
else
tlY-=incY;
return new Coord(tlX, tlY);
}
To determine this I set a breakpoint in the paint method and viewed what temp's values were through eclipses debugger.

How to use camera look direction as z- direction with lwjgl

I wrote this camera last week everything works fine, accept for the fact that I don't how to use the look position as Z-position.
If you try it you'll see for youself.
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.toRadians;
import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.util.vector.Vector3f;
public class Camera{
private Vector3f position = null; //X, Y, Z position of the PandaCam
private float yaw = 0.0f; //Yaw of the PandaCam
private float pitch = 0.0f; //Pitch of the PandaCam
private float dx = 0.0f, dy = 0.0f;
private float multi = 0.005f;
private float moveSpeed = 0.25f;
private float mouseSensitivity = 0.02f;
private float tDelta = getDelta();
private long lastFrame, time;
/**
* Create a new PandaCam
* default:
* x = 0
* y = 0
* z = 0
*/
public Camera(){
position = new Vector3f(0, 0, 0);
}
/**
* Create a new PandaCam
* default:
* z = 0
*
* #param x Set the Starting X position of the camera
* #param y Set the Starting Y position of the camera
*/
public Camera(float x, float y){
position = new Vector3f(x, y, 0);
}
/**
* Create a new PandaCam
*
* #param x Set the Starting X position of the camera
* #param y Set the Starting Y position of the camera
* #param z Set the Starting Z position of the camera
*/
public Camera(float x, float y, float z){
position = new Vector3f(x, y, z);
}
/**
* Call this function every frame to update the PandaCam
*/
public void update(){
glLoadIdentity();
mouseInput();
keyboardInput();
setPosition();
}
/**
* #return Returns the delta time.
*/
public int getDelta(){
time = (Sys.getTime() * 1000) / Sys.getTimerResolution();
int delta = (int) (time - lastFrame);
lastFrame = time;
return delta;
}
/**
* Updates the PandaCam yaw
* #param amount The amount the yaw moves. takes numbers below and above zero
*/
public void yaw(float amount){
yaw -= amount;
}
/**
* Updates the PandaCam pitch
* #param amount The amount the pitch moves. takes numbers below and above zero
*/
public void pitch(float amount){
pitch += amount;
}
/**
* Moves the PandaCam forward.
* #param distance The distance the camera move's forward
*/
public void walkForward(float distance){
calculatePosition(0, 0, multi * distance * 0.003f);
}
/**
* Moves the PandaCam backward.
* #param distance The distance the camera move's backward
*/
public void walkBackwards(float distance){
calculatePosition(0, 0, -multi * distance * 0.003f);
}
/**
* Moves the PandaCam left.
* #param distance The distance the camera move's left
*/
public void strafeLeft(float distance){
calculatePosition(multi * distance * 0.003f, 0, 0);
}
/**
* Moves the PandaCam right.
* #param distance The distance the camera move's right
*/
public void strafeRight(float distance){
calculatePosition(-multi * distance * 0.003f, 0, 0);
}
/**
* Sets the PandaCam position
* #param dx Is an amount that the PandaCam add's or subtracts from the current X
* #param dy Is an amount that the PandaCam add's or subtracts from the current Y
* #param dz Is an amount that the PandaCam add's or subtracts from the current Z
*/
private void calculatePosition(float dx, float dy, float dz){
position.x -= dx * (float) sin(toRadians(yaw - 90)) + dz * sin(toRadians(yaw));
position.y += dy * (float) sin(toRadians(pitch - 90)) + dz * sin(toRadians(pitch));
position.z += dx * (float) cos(toRadians(yaw - 90)) + dz * cos(toRadians(yaw));
}
/**
* Handles the keyboard input
*/
public void keyboardInput(){
//Move forward
if (Keyboard.isKeyDown(Keyboard.KEY_W) || Keyboard.isKeyDown(Keyboard.KEY_UP)){
walkForward(moveSpeed * (tDelta/10));
}
//Move backwards
if (Keyboard.isKeyDown(Keyboard.KEY_S) || Keyboard.isKeyDown(Keyboard.KEY_DOWN)){
walkBackwards(moveSpeed * (tDelta/10));
}
//Strafe left
if (Keyboard.isKeyDown(Keyboard.KEY_A) || Keyboard.isKeyDown(Keyboard.KEY_LEFT)){
strafeLeft(moveSpeed * (tDelta/10));
}
//Strafe right
if (Keyboard.isKeyDown(Keyboard.KEY_D) || Keyboard.isKeyDown(Keyboard.KEY_RIGHT)){
strafeRight(moveSpeed * (tDelta/10));
}
}
/**
* Handles mouse Input
*/
public void mouseInput(){
dx = Mouse.getDX();
dy = Mouse.getDY();
yaw(dx * mouseSensitivity);
pitch(dy * mouseSensitivity);
}
/**
* Sets the position of the PandaCam
*/
public void setPosition(){
//Rotate the pitch around the X axis
glRotatef(-pitch, 1.0f, 0.0f, 0.0f);
//Rotate the yaw around the Y axis
glRotatef(-yaw, 0.0f, 1.0f, 0.0f);
//translate to the position vector's location
glTranslatef(position.x, position.y, position.z);
}
public float getMX(){
return Mouse.getX();
}
public float getMY(){
return Mouse.getY();
}
/**
* #return The Pitch position of the PandaCam
*/
public float getPitch(){
return -pitch;
}
/**
* #return The Yaw position of the PandaCam
*/
public float getYaw(){
return -yaw;
}
/**
* #return The X position of the PandaCam
*/
public float getX(){
return position.x;
}
/**
* #return The Y position of the PandaCam
*/
public float getY(){
return position.y;
}
/**
* #return The Z position of the PandaCam
*/
public float getZ(){
return position.z;
}
}
In OpenGL Camera (view) matrix is usually built using lookAt method which defines the view direction of camera.Here is a source where you can find lookAt method implementation.
Or here is my answer to someone with camera problem ,with LWJGL lookat example code included :)
Btw , if you are using fixed pipeline (which seems to be the case ) ,take a look at :
gluLookAt ()

Tetris midlet attributes

public static final int SQUARE = 0,
LINE = 1,
S_FIGURE = 2,
Z_FIGURE = 3,
RIGHT_ANGLE_FIGURE = 4,
LEFT_ANGLE_FIGURE = 5,
TRIANGLE = 6;
Here above is my Tetris midlet/J2ME code for the block. But i don't know how to explain these parameters. can anyone give me advice? Let me know if you need the full code to work.
this is my full code:
public class Block {
public static final int SQUARE = 0,
LINE = 1,
S_FIGURE = 2,
Z_FIGURE = 3,
RIGHT_ANGLE_FIGURE = 4,
LEFT_ANGLE_FIGURE = 5,
TRIANGLE = 6;
public int kind;
public int color;
/**
* The horizontal figure position on the board. This value has no
* meaning when the figure is not attached to a square board.
*/
public int xPos = 0;
/**
* The vertical figure position on the board. This value has no
* meaning when the figure is not attached to a square board.
*/
public int yPos = 0;
/**
* The figure orientation (or rotation). This value is normally
* between 0 and 3, but must also be less than the maxOrientation
* value.
*
* #see #maxOrientation
*/
private int orientation = 0;
public int maxOrientation;
public int[] shapeX, shapeY;
private GameCanvas board = null;
public Block(int k) {
shapeX = new int[4];
shapeY = new int[4];
initialize(k);
this.kind = k;
}
private void initialize(int kind) {
switch (kind) {
case SQUARE :
maxOrientation = 1;
color = 0x0000ff; // blau
shapeX[0] = -1;
shapeY[0] = 0;
shapeX[1] = 0;
shapeY[1] = 0;
shapeX[2] = -1;
shapeY[2] = 1;
shapeX[3] = 0;
shapeY[3] = 1;
break;
case LINE :
maxOrientation = 2;
color = 0xff0000; // rot
shapeX[0] = -2;
shapeY[0] = 0;
shapeX[1] = -1;
shapeY[1] = 0;
shapeX[2] = 0;
shapeY[2] = 0;
shapeX[3] = 1;
shapeY[3] = 0;
break;
case S_FIGURE :
maxOrientation = 2;
color = 0xff00ff; // lila
shapeX[0] = 0;
shapeY[0] = 0;
shapeX[1] = 1;
shapeY[1] = 0;
shapeX[2] = -1;
shapeY[2] = 1;
shapeX[3] = 0;
shapeY[3] = 1;
break;
case Z_FIGURE :
maxOrientation = 2;
color = 0x008000; // grĂ¼n
shapeX[0] = -1;
shapeY[0] = 0;
shapeX[1] = 0;
shapeY[1] = 0;
shapeX[2] = 0;
shapeY[2] = 1;
shapeX[3] = 1;
shapeY[3] = 1;
break;
case RIGHT_ANGLE_FIGURE :
maxOrientation = 4;
color = 0x800080; // violett
shapeX[0] = -1;
shapeY[0] = 0;
shapeX[1] = 0;
shapeY[1] = 0;
shapeX[2] = 1;
shapeY[2] = 0;
shapeX[3] = 1;
shapeY[3] = 1;
break;
case LEFT_ANGLE_FIGURE :
maxOrientation = 4;
color = 0x000000; // schwarz
shapeX[0] = -1;
shapeY[0] = 0;
shapeX[1] = 0;
shapeY[1] = 0;
shapeX[2] = 1;
shapeY[2] = 0;
shapeX[3] = -1;
shapeY[3] = 1;
break;
case TRIANGLE :
maxOrientation = 4; // gelb
color = 0xCECE00;
shapeX[0] = -1;
shapeY[0] = 0;
shapeX[1] = 0;
shapeY[1] = 0;
shapeX[2] = 1;
shapeY[2] = 0;
shapeX[3] = 0;
shapeY[3] = 1;
break;
}
}
/**
* Checks if this figure is attached to a square board.
*
* #return true if the figure is already attached, or
* false otherwise
*/
public boolean isAttached() {
return board != null;
}
public boolean attach(GameCanvas board, boolean center) {
int newX;
int newY;
int i;
// Check for previous attachment
if (isAttached()) {
detach();
}
// Reset position (for correct controls)
xPos = 0;
yPos = 0;
// Calculate position
newX = board.getBoardWidth() / 2;
if (center) {
newY = board.getBoardHeight() / 2;
} else {
newY = 0;
for (i = 0; i < shapeX.length; i++) {
if (getRelativeY(i, orientation) < 0 && getRelativeY(i, orientation)<newY) {
newY = Math.abs(getRelativeY(i, orientation))+1;
}
}
}
// Check position
this.board = board;
if (!canMoveTo(newX, newY, orientation)) {
this.board = null;
return false;
}
// Draw figure
xPos = newX;
yPos = newY;
paint(color);
board.repaint();
return true;
}
/**
* Checks if the figure is fully visible on the square board. If
* the figure isn't attached to a board, false will be returned.
*
* #return true if the figure is fully visible, or
* false otherwise
*/
public boolean isAllVisible() {
if (!isAttached()) {
return false;
}
for (int i = 0; i < shapeX.length; i++) {
if (yPos + getRelativeY(i, orientation) < 0) {
return false;
}
}
return true;
}
/**
* Detaches this figure from its square board. The figure will not
* be removed from the board by this operation, resulting in the
* figure being left intact.
*/
public void detach() {
board = null;
}
/**
* Checks if the figure has landed. If this method returns true,
* the moveDown() or the moveAllWayDown() methods should have no
* effect. If no square board is attached, this method will return
* true.
*
* #return true if the figure has landed, or false otherwise
*/
public boolean hasLanded() {
return !isAttached() || !canMoveTo(xPos, yPos + 1, orientation);
}
/**
* Moves the figure one step to the left. If such a move is not
* possible with respect to the square board, nothing is done. The
* square board will be changed as the figure moves, clearing the
* previous cells. If no square board is attached, nothing is
* done.
*/
public void moveLeft() {
if (isAttached() && canMoveTo(xPos - 1, yPos, orientation)) {
paint(-1);
xPos--;
paint(color);
board.repaint();
}
}
/**
* Moves the figure one step to the right. If such a move is not
* possible with respect to the square board, nothing is done. The
* square board will be changed as the figure moves, clearing the
* previous cells. If no square board is attached, nothing is
* done.
*/
public void moveRight() {
if (isAttached() && canMoveTo(xPos + 1, yPos, orientation)) {
paint(-1);
xPos++;
paint(color);
board.repaint();
}
}
/**
* Moves the figure one step down. If such a move is not possible
* with respect to the square board, nothing is done. The square
* board will be changed as the figure moves, clearing the
* previous cells. If no square board is attached, nothing is
* done.
*/
public void moveDown() {
if (isAttached() && canMoveTo(xPos, yPos + 1, orientation)) {
paint(-1);
yPos++;
paint(color);
board.repaint();
}
}
/**
* Moves the figure all the way down. The limits of the move are
* either the square board bottom, or squares not being empty. If
* no move is possible with respect to the square board, nothing
* is done. The square board will be changed as the figure moves,
* clearing the previous cells. If no square board is attached,
* nothing is done.
*/
public void moveAllWayDown() {
int y = yPos;
// Check for board
if (!isAttached()) {
return;
}
// Find lowest position
while (canMoveTo(xPos, y + 1, orientation)) {
y++;
}
// Update
if (y != yPos) {
paint(-1);
yPos = y;
paint(color);
board.repaint();
}
}
/**
* Returns the current figure rotation (orientation).
*
* #return the current figure rotation
*/
public int getRotation() {
return orientation;
}
/**
* Sets the figure rotation (orientation). If the desired rotation
* is not possible with respect to the square board, nothing is
* done. The square board will be changed as the figure moves,
* clearing the previous cells. If no square board is attached,
* the rotation is performed directly.
*
* #param rotation the new figure orientation
*/
public void setRotation(int rotation) {
int newOrientation;
// Set new orientation
newOrientation = rotation % maxOrientation;
// Check new position
if (!isAttached()) {
orientation = newOrientation;
} else if (canMoveTo(xPos, yPos, newOrientation)) {
paint(-1);
orientation = newOrientation;
paint(color);
board.repaint();
}
}
/**
* Rotates the figure clockwise. If such a rotation is not
* possible with respect to the square board, nothing is done.
* The square board will be changed as the figure moves,
* clearing the previous cells. If no square board is attached,
* the rotation is performed directly.
*/
public void rotateClockwise() {
if (maxOrientation == 1) {
return;
} else {
setRotation((orientation + 1) % maxOrientation);
}
}
/**
* Rotates the figure counter-clockwise. If such a rotation
* is not possible with respect to the square board, nothing
* is done. The square board will be changed as the figure
* moves, clearing the previous cells. If no square board is
* attached, the rotation is performed directly.
*/
public void rotateCounterClockwise() {
if (maxOrientation == 1) {
return;
} else {
setRotation((orientation + 3) % 4);
}
}
/**
* Checks if a specified pair of (square) coordinates are inside
* the figure, or not.
*
* #param x the horizontal position
* #param y the vertical position
*
* #return true if the coordinates are inside the figure, or
* false otherwise
*/
private boolean isInside(int x, int y) {
for (int i = 0; i < shapeX.length; i++) {
if (x == xPos + getRelativeX(i, orientation)
&& y == yPos + getRelativeY(i, orientation)) {
return true;
}
}
return false;
}
/**
* Checks if the figure can move to a new position. The current
* figure position is taken into account when checking for
* collisions. If a collision is detected, this method will return
* false.
*
* #param newX the new horizontal position
* #param newY the new vertical position
* #param newOrientation the new orientation (rotation)
*
* #return true if the figure can be moved, or
* false otherwise
*/
private boolean canMoveTo(int newX, int newY, int newOrientation) {
int x;
int y;
for (int i = 0; i < 4; i++) {
x = newX + getRelativeX(i, newOrientation);
y = newY + getRelativeY(i, newOrientation);
if (!isInside(x, y) && !board.isSquareEmpty(x, y)) {
return false;
}
}
return true;
}
/**
* Returns the relative horizontal position of a specified square.
* The square will be rotated according to the specified
* orientation.
*
* #param square the square to rotate (0-3)
* #param orientation the orientation to use (0-3)
*
* #return the rotated relative horizontal position
*/
public int getRelativeX(int square, int orientation) {
switch (orientation % 4) {
case 0 :
return shapeX[square];
case 1 :
return -shapeY[square];
case 2 :
return -shapeX[square];
case 3 :
return shapeY[square];
default:
return 0; // Should never occur
}
}
/**
* Rotates the relative vertical position of a specified square.
* The square will be rotated according to the specified
* orientation.
*
* #param square the square to rotate (0-3)
* #param orientation the orientation to use (0-3)
*
* #return the rotated relative vertical position
*/
public int getRelativeY(int square, int orientation) {
switch (orientation % 4) {
case 0 :
return shapeY[square];
case 1 :
return shapeX[square];
case 2 :
return -shapeY[square];
case 3 :
return -shapeX[square];
default:
return 0; // Should never occur
}
}
/**
* Paints the figure on the board with the specified color.
*
* #param color the color to paint with, or -1 for clearing
*/
private void paint(int color) {
int x, y;
for (int i = 0; i < shapeX.length; i++) {
x = xPos + getRelativeX(i, orientation);
y = yPos + getRelativeY(i, orientation);
board.setSquareColor(x, y, color);
}
}
}
First of all, I think what you're looking for is an enum:
public enum Tetrimonos{
SQUARE , LINE, S_FIGURE, Z_FIGURE ,
RIGHT_ANGLE_FIGURE, LEFT_ANGLE_FIGURE , TRIANGLE
}
Using constants is a bad idea, relic from old languages.
Secondly, what do you mean 'explain these parameters'? Explain the tetris structure of each thing you named? In this case you should go to the relevant literature: a tetris piece is called tetrimono, and each one is called by a letter. Take a look here:
http://en.wikipedia.org/wiki/Tetris#Gameplay
You might like to link to this in your documentation as well.

Categories

Resources