Passing an array as a parameter- chess board - java

I can't see what is wrong, I am trying to pass the gameBoard array (is this not an array?- see constructor) into the findPiece method, but it says it
isn't an array, what should I be passing here to get un updated board? Sorry, I am new to programming but I really appreciate any hints!
public class Game {
private Board gameBoard;
public Game() {
gameBoard = new Board();
}
public void play(Board board) {
EasyIn2 reader = new EasyIn2();
gameBoard = new Board(); //initializes the board so dont need to do so in main
boolean done = false;
while(!done) { //keeps looping when no one has won yet
gameBoard.printBoard();
System.out.println(WHITEPLAYS_MSG);
String pos1 = reader.getString(); //gets user input ... move from... to.... temporary variables
int xFrom=pos1.charAt(0) - 'a'; //to transform the letter
int yFrom=pos1.charAt(1) - '1'; // to transform the number
String pos2 = reader.getString();
int xTo=pos2.charAt(0) - 'a'; //to transform the letter
int yTo=pos2.charAt(1) - '1'; // to transform the number
gameBoard.findPiece(gameBoard,xFrom,yFrom);
}
}
}
public class Board {
private static final int DEFAULT_SIZE = 8; //images for pieces to be displayed on board
private static final char FREE = '.';
private static final char WHITEROOK = '♖';
private static final char BLACKROOK = '♜';
private static final char WHITEBISHOP = '♗';
private static final char BLACKBISHOP = '♝';
private static final char WHITEKING = '♔';
private static final char BLACKKING = '♚';
private static final char WHITEQUEEN = '♕';
private static final char BLACKQUEEN = '♛';
private static final char WHITEKNIGHT = '♘';
private static final char BLACKKNIGHT = '♞';
private static final char WHITEPAWN = '♙';
private static final char BLACKPAWN = '♟';
private int boardsize;
public char[][] board;
public Board() {
this.boardsize = DEFAULT_SIZE;
board = new char[boardsize][boardsize];
// Clear all playable fields
for (int x = 0; x < boardsize; x++)
for (int y = 0; y < boardsize; y++)
board[x][y] = FREE;
board[0][7] = BLACKROOK;
board[2][7] = BLACKBISHOP;
board[5][7] = BLACKBISHOP;
board[7][7] = BLACKROOK;
board[0][0] = WHITEROOK;
board[2][0] = WHITEBISHOP;
board[5][0] = WHITEBISHOP;
board[7][0] = WHITEROOK;
}
public boolean findPiece(char[][] boardIn, int xFrom, int yFrom) { //checks that the player has selected a piece
for (int i = 0; i < boardIn.length; i++) {
for (int j = 0; j < boardIn.length; j++) {
if (boardIn[i][j] == boardIn[xFrom][yFrom]) { //checks the user input co-ordinate is on the board
break;
if (boardIn[xFrom][yFrom] != FREE) {
Piece piece=new Piece(); //checks the piece is real, ie not a free space
piece.getPieceType(xFrom, yFrom);
return true;
} else {
return false;
}
}
}

You should pass gameBoard.board: actually, you are passing the entire instance of that class (gameBoard), not just the array component of it. So, it's right: the error you got said that you are not passing an array.

The findPiece expects a char[][] as the first parameter and not the entire class Board.
You need to call findPiece method with the first parameter as gameBoard.board;

Related

How to initialize an array to avoid a Null Pointer Exception?

I get a nullPointerException in my program when I try to call a boolean array in a method parameter. The boolean array is created as a constant, and then initialized in a separate void method. Can someone explain to me why it can't find the boolean array (or can't find the array values)?
public static void moveTarget(Graphics g) {
if (!targetMovement)
return;
drawTarget(g, BACKGROUND_COLOR);
drawShield(g, BACKGROUND_COLOR);
This line right here is the specific part where the program fails. (nullPointerException)
int f = findTargetMissilePosition(targetMissileActive);
I specify the constants here, but do not initialize.
// Target Missile values
public static Color TARGET_MISSILE_COLOR = TARGET_COLOR;
public static int MAX_MISSILES = 10;
public static double TARGET_MISSILE_SPEED = MISSILE_SPEED;
public static double TARGET_SHOOT_PROBABILITY = .1;
public static double[] targetMissilePositionX;
public static double[] targetMissilePositionY;
public static double[] targetMissileDeltaX;
public static double[] targetMissileDeltaY;
public static boolean[] targetMissileActive;
// main method does initialization and calls startGrame
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(PANEL_WIDTH, PANEL_HEIGHT);
Graphics g = panel.getGraphics( );
initialize();
startGame(panel, g);
}
//initialize() is called above which is where the arrays are intialized
// start the main game loop which runs forever
public static void startGame(DrawingPanel panel, Graphics g) {
while(true) {
panel.sleep(SLEEP_TIME);
handleKeys(panel,g);
moveTarget(g);
drawAll(g);
moveMissile(g);
shootTargetMissile(g);
for (int i=0;i<10;i++) {
int f = findTargetMissilePosition(targetMissileActive);
moveTargetMissile(g, f);
}
shieldHitTimer--;
targetHitTimer--;
shooterHitTimer--;
}
}
// above is the first time that line of code appears and does not appear to have an issue.
// reset all parameters to start over
public static void reset(Graphics g) {
g.setColor(BACKGROUND_COLOR);
g.fillRect(0,0,PANEL_WIDTH,PANEL_HEIGHT);
initialize();
}
//Here the arrays are initialized
// initialize parameters for the start of the program
public static void initialize() {
shooterPositionX = SHOOTER_INITIAL_POSITION_X;
gunAngle = 0;
targetPositionX = PANEL_WIDTH/2;
missileActive = false;
hitCount = 0;
shooterHitCount = 0;
hitDisplayString = "Hits: ";
targetDeltaX = 0;
targetHitTimer = 0;
shieldHitTimer = 0;
shooterHitTimer = 0;
boolean [] targetMissileActive = new boolean [9]; // might change??
int [] targetMissilePositionX = new int [9];
int [] targetMissilePositionY = new int [9];
int [] targetMissileDeltaX = new int [9];
int [] targetMissileDeltaY = new int [9];
for (int i=0; i<9; i++) {
targetMissilePositionX[i] = 0;
targetMissilePositionY[i] = 0;
targetMissileDeltaX[i] = 0;
targetMissileDeltaY[i] = 0;
targetMissileActive[i] = false;
}
}
// draw everything in its current position
public static void drawAll(Graphics g) {
g.setColor(Color.BLACK);
g.drawString("Project 3 by Benjamin Koch",10,15);
g.drawString(hitDisplayString,10,30);
int f = findTargetMissilePosition(targetMissileActive);
drawTargetMissile(g, TARGET_MISSILE_COLOR, f);
drawShooter(g,SHOOTER_COLOR);
if (targetHitTimer > 0)
drawTarget(g, SHIELD_HIT_COLOR);
else
drawTarget(g,TARGET_COLOR);
Color shieldColor = BACKGROUND_COLOR; // default: do not draw
if (shieldActive) {
if (shieldHitTimer > 0)
shieldColor = SHIELD_HIT_COLOR;
else
shieldColor = SHIELD_COLOR;
}
drawShield(g, shieldColor);
}
public static int findTargetMissilePosition (boolean[] data) {
for (int i=0;i<MAX_MISSILES;i++) {
if (data[i]==false) {
return i;
}
}
return -1;
}
Inside your initialize() function, you're creating local variables but not initializing the global ones.
targetMissileActive = new boolean [9];
targetMissilePositionX = new int [9];
targetMissilePositionY = new int [9];
targetMissileDeltaX = new int [9];
targetMissileDeltaY = new int [9];
for (int i=0; i<9; i++) {
targetMissilePositionX[i] = 0;
targetMissilePositionY[i] = 0;
targetMissileDeltaX[i] = 0;
targetMissileDeltaY[i] = 0;
targetMissileActive[i] = false;
}
This will reference the variables to the global one.

Word object changing after pushing onto stack Java

while(!paths.isEmpty()){
BoggleSearchState2 path = paths.pop();
if(dictionary.contains(path.getWord()) && !foundWords.contains(path.getWord())){
foundWords.add(path.getWord());
}
int[][] grid = path.getGrid();
int row = path.getRow();
int column = path.getColumn();
Letter[][] game = path.getGame();
if(row < (grid.length-1) && grid[row+1][column] == 0) {
paths.push(new BoggleSearchState2(path.getWordWord(), game[(row+1)][column], game));
}
}
My BoggleSearchState2 constructor is overloaded like this:
public BoggleSearchState2(Letter l, Letter[][] gameIn) {
game = gameIn;
word = new Word(l);
grid = initialGrid(l);
row = l.getPoint().y;
column = l.getPoint().x;
stringWord = wordToString(word);
}
public BoggleSearchState2(Word wordIn, Letter l, Letter[][] gameIn){
game = gameIn;
word = new Word(wordIn.getLetters());
word.addLetter(l);
grid = genGrid(word, game);
row = l.getPoint().y;
column = l.getPoint().x;
stringWord = wordToString(word);
}
With my class variables like this:
public class BoggleSearchState2 {
private Word word;
private Letter[][] game;
private int[][] grid;
private String stringWord;
private int row, column;
The problem i am having is that after i push the new BoggleSS2, my path.word changes and adds another letter object. i do not know how this is happening. can anyone tell me why?
public class Word {
private ArrayList<Letter> word;
public Word(Letter l) {
word = new ArrayList<Letter>();
word.add(l);
}
public Word(ArrayList<Letter> listLetters, Letter l){
word = listLetters;
word.add(l);
}
public Word(ArrayList<Letter> letters) {
word = letters;
}

Hard time with factory method implementation in java

So, I have a class that represents a game board (4x4), each space is the face value of a die, represented internally by an arraylist. I'm supposed to implement factory methods to generate the board.
public class Board {
static ArrayList<Die> board = new ArrayList<Die>();
public static Board makeFixedBoard(DiceManager dice) {
for (int i = 0; i < 16; i++) {
//add faces
}
return new Board();
}
}
However, I'm having a hard time understanding exactly how to implement the factory method. Here, my return is a new board, but that just creates a new empty board rather than the one I generated.
This is the die class
public class Die {
char[] faces = new char[6];
char facevalue;
public Die(char side1, char side2, char side3, char side4, char side5, char side6){
faces[0] = side1;
faces[1] = side2;
faces[2] = side3;
faces[3] = side4;
faces[4] = side5;
faces[5] = side6;
facevalue = faces[0];
}
public void roll() {
int roll = 0 + (int)(Math.random() * 6);
facevalue = faces[roll];
}
public char getValue() {
return facevalue;
}
There is no need to keep board as static.
private ArrayList<Die> board = new ArrayList<Die>();
public static Board makeFixedBoard(DiceManager dice) {
Board boardInstance = new Board();
for (int i = 0; i < 16; i++) {
//add faces
boardInstance.board.add(die);
}
return boardInstance;
}
You first need to create instance of Board and then in the for loop add the die you create into the boardInstance, after all the die have been added, you return the created instance of the board to the caller.

java text based world moving elements around

I have a project that i cannot for the life of me figure out the moving pattern, whether some object is in the same place as another, or how to interact with each project, here is the first class:
public class AnimalKingdom {
public static final int WORLD_ROWS = 4;
public static final int WORLD_COLUMNS = 4;
public static final int ROUNDS = 10;
public static void main(String[] args) {
Animal[] animals = new Animal[10];
animals[0] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[1] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[2] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[3] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[4] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[5] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[6] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[7] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[8] = new Wolf(WORLD_ROWS, WORLD_COLUMNS);
animals[9] = new Wolf(WORLD_ROWS, WORLD_COLUMNS);
for (int i = 1; i < ROUNDS; i++) {
showWorld(animals);
doEating(animals);
doMoving(animals);
}
}
public static void showWorld(Animal[] animals) {
System.out.println();
System.out.println("The World");
/* The world is made of rows and columns.
Each location must be big enough to list all the animals
(in case they all show up at that spot at once). So we print
the single character string for each animal, then later add in enough
blanks to ensure that the lines between locations are neatly
drawn. */
for (int r = 0; r < WORLD_ROWS; r++) {
for (int c = 0; c < WORLD_COLUMNS; c++) {
int localAnimals = 0;
for (int a = 0; a < animals.length; a++) {
if (animals[a] != null) { // as animals die, nulls will be left in the array
int ar = animals[a].getRow();
int ac = animals[a].getCol();
if (r == ar && c == ac) { // this animal is local to this location
localAnimals++;
System.out.print(animals[a]); // draw the animal
}
}
}
// create enough blanks to fill out the location
for (int i = 0; i < animals.length-localAnimals; i++) {
System.out.print(" ");
}
System.out.print("|");
}
System.out.println();
}
System.out.println();
}
public static void doEating(Animal[] animals) {
// This needs to be filled in
}
public static void doMoving(Animal[] animals) {
// This needs to be filled in
}
}
And here is the second part of my coding:
import java.util.Random;
public class Animal {
private Random rand = new Random();
private int worldWidth;
private int worldHeight;
private int row;
private int col;
public Animal(int worldHeight, int worldWidth) {
this.worldHeight = worldHeight;
this.worldWidth = worldWidth;
row = rand.nextInt(worldHeight);
col = rand.nextInt(worldWidth);
}
public boolean willEat(Animal anim) {
return false;
}
public void move() {
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public void setRow(int r) {
row = r;
}
public void setCol(int c) {
col = c;
}
public String toString() {
return "";
}
public int getWorldWidth(){
return worldWidth;
}
public int getWorldHeight(){
return worldHeight;
}
public boolean isInSamePlaceAs(Animal other) {
return false; // code needs to be replaced
}
}
Each subclass is named Worm, Bird, and Wolf. Each subclass toString is represented in the form of one char. 'B' for Bird, '.' for Worm, and 'W' for Wolf. The worms can move left and right, remembering the direction they are going in and reverse if they hit a wall or end/beginning of array. The Bird moves diagonally in the world. The Wolf is allowed to move in any direction.
I just need help with starting to make movements in the doMoving(), help identify isInSamePlaceAs() and help doEating(). Birds eat worms, Wolves eat Birds, and worms do nothing.

Java:JGraphT add edges using a loop

Is it possible to add edges to a graph through the use of a loop? I am parsing a String to determine the appropriate edges and labels. For some reason it will only add the edge for the first round of the while loop used to iterate through the String. For all of the others the following message appears...
Warning: an edge was deleted because the underlying JGraphT graph refused to create it. This situation can happen when a constraint of the underlying graph is violated, e.g., an attempt to add a parallel edge or a self-loop to a graph that forbids them. To avoid this message, make sure to use a suitable underlying JGraphT graph.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import org.jgraph.*;
import org.jgraph.graph.*;
import org.jgrapht.*;
import org.jgrapht.ext.*;
import org.jgrapht.graph.*;
// resolve ambiguity
import org.jgrapht.graph.DefaultEdge;
public class JGraphAdapterDemo
extends JApplet
{
private static final long serialVersionUID = 3256444702936019250L;
private static final Color DEFAULT_BG_COLOR = Color.decode("#FAFBFF");
private static final Dimension DEFAULT_SIZE = new Dimension(530, 320);
static ListenableGraph<String, String> g =
new ListenableDirectedMultigraph<String, String>(String.class);
static int [] finalStates = new int[10];
static int startState = 0;
static char tran = ' ';
static int endState = 0;
private JGraphModelAdapter<String,String> jgAdapter;
public static void main(String [] args)
{
JGraphAdapterDemo applet = new JGraphAdapterDemo();
applet.init();
JFrame frame = new JFrame();
frame.getContentPane().add(applet);
frame.setTitle("JGraphT Adapter to JGraph Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void init()
{
// create a JGraphT graph
ListenableGraph<String, String> g =
new ListenableDirectedMultigraph<String, String>(String.class);
// create a visualization using JGraph, via an adapter
jgAdapter = new JGraphModelAdapter<String, String>(g);
JGraph jgraph = new JGraph(jgAdapter);
adjustDisplaySettings(jgraph);
getContentPane().add(jgraph);
resize(DEFAULT_SIZE);
int numStates = 4;
int numSymbols;
int currentState;
int i = 0;
String input = "4 2 0 2 -1 0 a 1 1 b 3 2 c 2 3 c 3 -1"; //place input String here
int readInt = 0;
int j = 0;
String str = "";
int place = 0;
String fState;
//read in numStates, numSymbols, initialState
i=0;
//parse string
i = input.indexOf(" ",0);
str = input.substring(0,i); //number of states
numStates = Integer.parseInt(str); //convert to int
for(int k = 0; k< numStates; k++){
g.addVertex("q"+k);
}
i++;
j = i;
i=input.indexOf(" ",j);
str = input.substring(j,i); //number of symbols
numSymbols = Integer.parseInt(str);
i++;
j = i;
i=input.indexOf(" ",j);
str = input.substring(j,i); //initial state
currentState = Integer.parseInt(str);
i++;
j = i;
//read in finalStates
while(readInt!=-1){
i=input.indexOf(" ",j);
fState = input.substring(j,i); //a final state
readInt = Integer.parseInt(fState);
if(readInt!=-1){
finalStates[place] = readInt;
i++;
j = i;
place++;
}//end if
}//end while
i++;
j = i;
String sState;
String eState;
while(startState!=-1&& j<(input.length()-2)){ //until end of file
i=input.indexOf(" ",j);
sState = input.substring(j,i); //start state
startState = Integer.parseInt(sState); //convert to int
if(startState!=-1){
i++;
j = i;
String cStr = "";
tran = input.charAt(i); //transition
cStr = cStr + tran;
i = i+2;
j=i;
i=input.indexOf(" ",j);
eState = input.substring(j,i); //end state
endState = Integer.parseInt(eState);
i++;
j=i;
String one = "q"+startState;
String two = "q"+endState;
System.out.println(one+ two +" "+cStr);
g.addEdge(one, two, cStr);
//drawEdge(one, two, cStr);
}//end if
}//end while
}
public static void drawEdge(String v, String v1, String label){
System.out.println(v +" "+v1+ " "+label);
g.addEdge(v,v1,label);
}
private void adjustDisplaySettings(JGraph jg)
{
jg.setPreferredSize(DEFAULT_SIZE);
Color c = DEFAULT_BG_COLOR;
String colorStr = null;
try {
colorStr = getParameter("bgcolor");
} catch (Exception e) {
}
if (colorStr != null) {
c = Color.decode(colorStr);
}
jg.setBackground(c);
}
#SuppressWarnings("unchecked") // FIXME hb 28-nov-05: See FIXME below
private void positionVertexAt(Object vertex, int x, int y)
{
DefaultGraphCell cell = jgAdapter.getVertexCell(vertex);
AttributeMap attr = cell.getAttributes();
Rectangle2D bounds = GraphConstants.getBounds(attr);
Rectangle2D newBounds =
new Rectangle2D.Double(
x,
y,
bounds.getWidth(),
bounds.getHeight());
GraphConstants.setBounds(attr, newBounds);
// TODO: Clean up generics once JGraph goes generic
AttributeMap cellAttr = new AttributeMap();
cellAttr.put(cell, attr);
jgAdapter.edit(cellAttr, null, null, null);
}
//~ Inner Classes ----------------------------------------------------------
/**
* a listenable directed multigraph that allows loops and parallel edges.
// */
private static class ListenableDirectedMultigraph<V, E>
extends DefaultListenableGraph<V, E>
implements DirectedGraph<V, E>
{
private static final long serialVersionUID = 1L;
ListenableDirectedMultigraph(Class<E> edgeClass)
{
super(new DirectedMultigraph<V, E>(edgeClass));
}
}
}
If you want to use a graph that allows loops you have to create an abstract class "AbstractBaseGraph". For this reason you have to create another class that extends your super class. Here's an example.
public class MiGrafo
extends AbstractBaseGraph<String, DefaultEdge>
implements DirectedGraph<String, DefaultEdge> {
public MiGrafo() {// EdgeFactory<String, DefaultEdge> arg0, boolean arg1,boolean arg2
super(new ClassBasedEdgeFactory<String, DefaultEdge>(
DefaultEdge.class),
true,
true);
// TODO Auto-generated constructor stub
}
}
In addition you have to implement a directed or undirected graph follow of your extends.
When you create the new graph that allows using loops you only have to write this sentence:
MiGrafo h = new MiGrafo();
Finally you only have to use the graph like a simple graph.
See you.

Categories

Resources