import java.util.*;
import java.lang.*;
public class TestIt
{
public static void main(String[] args)
{
// Create an array of random Game objects
Random r = new Random();
GameObject[] A = new GameObject[10];
for(int i = 0; i < 10; ++i)
A[i] = new GameObject(r.nextInt(5),
r.nextInt(5),
r.nextInt(3),
(char)('a' + i));
// Print out array
for(int i = 0; i < 10; ++i)
System.out.println(A[i]);
System.out.println();
Arrays.sort(A);
// Print out array
for(int i = 0; i < 10; ++i)
System.out.println(A[i]);
System.out.println();
}
}
|
import java.util.*;
public class GameObject extends Pos implements Comparable
{
private char sym;
public GameObject(int row, int col, int dir, char s)
{
super(row,col,dir);
sym = s;
}
public char getSym() { return sym; }
public void write(char[][] board)
{
board[getRow()][getCol()] = sym;
}
public String toString() {
return "(" + getRow() + "," + getCol() + "," +
getDir() + "," + getSym() + ")";
}
public int compareTo(Object o)
{
GameObject a = (GameObject)o;
if (getRow() < a.getRow()) return -1;
if (getRow() > a.getRow()) return 1;
if (getCol() < a.getCol()) return -1;
if (getCol() > a.getCol()) return 1;
if (getDir() < a.getDir()) return -1;
if (getDir() > a.getDir()) return 1;
if (getSym() < a.getSym()) return -1;
if (getSym() > a.getSym()) return 1;
else return 0;
}
}
|
/**
This class represents a row-col position with
a N/E/S/W direction. N=0,E=1,S=2,E=3.
@author Dr. Brown
*/
public class Pos {
private int r, c, d;
public Pos(int row, int col, int dir) {
r = row;
c = col;
d = dir;
}
public void moveForward() {
int[] dr = {-1, 0, 1, 0};
int[] dc = {0, 1, 0, -1};
r += dr[d];
c += dc[d];
}
public void turnRight() {
d = (d + 1) % 4;
}
public void turnLeft() {
d = (d + 3) % 4;
}
public int getRow() {
return r;
}
public int getCol() {
return c;
}
public int getDir() {
return d;
}
@Override
public String toString() {
return "(" + r + "," + c + "," + d + ")";
}
public static void main(String[] args) {
Pos p = new Pos(4, 7, 1);
System.out.println(p);
p.moveForward();
System.out.println(p);
}
}
|