moving a player around a 2d monopoly game array - java

I am creating the player class for a monopoly board game. I am not exactly sure how to make the player move around the board and then store that players position. I have created an array with 40 places using
BoardSquare[] square = new BoardSquare[40];
and i have created two die using
diceOne=1+(int)(Math.random()*6);
diceTwo=1+(int)(Math.random()*6);
roll=diceOne+diceTwo;
this is the code for my player class so far
class Player
{
private String name;
private String token;
private int location;
private int balance;
public Player()
{
name = "";
token = "";
location = 0;
balance = 1500;
player = (name+token+location+balance);
}
public Player(String name, String token, int location, int balance)
{
this.name = name;
this.token = token;
this.location = location;
this.balance = balance;
}
i realize i need to initialize a player to zero and then add the value of the rolled die to give the plahyer a position on the board. However, i am really not sure what happens when space runs out, how to properly develop the for loop, etc. I have looked at some examples but i am not really sure how to properly develop the logic for a board game. Any suggestions about board game development that are outside of the scope of this question are most welcome. thx.

You can use the modulo operator to wrap positions around, e.g.:
int newPosition = (oldPosition + diceRoll) % 40;
As for passing Go you have many options. It's simplest if you define Go as index 0. You can compute the position before modulo 40 and check if its greater than 40 (meaning its about to wrap around). You can also check to see if the new position is less than the old position (which works presuming you can never have a dice roll >= 40).

Just before updating the new position of the player ,do the following check:
if(position>40)
{
position=position-40
}
update the changed position with the specifics of money

Related

Assign random class object (image) to ImageView

I'm developing a card game, based on higher wins.
From my first question here assign int value to image for compare I've rewritten my code but now I'm stuck on randomization of cards and assignment to ImageView.
I have a class card.
public class Card{
private int cardValue;
#DrawableRes
private int image;
public Card(int cardValue, #DrawableRes int image){
this.cardValue = cardValue;
this.image = image;
}
public int getCardValue()
{
return cardValue;
}
#DrawableRes
public int getCardImage()
{
return image;
}
//Cards
Card ash = new Card(20, R.drawable.ash_card);
Card atlas = new Card(23, R.drawable.atlas_card);
Card banshee = new Card(14, R.drawable.banshee_card);
and so on....
In MainActivity:
I have array of this cards:
//Creating array of the cards
ArrayList<Card> cards = new ArrayList<>();
Now I need to randomize four cards from this array and assign each one to IV.
final Random random1 = new Random();
//Generate random indexes for cards
int RandomCard1 = random1.nextInt(cards.size());
int RandomCard2 = random1.nextInt(cards.size());
int RandomCard3 = random1.nextInt(cards.size());
int RandomCard4 = random1.nextInt(cards.size());
//Generate the card from RandomCard
Card drawableCard1 = cards.get(RandomCard1);
Card drawableCard2 = cards.get(RandomCard2);
Card drawableCard3 = cards.get(RandomCard3);
Card drawableCard4 = cards.get(RandomCard4);
I'm using this, because I have flip animation for each card (maybe there is a better way to do it, but it works for me). So now I just need to assign a card to IV, but this won't work.
//Deal my cards
card1.setImageResource(drawableCard1);
card2.setImageResource(drawableCard2);
card3.setImageResource(drawableCard3);
card4.setImageResource(drawableCard4);
I can't use setImageResource for class object. I've been stuck here for days, trying to figure it out but with no luck. Should I do randomizing differently (f.e. with Collections.shuffle?). Or is there any way how to do it?
Thank you.
You actually have two different problems:
the simplest is that your cards are not showing since setImageResource requires the int representing the resource id as parameter, you'll just need to call:
//Deal my cards
card1.setImageResource(drawableCard1.getCardImage());
card2.setImageResource(drawableCard2.getCardImage());
card3.setImageResource(drawableCard3.getCardImage());
card4.setImageResource(drawableCard4.getCardImage());
Now if the UI is correctly set up you'll see the images.
The second problem (I don't know if it's intended behavior) is that some cards could be given repeatedly, since the algorithm just generates a number within the bound and repetitions could occur.
A possible solution is, as you suggested, using Collections.shuffle() on the deck at the beginning so that it would simulate the initial deck shuffling and start dealing the cards in the exact order in which they are contained in your shuffled deck.
How to deal cards
Currently, if we consider our deck to be the entire List of Card objects, the way in which the dealer is picking the next card to give is by choosing a random card in any position of the deck (list) and put it on the table (for example). This idea could be extended by removing the picked card from the deck (which is something that at the moment is not implemented), but the dealing style wouldn't represent what happens in reality.
Solution
The solution would be shuffling the cards at the beginning of the game (Collections.shuffle()) and start picking the card in the exact order in which they are contained in the list. In fact, since it's already shuffled, the dealer can pick the 0-th, 1-st, 2-nd
etc. card and put them on the table (or give them to the players). The Random object, in this case, wouldn't be needed. A simple cycle could be implemented to select the next card the dealer will pick.

Create and connect locations for a game

I want to make a text adventure game as a school project and I was wondering how it would be possible to create and connect game locations in which the story takes place.
I thought of making a super class Location with variables like name and a two-dimensional array like
int[][] locnow = new int[20][20];
for the location position itself (north, west, east, south point).
My main questions are
Is it a good way to realise something like this in this way, or is something different better?
How can I load locations like "Button Click -> go east" and the location one to the east is loaded?
Thank you for your help.
What about:
public class Location {
private int x, y;
private String name;
// getters and setters here
}
Combined with
public class Game {
private GameTile[][] field;
// getters and setters here
}
public class GameTile {
// some tile-specific information goes here
}
Thay way, you store the game-field specific information (in GameTile, if needed). If you don't need the GameTile class, you can just leave out the array in the Game class, and just store the maximum dimensions.
How does this answer your question:
Going east would just be x += 1,
west x -= 1,
etc...

ImageIcon Updating for Hangman GUI Java

For my group project we are doing a fairly standard Hangman GUI game.
I have created a series of .png files depicting a flower that wilts as the game progresses with wrong guesses.
I have got the code to insert the ImageIcon into a JLabel, and that works fine. But I don't know how to code for the image changing when a wrong answer is guessed.
I am thinking I should create an array of the series of images and iterate through it according to the guessesLeft variable that keeps track of the number of guesses a user still has to correctly guess the puzzle.
Any ideas?
I'd recommend you to link each image to the number of guesses.
Then make method updateScore that will update user score (or guesses left) and work with images. Something like:
public class ImagedScore {
private final int guessesLeft;
private final Image image;
//getters&constructor
}
public class MainClass {
ImagedScore[] imagedScoreArray;
//constructors, other methods and data, etc.
updateScore(int score) {
ImagedScore imagedScore = imagedScoreArray[score];
//checks or other way to find proper ImagedScore object
this.score = score;
this.image = imagedScore.getImage;
}
}

Need help figuring out Basic Chess movement logic

Sorry for wall of text, but currently stumped. I'm not asking to be "spoon feed" since I have the basic idea down for each piece, it's just I'm having a difficult time on how to finish determining my move logic. Allow me to further explain. I'll be posting my code as well for better reference.
I'm coding with a MVC structure. I have a Model which is a 2D array of BoardSquares. Which those BoardSquares keep track of it's location on the board, what piece is in it (if there is one), what color that piece is (if there is one), and if it's empty. Here's the code for it:
public class BoardSquare {
// Private information stored in each BoardSquare
private boolean isSquareEmpty;
private int row;
private int col;
private String space;
private String pColor;
// Constructor to make an empty space on the board
public BoardSquare(int row, int col) {
space = "";
pColor = "";
this.row = row;
this.col = col;
SquareEmpty();
}
//Constructor to get the information of a space with a piece
public BoardSquare(BoardPiece piece, int row, int col) {
this.space = piece.getModelName();
this.pColor = Character.toString((piece.getModelName().charAt(0)));
this.row = row;
this.col = col;
SquareNotEmpty();
}
public String getpColor() {
String temp = getPieceColor(pColor);
return temp;
}
//A bunch of auto generated getters/setters...
// Gets the correct color label for the piece
public String getPieceColor(String info){
String temp;
if(info.equalsIgnoreCase("b")){
temp = "Black";
}
else {
temp = "White";
}
return temp;
}
Currently all my Pieces extend an abstract BoardPiece class which has several abstract methods as well, but my piece knows of it's location on the board, it's name, it's color, and the 2D board array for the way I'm generating the valid moves.
I'm generating them by checking the spaces it can move to and seeing if they are empty and adding them to an ArrayList and comparing and seeing if that list contains the inputted destination.
However I'm having problems thinking of how to stop checking if say Black Rook was on the left side of the board and wanted to move all the way to the Right, but there was a Black Pawn to the right of the Rook preventing it from doing so. I'm trying to generically think of it to make my life easier and I can implement it in the other piece classes as well So here's the Rook's code:
public class Rook extends BoardPiece{
private String name = "Rook";
private String color;
private String modelName;
BoardSquare board[][];
// Both should remain 0 - 7
private int row;
private int col;
public Rook (String modelName, int row, int col, String color, BoardSquare[][] field) {
this.modelName = modelName;
this.row = row;
this.col = col;
this.color = color;
this.board = field;
}
#Override
void move(BoardSquare target) {
if(!getPossibleMove(board).contains(target)){
//Sysout false move
}
}
#Override
Collection<BoardSquare> getPossibleMove(BoardSquare[][] board) {
ArrayList<BoardSquare> validMoves = new ArrayList<BoardSquare>();
for(int i = 0; i < 8; i++){
// Checks every column of the row that the piece is on
if(moveValidator(board[row][i])){
validMoves.add(board[row][i]);
}
// Checks every row of the column that the piece is on
if(moveValidator(board[i][col])){
validMoves.add(board[i][col]);
}
}
return validMoves;
}
#Override
boolean moveValidator(BoardSquare space) {
// Removes the current square the piece is on as a valid move
if(space.getRow() == getRow() && space.getCol() == getCol()){
return false;
}
//Checks if the space is not empty and the piece in the spot is the same color as the piece itself
if(!space.isEmptySquare() && space.getpColor().equalsIgnoreCase(color)){
return false;
}
return true;
}
Like I said any help or push toward the right direction would be appreciated. Sorry for the wall of text but trying to be as clear as I can so that whoever wants to help can fully understand and see my logic.
EDIT: Forgot to note that the Rook has Auto-generated Getters and Setters as well.
I would approach it the most brute-force and intuitive way possible: think of moving the rook one square at a time as it takes its turn and see if it collides with anything. That is, hop it across every square until it gets to the desired spot and check if it's a valid move at each square.
This is a fine approach because
it's easy to understand
it's not expensive until your chess board gets massively huge, so brute force isn't a problem.
it generalizes to all pieces: rooks have to "slide" to their destination, but knights can "jump" or "teleport" over other pieces to their new location, so don't need the intermediate hops.
This sounds close to your current implementation, but you need to stop tracing when you collide. That is, if there is a black pawn in the way, the columns after that pawn are no longer valid spaces, right? In other words, think of the move as an action that the rook takes instead of an independent state space of possible moves, since some spaces are legal moves except that the rook was previously blocked. You need to know where the rook is from and where it is going to determine valid moves, not just if the space is in the same row.
So, reading your code (thanks for posting the context, by the way, it's quite helpful) really all you need to do is not iterate on each square, but iterate moving through each square, and stop the iteration when you get blocked.

Trying to avoid a Force close after a bullet goes off screen

So I'm just messing around learning to create a Space invaders type game. I can get the bad guys to move, Great!!. Hero moves, Great!! Bullets move, Great!! However I try to remove my bullets once they leave the screen as to not eat up all resources and it force closes on me once it gets rid of the bullet. It goes off the screen. Hits the int of -2 and then we use the remove() and boom. Force Close.
Here is my code. I'm wondering if they access the size() at the same time and just cause a force close because of it.
//I removed everything that doesn't pertane to the bullets.
public class GameScreen{
Bullet bullet = world.bullet;
public GameScreen(Game game) {
super(game);
world = new World();
}
//Draws our bullets.
int bulletLength = bullet.bullets.size();
for(int i = 0; i < bulletLength; i++) {
Placement part = bullet.bullets.get(i);
x = part.x * 32 + 11;
y = part.y * 32;
g.drawPixmap(Assets.bullet, x, y);
}
Class that holds my bullets.
public class Bullet {
public List<Placement> bullets = new ArrayList<Placement>();
public Bullet() {
}
public void shoot(int x, int y){
bullets.add(new Placement(x,y));
}
public void advance(){
int len = bullets.size(); // gets all bullets.
for(int i = 0; i < len; i++) {
bullets.get(i).y --;
if (bullets.get(i).y <= -2){//removes them once they are off the screen.
bullets.remove(i);
}
}
}
This is what I use to keep track of placement.
package com.learning.planecomander;
public class Placement {
public int x, y;
public Placement(int x, int y) {
this.x = x;
this.y = y;
}
}
When going through your list to remove bullets, you can remove bullets from a list but that affects the list immediately instead of after your loop is done. Since you are traversing to the length of the list at the start, you are going off the end of the list since you've removed elements. An example is probably more helpful than that description.
Let's say you have a list with three bullets (which I'll call a, b, c to make the example easier). On a pass through the list, a and c are fine but b needs to be removed.
i = 0;
bullets[0] = a;
bullets[1] = b;
bullets[2] = c;
First loop goes fine, second loop starts like this
i = 1;
bullets[0] = a;
bullets[1] = b;
bullets[2] = c;
We remove b, but the loop keeps going
i = 2;
bullets[0] = a;
bullets[1] = c;
OH CRAP ARRAYINDEXOUTOFBOUNDS! PROGRAM CRASHES!
The way to solve this is to use a temp list to store the bullets that need to be removed, and then once your update loop is finished, make a call to bullets.removeAll(temp)
Doing two passes is a good answer. It makes the loops simpler and easy to understand. If you'd like to do it in one pass though, iterate through the list in reverse order, and when you remove a bullet you can go to the next one and not worry about blasting past the end of the ArrayList.
Alternatively, you can keep your bullets in a linked list, and run through the list with an Iterator, which you can also use to remove items from the list with. Removing from the beginning middle or end of an linked list is always a constant time operation. Whereas removing from the beginning of an ArrayList can be more expensive. If you need random access to the elements in the list, then they can be inefficient. Keep in mind though, if you're only dealing with a handful of objects, then it doesn't really matter.
For bonus points, you might want to put all of your objects in a list, and then have your central loop process them all and have your game objects respond polymorphically to calls like dead?, think, move, draw or whatever you think is appropriate.

Categories

Resources