Hard time with factory method implementation in java - 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.

Related

Dack/Card array duplicating between Hands and Poker Board

EDIT: I have partially resolved the issue. I had previously removed the for loop fro it's own method and put it into main for it to work, but for some reason it was not working this time. That's because a new Cards object was being initialized (underneath //The Flop comment), which I guess reset the deck. If i remove that and place the loop there instead of it's own method, it works. However, the issue still happens within the method because I need to create a new object to "communicate" with the deck class. I will try to either pass in the object as an argument or set it somewhere accessible and see if that works, then I will re-edit this post.
Edit 2: Passing in the Cards Object as an argument has worked! Will post as answer.
Start of post:
I'm trying to write a Texas Hold 'em game for my class. I'm trying to use methods to tidy up the main(). Unfortunately, it seams Cards are being duplicated between the other arrays I have (The Player's Hand, Opponents Hand, and Board. I don't seem to be on my teacher's favorites list so he doesn't provide much help when asked for it.
Here is the main class:
public class PokerGame
{
private int pot = 0;
public static void main(String[] args)
{
//Create Objects to connect classes.
Deck Cards = new Deck(0, "s");
Player Player = new Player();
Opponents Op1 = new Opponents();
//Bring deck into this main class.
Deck[] aDeck = new Deck[52];
Deck[] fDeck = Cards.buildDeck(aDeck);
Deck[] mDeck = Cards.shuffle(fDeck, 100);
//Create the Board and Hand arrays.
Deck[] Board = new Deck[5];
Deck[] Burned = new Deck[3];
Deck[] pHand = new Deck[2];
Deck[] o1Hand = new Deck[2];
int count;
for(count = 0; count < pHand.length; count++)
{
pHand[count] = Cards.deal(mDeck);
System.out.println("P " + pHand[count].namedRank + " of " + pHand[count].s);
o1Hand[count] = Cards.deal(mDeck);
}
System.out.println("o1 " + o1Hand[0].namedRank + " of " + o1Hand[0].s);
System.out.println("o1 " + o1Hand[1].namedRank + " of " + o1Hand[1].s);
//The Flop
Cards = new Deck(0, "s");
Burned[0] = Cards.deal(mDeck);
Board = flop(Board, mDeck);
//The Turn
Burned[1] = Cards.deal(mDeck);
Board[3] = Cards.deal(mDeck);
System.out.println("\n\n");
System.out.println("Now the Board is...");
for(int b = 0; b < 4; b++)
{
System.out.println(Board[b].namedRank + " of " + Board[b].s);
}
showdown(Board, pHand, o1Hand);
}
public static Deck[] flop(Deck[] Board, Deck[] mDeck)
{
Deck Cards = new Deck(0, "s");
System.out.println();
System.out.println("The Board is...");
for(int b = 0; b < 3; b++)
{
Board[b] = Cards.deal(mDeck);
System.out.println(Board[b].namedRank + " of " + Board[b].s);
}
return Board;
}
And this is the Deck class where I shuffle and deal.
public class Deck
{
public Deck[] Deck = new Deck[52];
private int index = 0;
public int rank;
public String s;
public String namedRank;
private int x = 0;
/**
* Constructor for card Objects
*
* Cannot get to work, not sure where issue is.
*/
public Deck(int rank, String s)
{
if(rank == 1)
{
this.rank = 14;
}
else
{
this.rank = rank;
}
String numRank = String.valueOf(rank);
if(this.rank == 11)
{
this.namedRank = "Jack";
}
else if(this.rank == 12)
{
this.namedRank = "Queen";
}
else if(this.rank == 13)
{
this.namedRank = "King";
}
else if(this.rank == 14)
{
this.namedRank = "Ace";
}
else
{
this.namedRank = numRank;
}
this.s = s;
}
/**
* Assigns each element in the array a card
*
* #param Deck array before elements assigned
* #return Deck array after elemnts assigned
*/
public Deck[] buildDeck(Deck[] fDeck)
{
String[] suit = {"Club", "Diamond", "Heart", "Spade"};
int c;
String of = " of ";
for(c = 0; c < suit.length; c++)
{
for(rank = 1; rank < 14; rank++)
{
s = suit[c];
fDeck[x] = new Deck(rank, s);
x++;
}
}
return fDeck;
}
/**
* Shuffles the cards by picking to random numbers and switching them
*
* #param Deck array after elemetns assigned
* #return Deck array after elements are mixed up
*/
public Deck[] shuffle(Deck[] mDeck, int shuffle)
{
for(int count = 0; count < shuffle; count++)
{
int f = ((int)(Math.random() * 100) % 51 + 1);
int s = 0;
Deck move = mDeck[f];
mDeck[f] = mDeck[s];
mDeck[s] = move;
}
return mDeck;
}
/**
* Deals the cards and keeps track by incrasing the index
*
* #param Deck array after elements are mixed up
* #return single Deck array element at whatever position int index is at
*/
public Deck deal(Deck[] dDeck)
{
index++;
return dDeck[index];
}
}
Literally any help is much appreciated as I've been scratching my head on this for a long time already. Will be continuing what I can mess around with before I have to head to work.

Passing an array as a parameter- chess board

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;

Why doesn't this class execute properly?

Here is my first class called World
public class World {
private static char[][] world2D;
private int characterRow;
private int characterColumn;
public World(int width, int height){
world2D = new char[width][height];
characterColumn = 0;
characterRow = 0;
for(int i = 0; i < world2D.length; i++){
for(int j = 0; j < world2D[i].length; j++){
world2D[i][j] = '-';
}
}
world2D[characterRow][characterColumn] = 'P';
}
public void moveUp(){
world2D[characterRow][characterColumn] = '-';
if (characterRow > 0){
characterRow -= 1;
}
world2D[characterRow][characterColumn] = 'P';
}
public void moveDown(){
world2D[characterRow][characterColumn] = '-';
if (characterRow < world2D.length){
characterRow += 1;
}
world2D[characterRow][characterColumn] = 'P';
}
public void moveRight(){
world2D[characterRow][characterColumn] = '-';
if (characterColumn < (world2D[characterRow].length - 1)){
characterColumn += 1;
}
world2D[characterRow][characterColumn] = 'P';
}
public void moveLeft(){
world2D[characterRow][characterColumn] = '-';
if (characterColumn > 0){
characterColumn -= 1;
}
world2D[characterRow][characterColumn] = 'P';
}
public static void displayWorld(){
for(int i = 0; i < world2D.length; i++){
for(int j = 0; j < world2D[i].length; j++){
System.out.print(world2D[i][j]);
}
System.out.println();
}
}
}
Here is my second class called Driver
import java.util.Scanner;
public class Driver {
public static void main(String[]args){
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("How tall should the world be?: ");
int height = input.nextInt();
System.out.print("How wide should the world be?: ");
int width = input.nextInt();
World myWorld = new World(width,height);
World.displayWorld();
}
}
Why don't I need to call displayWorld specifically on the myWorld instance of the World class?
What if I created multiple World instances? This can't be right.
**edit for more detail
I want to call one of the class methods (i.e. moveUp or moveDown) on the instance of the World class myWorld object. However, I can't pass my reference to that object (myWorld) into those methods. I want to be able to call one of those methods, which changes the postion of 'P' in the 2 dimensional array and print it out using the methods that I have defined including the displayWorld method
Please refer to this link to learn more about static types.
If you want to display worlds of different instances, remove static from public static void displayWorld() and call myWorld.displayWorld().
Static variables, such as private static char[][] world2D, exist within a class, not objects of that class. This means they are accessed through the class name, not an instance name. Since you are initializing it in your constructor, it will be changed each time you create a new world, but the value will be the same for each instance. It looks like you should make the variable world2D non-static (just remove the static keyword) and do the same on the function displayWorld()
Then, the line World.displayWorld(); can be replaced with myWorld.displayWorld();

Creating Array of objects and read the information

I am creating a Box[] with box objects(i.e.boxes[box1,box2,box3]),then writing a method to access the element in Box[], I encountered no Pointer error.
public class GameState
{
public static final int noOfSquares = 10; // the extent of the board in both directions
public static final int noOfBoxes = 3; // the number of boxes in the game
private Square[][] board; // the current state of the board
private Box[] boxes; // the current state of the boxes
private int score; // the current score
// initialise the instance variables for board
// all squares and all boxes are initially empty
public GameState()
{
score = 0;
board = new Square[10][10];
Box[] boxes = new Box[3];
for(int j =0;j<boxes.length;j++){
boxes[j] = new Box();
}
// return the current state of the board
public Square[][] getBoard()
{
return board;
}
// return the current contents of Box i
public Box getBox(int i)
{
if (0 <= i && i < noOfBoxes) **// here doesn't work**
{
return boxes[i];
}
else {
return null;
}
}
// return the current score
public int getScore()
{
return score;
}
}
}
There are no errors in the box class,in which Box() creates a new null box.
Thanks for help.
You're shadowing the variable boxes. Replace
Box[] boxes = new Box[3];
with
boxes = new Box[3];

Java Dice Game Trouble Generating new numbers

I am trying to learn OOP, starting with Java as I have read and been told it's the best place to start. With that said, I am trying to create a game for fun to help my learning, but I also know game programming and design can be more challenging.
So my goal here is to generate a new value from the RollDice D20 without having to reset or restart the program. You'll notice when I print out the values I print the same instance twice to demonstrate what I am avoiding, and a new instance to show that the new instance does indeed generate a new value. Perhaps, I am not approaching this in the right way, but this is a hurdle I am hoping to overcome with some help!
What I ultimately want is to figure out how to generate a new instance or at least a new roll value as many times as I want. Any and all help is greatly appreciated! I have added the code below as an example. Also any other feedback is appreciated.
import java.util.Random;
class RollDice
{// Begin RollDice Class
// Initiate method rollDice
public static int rollDice(int number, int nSides)
{
// System.out.println( "--- Welcome to the Dice Game v2! ---" ); //
// welcomes player
Random r = new Random();
// Declare class variables
int num = 0;
int roll = 0;
if (nSides >= 3)
{
for (int i = 0; i < number; i++)
{
roll = r.nextInt(nSides) + 1;
// System.out.println("Roll is: " + roll);
num = num + roll;
}
}
else
{
System.out.println("Error num needs to be from 3");
}
return num;
} // end method rollDice
int d4 = rollDice(1, 4);
int d6 = rollDice(1, 6);
int d8 = rollDice(1, 8);
int d10 = rollDice(1, 10);
int d12 = rollDice(1, 12);
int d20 = rollDice(1, 20);
public RollDice()
{
this.d4 = d4;
}
public void setD4(int D4)
{
this.d4 = D4;
}
public int getD4()
{
return d4;
}
// ////////////////
{
this.d6 = d6;
}
public void setD6(int D6)
{
this.d6 = D6;
}
public int getD6()
{
return d6;
}
// ////////////////
{
this.d8 = d8;
}
public void setD8(int D8)
{
this.d8 = D8;
}
public int getD8()
{
return d8;
}
// ////////////////
{
this.d10 = d10;
}
public void setD10(int D10)
{
this.d10 = D10;
}
public int getD10()
{
return d10;
}
// ////////////////
{
this.d12 = d12;
}
public void setD12(int D12)
{
this.d12 = D12;
}
public int getD12()
{
return d12;
}
// ////////////////
{
this.d20 = d20;
}
public void setD20(int D20)
{
this.d20 = D20;
}
public int getD20()
{
return d20;
}
// ////////////////
}// End RollDice Class
class Champion
{// Begin Champion Class
RollDice champDice = new RollDice();
int champroll = champDice.getD20();
public Champion()
{
this.champroll = champroll;
}
public void setChampRoll(int ChampRoll)
{
this.champroll = ChampRoll;
}
public int getChampRoll()
{
return champroll;
}
}// End Champion Class
public class DiceRollTest
{
public static void main(String ars[])
{
Champion tChampion = new Champion();
Champion pChampion = new Champion();
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + pChampion.getChampRoll() + "\n");
}
}
Your RollDice class is not accomplishing what you want. All it's doing is storing a single dice roll result for each type of dice you have. Therefore, when you go an call getChampRoll() on your Champion object, all it's doing is returning the roll that already took place when you constructed your RollDice class.
Instead, you should make rollDice() a member function of your RollDice class. RollDice should then take in its constructor an argument indicating which dice should be rolled when rollDice() is called. That way, when you call getD20(), it will roll the D20 and give you the result.
I'll leave you with this as a starting point:
import java.util.Random;
public class Die {
private int mSides;
private Random mRandom;
public Die(int sides) {
this.mSides = sides;
mRandom = new Random(System.currentTimeMillis());
}
public int roll() {
return mRandom.nextInt(mSides + 1);
}
public int roll(int times) {
int sum = 0;
for (int i = 0; i < times; i++) {
sum += roll();
}
return sum;
}
}
This class can be inherited/subclassed for each dice you want to create. Then you can toss a few of these in your champion's pockets :)
First, you should create new Constructor. In this constructor you should inicialize Random object, and probably how many sides will dice have
class RollDice{
Random rand;
int sides;
public RollDice(int x){
sides = x;
rand = new Random()
}
}
then, in that class you can add method which will generate new value
public int roll(){
return rand.nextInt(x);
}
you may as well don,t generate RollDice object with fixed value of dice's sides and make the method like:
public int roll(int x){
return rand.nextInt(x);
}
if you want java to generate new value after you enter something on console just use loop with System.in.read() and if or switch statement (for example if someone enters 1 - generate new value, if 0, end program)

Categories

Resources