Skip to main content

New to java! Stuck in infinite loop or program doesn't work at all. Help please!

1 reply [Last post]
ayelleeeecks
Offline
Joined: 2011-10-19
Points: 0

Okay, so my teacher has assigned this project where we have to create a game called 'Opoly'. Basically, the user sets the size of the board via Scanner, and the program uses that number to create a board out of '*'s and 'O's. The 'O' represents your current position, for example, if a row of the board looked like this: ***O****************.... your position would be 4. The program runs this way, until the 'O' marker has reached the last position of the board. The "spinner" (which is just a Math.random int between 1 and 5) advances the 'O'.

The reward: your reward is initialized to 12. If you land on a position that is divisible by 5, then your reward doubles. If you land on the second to last position, your reward is divided by 5, and you position is reset to 0. However, if the second to last spot is divisible by 5, your reward is NOT doubled, it is ONLY divided by 5. If you spin a number that puts you off the board, your reward and position remain the same.

Here's the specific instructions if I did a poor job summarizing:

Programming Assignment: Opoly

For this assignment, your job is to create a kind of lobotomized version of a board game (such as Monopoly) called Opoly.

Opoly works this way: The board is a straight linear track of variable length (you determine the length when you start up the game). There is only one playing piece, which begins the game just off the board, at position 0. Thus, if the board length is 20, then the board positions start at position 1 and end at position 20. To finish the game, the piece must land exactly on the last cell of the board (e.g., cell 20 in the example above).

The object of the game is to acquire reward. The reward amount is initialized to 12. If your board piece lands on a board cell that is divisible evenly by 5, your reward doubles. However, if your piece lands one cell shy of the final board cell, your reward is reduced to 1/5 of its current value (via integer division), and your piece must go back to the start position - position 0. Note, though, that if the position of the last cell is divisible evenly by 5, then reward is doubled just before the game ends.

In Opoly the game piece advances via a spinner - a device that takes on the values 1-2-3-4-5 at random, with each advance value equally likely.

Two additional rules:

1) if a spin would move the piece beyond the end of the board, the piece should not advance at all (thus, if the piece is at location 18 of a 20 cell board, and if the spinner spins a 5, this is counted as a move but the piece remains at location 18.) If a piece doesn't move at all, its current reward amount should remain unchanged, even if the piece sits at a location that is divisible evenly by 5.

2) if the next to last board location is divisible by 5, and if the piece lands on this location, the reward is reduced to 1/5 of its current value only - the reward is NOT also doubled. Example: the board size is 26, and the piece is at location 23, with reward 30. Suppose the spinner spins a 2. This puts the piece on the next to the last location on the board (25). This resets the reward to 6 = 30 * 1/5, and places the piece at location 0. Even though location 25 is divisible by 5, no doubling happens.

Here is the driver class for the game:

import java.util.*;

public class OpolyDriver{
 
  public static void main(String[] args){
    System.out.println("Enter an int - the size of the board");
    Scanner s = new Scanner(System.in);
    int boardSize = s.nextInt();
    System.out.println("Board Size: " + boardSize);
    Opoly g = new Opoly(boardSize);
    g.playGame();
  }
}

Here is a sample run:

> java OpolyDriver

Enter an int - the size of the board

Board Size: 20

*O****************** 12 // current position is 2, current reward is 12

****O*************** 24 // current position is 5, reward is 24

*******O************ 24

**************O***** 48

********************O 96 // board size is 20, so reward doubles before game ends

game over

rounds of play 5

final reward 96

A requirement: your Opoly class must include and make use of the following methods, in addition to the Opoly constructor and principal method playGame(). These are:

    * spin - generates a integer value from 1 to 5 at random
    * move - advances the piece
    * spinAndMove - spins the spinner and then advances the piece according to the rules of the game (uses spin, move methods)
    * isGameOver - checks if game termination condition has been met
    * drawBoard - draws the board using *'s and an O to mark the current board position. Feel free to improve on the display we've shown above.
    * displayReport - reports the end of the game, and gives the number of rounds of play, and the final reward

How to proceed:

* First, decide on the attributes for the Opoly class. At any instant, what is the "state" of the board? What do you need to keep track of to give the final report? The answers to these questions will tell you what the attributes to Opoly can be.

* Second, write the Opoly constructor.

* Third, try to write the playGame method using the methods outlined above. A good way to proceed is to write a "dummy" drawBoard method first - instead of having it draw anything, merely have it print out the current position. Once you're satisfied with the general running of the game in this format, then work on the drawing part.

* My board rendering is particularly klunky. If you like, you may devise a better way to draw the board. Of course make sure that you get the numbers right.

Paste in your Opoly class in the box below:

NOTE: you may NOT use any import statements in your class. Use the Math class methods to generate your random numbers. Do NOT import the java.util library.

Now, the problem I am having is either one of two things. My board either continues on forever and ever and never reaches "game over" and has infinite rounds, OR the game ends after a few rounds and doesn't display the report that is should. I've gone through time and time again trying to fix the methods, but it just isn't working, and I keep digging myself a deeper hole.

public class Opoly{
  private int boardSize;
  int[] gameArray;
  private int position=0;
  private int reward;
  private int spins;
  private int moves;
  private int round=0;
 
  public Opoly(int boardSize){
    this.boardSize = boardSize;
    this.gameArray = new int[boardSize];
    this.position = 0;
    this.reward=12;
  }
 
  private void calcReward(){
    if((position%5==0)&&(position!=gameArray.length-1)){
      reward=reward*2; //doubles reward if position is divisible by 5
      round++; //adds one round to the round counter
    }
    else if(position==(gameArray.length-1)){
      reward=reward/5; //divides reward by 5 if you land on the second to last spot
      position=0; //bumps you back to position=0
      round++; //adds one round to the round counter
    }
    else {
      reward=reward;
      round++;
    }
  }
  public void spin(){//generates random integer for spinner
    this.spins = (int)(Math.random()*5+1);
  }
  public void move(){//advances the piece
    this.moves = position + spins;
    position+=moves;
  }
  public void spinAndMove(){//spins spinner and advances piece according to rules of game
    spin();
    move();
  }

  public void isGameOver(){//checks if condition for ending game is met
      System.out.println("game over");   
  }
  public void drawBoard(){//prints board with *'s and O's to show current position
    for(int k=0; k<=gameArray.length+1; k++){
      if(position==k){
        System.out.print("O");
      }
      else{
        System.out.print("*");
      }
    }
    System.out.print(reward);
    System.out.println("");
  }
  public void displayReport(){//reports game over, rounds, and final reward
    isGameOver();
    calcReward();
    System.out.println("rounds of play: "+round);
    System.out.println("final reward: "+reward); 
  } 
  public void playGame(){//initiates game play
    while(position<gameArray.length){
      spinAndMove();
      drawBoard();
      }   
    if(moves==gameArray.length){
      displayReport();
    }
  }
}

I've already begun to change the program so it doesn't use an Array anymore, because I think that's overcomplicating things a bit. But other than that, I don't know where I'm going wrong. It all compiles fine. Any help or advice would be completely appreciated, I'm still fairly new to programming. Thanks!

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
OneJumpedUp
Offline
Joined: 2012-04-05
Points: 0

See below, a thank you would be nice :-}

public class Opoly 
{
    private int boardSize;
    int[] gameArray;
    private int position = 0;
    private int reward;
    private int round = 0;

    public Opoly(int boardSizeI )
    {
        this.boardSize = boardSizeI;
        this.gameArray = new int[boardSize];
        this.position = 0;
        this.reward = 12;
    }

    private void calcReward()
    {
        if((( position % 5 ) == 0 ) && ( position <= gameArray.length - 1 ))  //<_-- Should be <=
        {
            if((( gameArray.length - 1 ) % 5 ) != 0 )
            {
                reward = reward * 2; //doubles reward if position is divisible by 5
                round++; //adds one round to the round counter
                drawBoard();
            }
        }
        else
        if( position == ( gameArray.length - 1 ))
        {
            reward = reward / 5; //divides reward by 5 if you land on the second to last spot
            position = 0; //bumps you back to position=0
            round++; //adds one round to the round counter
            drawBoard();
        }
        else
        if( position < gameArray.length )
        {
            round++;
            drawBoard();
        }
    }

    public void spin()
    {
        //generates random integer for spinner
        this.position += (int) (Math.random() * 5 + 1);
    }

    public void GameOver()
    {
        //checks if condition for ending game is met  <--- No it doesn't
        System.out.println("game over");
    }

    public void drawBoard()
    {
        if( position == 0 )
        {
            System.out.print( "Oops landed on the penultimate, Current Score:" );
        }
        else
        {
            //prints board with *'s and O's to show current position
            for( int k = 1; k <= gameArray.length; k++ ) // should start at 1 and end at len NOT +1 !!!
            {
                if( position == k )
                {
                    System.out.print("O");
                }
                else
                {
                    System.out.print("*");
                }
            }
        }
           
        System.out.println( " " + reward + " (" + position + ")" );
    }

    public void displayReport()
    {
        //reports game over, rounds, and final reward
        GameOver();
        calcReward();
        System.out.println( "rounds of play:" + round );
        System.out.println( "final reward: " + reward );
    }

    public void playGame()
    {
        //initiates game play
        while( position < gameArray.length )
        {
            spin();
            calcReward(); // <-- you forgot this !!!
            //drawBoard(); // doesn't belog here, see specs
        }

        displayReport();
    }
}