Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Need help creating a a simple 'credit' system to a game

  1. #1
    Junior Member
    Join Date
    Nov 2009
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Need help creating a a simple 'credit' system to a game

    Hi everyone.

    Basically, I am creating a game based on two dices, and a guess box. The user inputs the guess of what the dice outcome will be, and then clicks the roll button. This generates a random number in each dice. If the user is correct, a win message comes up. If wrong, a lose message comes up.

    I need to add a bit of code to the game, to allow the user to have an amount of 'credit' such as 10, and be able to place a bet of whatever amount they wish, within there credit range. If the user is correct at guessing the die outcome, this amount is 'added' to there 'credit'. If they are incorrect, it is subtracted. When the credit reaches 0, I need the game to end and reset.

    Can anyone help me out please? I have the code for my game up to now, Which I will paste here for anyone wanting to help to take a look at.

    First, main class:

    DiceRoller

    import java.applet.Applet;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.TextField;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    /**
     
    * @author snk2012
    *
    */
    public class DiceRoller extends Applet implements ActionListener{
     
    // We need 2 dice
    private Die d1,d2;
    // a button to roll the dice
    private Button btnRoll;
     
    private TextField txfGuess; //a field to enter a guess of the addition of the two dice values
    private int guess; // a field for the guess to be stored and compared with actual result
    private int total; // a total field to find the addition of the two dice values
    private boolean win; //a boolean value to display win/loose message.
     
    /**
    * Initialise the applet
    */
    public void init(){
    setSize(320,200); //sets the size of the window
    setBackground(Color.red); //sets the background color
    setLayout(null); /*gets rid of the standard layout precedure of placing from centre outwards. Allows
    for user to input coordinates for objects to be placed */
     
    // Create the 2 dice
    d1 = new Die(20,40); //creates a new dice, dice1, using the attributes from the dice class
    d2 = new Die(220,40); // does as before, creates a new dice
     
    // Create the button and add it to the GUI
    btnRoll = new Button("ROLL THE DICE"); //This adds a button named roll the dice to the program
    btnRoll.addActionListener(this);
    btnRoll.setBounds(10, 10, 100, 20); //sets its 'boundaries' or position on the screen.
    add(btnRoll); //adds the actual button, 'btnroll', to the program.
     
    txfGuess = new TextField(""); /* adds a textfield to enter the numerical guess. As its stored as
    a string it will need to be converted to a integer using the 'Integer parseInt' command. */
     
    txfGuess.setBounds(200,10,40,20); //sets the position of the Guess box.
    add(txfGuess); //adds the guess textbox to the program.
    }
     
    /**
    * Display the current values of the 2 dice
    */
    public void paint(Graphics g){ /* in the dice class the graphics g is used to set the dimensions of the dice, set the colour of the dice, set the fonts
    used on the numbering for the dice, draws the value from the mathrandom calculation to the dice, */
    d1.display(g); //using the paint method, dice1 & 2 are drawn to the applet window
    d2.display(g);
    //using the boolean command, we can set the win or loose to display based on weather the statement is true or false.
    if(win == true){ //display win if equal to true
    g.drawString("Win", 20,180);
    }
    else {
    g.drawString("Lose", 20,180); //otherwise, display lose.
     
    }
    }
     
    /**
    * When the button is clicked roll the dice.
    *
    */
    public void actionPerformed(ActionEvent ae) {
    d1.roll(); /*this is linked with the actionlistener. when the roll the dice button is clicked, is uses d1.roll() statement.
    This is listed in the dice class, as a mathrandom calculation. This means it will work out a random number as displayed it as the result for the dice roll.*/
    d2.roll();
    total = d1.getValue() + d2.getValue(); /*This is showing that the 'total' is created from the addition of the two dice roll values. using the getValue command. In the dice class the value is declared as 'Value'.
    then linked with a mathrandom calculation, to produce a random number on the dice when rolled.*/
    guess = Integer.parseInt(txfGuess.getText()); //This converts a string character '2' to an integer numerical value '2'.
    if(guess == total){
    System.out.println("WIN");
    win = true;
    // this is a boolean statement. If the guess input by the user is EQUAL to that of the total of the two dice, it is classed as TRUE, and WIN is displayed as a string on the screen
    }
    else {
    System.out.println("LOSE");
    win = false;
    // or else, (guess is not equal to total) the string Lose is displayed as win is returned false.
    }
    {}
    repaint();
    }
    }

    Next class, Die class:

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
     
    /**
    * Simple class to demonstrate a Die
    *
    * @author Peter lager
    *
    */
    public class Die {
     
    private int value;
    private int posX, posY;
    private Font font;
     
    /**
    * Create a new die at the given position and
    * set the initial value to 1
    *
    * @param posX
    * @param posY
    */
    public Die(int posX, int posY) {
    this.posX = posX;
    this.posY = posY;
    value = 1;
    font = new Font("Courier", Font.BOLD, 60);
    }
     
    /**
    * Set the top left position to display the die
    * @param posX
    * @param posY
    */
    public void setPos(int posX, int posY){
    this.posX = posX;
    this.posY = posY;
    }
     
    /**
    * @return the value
    */
    public int getValue() {
    return value;
    }
     
    /**
    * @param value the value to set
    */
    public void setValue(int value) {
    this.value = value;
    }
     
    /**
    * @param font the font to set
    */
    public void setFont(Font font) {
    this.font = font;
    }
     
    /**
    * Roll the dice to get a random value between 1& 6
    */
    public void roll(){
    value = (int)(Math.random()*4 + 1 + 1);
    }
     
    public void display(Graphics g){
    g.setColor(Color.yellow);
    g.fillRect(posX, posY, 80, 80);
    g.setColor(Color.black);
    g.drawRect(posX, posY, 80, 80);
    g.setFont(font);
    g.drawString(""+value, posX + 20, posY+60);
    }
    }

    Can anyone help me implement some code to allow me to use a gambling like function within this game?

    Thanks alot for any help, Greatly appreciated!

    G


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Need help creating a a simple 'credit' system to a game

    You can add two int variables, call them score and bet. You should probably add another JTextField (or maybe a JSpinner) to let users enter in the bet. You may wish to have a default bet that you set the JTextField value to every round, perhaps 1/2 the current score (you should evaluate this number. You can also check the entered value to make sure it is reasonable (> 0 and <= score).
    int bet = Integer.parseInt(/*GUI element for user entered bets*/.getText());
    if(guess == total){
    System.out.println("WIN");
    win = true;
    score += bet;
    // this is a boolean statement. If the guess input by the user is EQUAL to that of the total of the two dice, it is classed as TRUE, and WIN is displayed as a string on the screen
    }
    else {
    System.out.println("LOSE");
    win = false;
    score -= bet;
    if ( score <= 0 ){
        /**GAME ENDS - RESTART GAME*/
    }
    // or else, (guess is not equal to total) the string Lose is displayed as win is returned false.
    }

  3. The Following User Says Thank You to copeg For This Useful Post:

    Sneak (December 6th, 2009)

  4. #3
    Junior Member
    Join Date
    Nov 2009
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Need help creating a a simple 'credit' system to a game

    Thanks very much forthat help!

    I am still at a bit ofconfusion though. I added:
    private int bet;
    private int score;

    to the top of my code, just below my first lines of code.Then, i have added the bits of help you gave me to the bottom section ofmy code. All is well, but, i cant work out how to create the bet box so the user can enter a value to bet with, or how this would increase/decrease with a correct answer?. Up to now i have had help from my tutor, but the last bit i said id go away and try and work out myself, but as you see im really failing!

    Sorry to ask such questions like this, but it is helping me learn and i appreciate any help i can get. Im sure the penny will drop soon enough but for now its taking its toll on my mind!

  5. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Need help creating a a simple 'credit' system to a game

    I typed too fast for my own good: the above post should be JTextField (not JTextArea).

    You should probably also somehow have a display showing the total score, this could be a uneditable JTextField

    Suppose you now have these added to your GUI

    JTextField userBet = new JTextField();
    JTextField totalScore = new JTextField();//set uneditable using totalScore.setEditable(false);


    try{
    bet = Integer.toString(userBet.getText());/*You should validate the user entry somewhere above or below here!*/
    }catch (NumberFormatException nfe ){
    //let the user know its invalid
    }
    if(guess == total){
    System.out.println("WIN");
    win = true;
    score += bet;
    userBet.setText( Integer.toString(score/2) );//set the default bet, score/2 but this can be changed to whatever
    totalScore.setEditable(true);
    totalScore.setText( Integer.toString(score));
    totalScore.setEditble(false);
    // this is a boolean statement. If the guess input by the user is EQUAL to that of the total of the two dice, it is classed as TRUE, and WIN is displayed as a string on the screen
    }
    else {
    System.out.println("LOSE");
    win = false;
    score -= bet;
    if ( score <= 0 ){
        /**GAME ENDS - RESTART GAME*/
    }
    totalScore.setEditable(true);
    totalScore.setText( Integer.toString(score));
    totalScore.setEditble(false);
    // or else, (guess is not equal to total) the string Lose is displayed as win is returned false.
    }

    Hope this helps...

  6. The Following User Says Thank You to copeg For This Useful Post:

    Sneak (December 6th, 2009)

  7. #5
    Junior Member
    Join Date
    Nov 2009
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Need help creating a a simple 'credit' system to a game

    Heres what Ive got down up to now, can you give me an idea where im going wrong?

    Bah need a cup of tea here!! Anyone else for one? lol!

    import java.applet.Applet;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.TextField;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    /**
     
     * @author sneak *
     */
    public class DiceRoller extends Applet implements ActionListener{
     
     
    	// We need 2 dice
    	private Die d1,d2;
    	// a button to roll the dice
    	private Button btnRoll;
    	private int bet;
    	private int score;
     
     
    	private TextField txfGuess; //a field to enter a guess of the addition of the two dice values
    	private int guess; // a field for the guess to be stored and compared with actual result
    	private int total;  // a total field to find the addition of the two dice values
    	private boolean win; //a boolean value to display win/loose message.
    	private TextField userBet = new TextField();
    	TextField totalScore = new TextField();//set uneditable using totalScore.setEditable(false);
    	/**
    	 * Initialise the applet
    	 */
    	public void init(){
    		setSize(500,400); //sets the size of the window 
    		setBackground(Color.cyan); //sets the background color
    		setLayout(null); /*gets rid of the standard layout precedure of placing from centre outwards. Allows
    		for user to input coordinates for objects to be placed */
     
    		// Create the 2 dice
    		d1 = new Die(50,40); //creates a new dice, dice1, using the attributes from the dice class
    		d2 = new Die(220,40); // does as before, creates a new dice
     
    		// Create the button and add it to the GUI
    		btnRoll = new Button("ROLL THE DICE"); //This adds a button named roll the dice to the program
    		btnRoll.addActionListener(this);
    		btnRoll.setBounds(370, 50, 100, 20); //sets its 'boundaries' or position on the screen.
    		add(btnRoll); //adds the actual button, 'btnroll', to the program.
     
    		txfGuess = new TextField(""); /* adds a textfield to enter the numerical guess. As its stored as 
    		a string it will need to be converted to a integer using the 'Integer parseInt' command. */
     
    		txfGuess.setBounds(400,17,40,20); //sets the position of the Guess box.
    		add(txfGuess); //adds the guess textbox to the program.
    	}
     
    	/**
    	 * Display the current values of the 2 dice
    	 */
    	public void paint(Graphics g){ /* in the dice class the graphics g is used to set the dimensions of the dice, set the colour of the dice, set the fonts 
    	used on the numbering for the dice, draws the value from the mathrandom calculation to the dice, */
    		g.drawString("Please enter a sum of what you think the dice roller will achieve", 25,30);
    		d1.display(g); //using the paint method, dice1 & 2 are drawn to the applet window
    		d2.display(g); 
    		//using the boolean command, we can set the win or loose to display based on weather the statement is true or false. 
    		if(win == true){ //display win if equal to true
    			g.drawString("You Win!", 35,180);
    		}
    		else {
    			g.drawString("You Lose!", 25,180); //otherwise, display lose.
    		}
    	}
     
    	/**
    	 * When the button is clicked roll the dice.
    	 * 
    	 */
     
     
    	public void actionPerformed(ActionEvent ae) {
    		d1.roll(); /*this is linked with the actionlistener. when the roll the dice button is clicked, is uses d1.roll() statement. 
    		This is listed in the dice class, as a mathrandom calculation. This means it will work out a random number as displayed it as the result for the dice roll.*/
    		d2.roll();
    		total = d1.getValue() + d2.getValue(); /*This is showing that the 'total' is created from the addition of the two dice roll values. using the getValue command. In the dice class the value is declared as 'Value'. 
    		then linked with a mathrandom calculation, to produce a random number on the dice when rolled.*/
    		guess = Integer.parseInt(txfGuess.getText()); //This converts a string character '2' to an integer numerical value '2'.
     
    		try{
    			bet = Integer.toString(userBet.getText());/*You should validate the user entry somewhere above or below here!*/
    			}catch (NumberFormatException nfe ){
    			//let the user know its invalid
    			}
    		if(guess == total){ 
    			System.out.println("WIN");
    			win = true;
    			score +=bet;
    			userBet.setText( Integer.toString(score/2) );//set the default bet, score/2 but this can be changed to whatever
    			totalScore.setEditable(true);
    			totalScore.setText( Integer.toString(score));
    			totalScore.setEditble(false);
     
    			// this is a boolean statement. If the guess input by the user is EQUAL to that of the total of the two dice, it is classed as TRUE, and WIN is displayed as a string on the screen
    		}
    		else {
    			System.out.println("LOSE");
    			win = false;
    			score -=bet;
    			if (score <= 0 ){
    			}
    			totalScore.setEditable(true);
    			totalScore.setText( Integer.toString(score));
    			totalScore.setEditble(false);
    			// or else, (guess is not equal to total) the string Lose is displayed as win is returned false.
    			}
     
    			{}
    		repaint();
    		}

  8. #6
    Junior Member
    Join Date
    Nov 2009
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Need help creating a a simple 'credit' system to a game

    .............
    Last edited by Sneak; December 9th, 2009 at 05:08 PM. Reason: delete please

  9. #7
    Junior Member
    Join Date
    Nov 2009
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Need help creating a a simple 'credit' system to a game

    Thanks for all the help up to now, But is there anyone able to give me a little more help as to where I should be placing the pieces of code I have been given, within my Class.

    Would I need to draw a box for the score to be displayed in, and then link it with the code that is listening for the user to make a move?

    Thanks again people, ugh!

  10. #8
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Need help creating a a simple 'credit' system to a game

    I'd suggest to take a step back for a second, and draw out how you want your layout to be before assembling everything....for example:

    -------------------------------------------------------------------------------
    |                                                                            
    |   score      |    bet        |    guess   |    result    |     button   |     
    |                                                             
    --------------------------------------------------------------------------------
    where each 'box' represent some interface component that is displayed to the user and that the user can interact with. This layout is entirely dependent upon the behavior you want so the above is just an example. What information do you want the user to know? Next, define exactly what each interface component is (JTextField, JPanel, JButton, etc...) and for each define how to change them using the appropriate methods (paintComponent, setText, ec...). Finally organize these together by adding them into your applet, and let your actionPerformed method change each component using the appropriate calls. You are very close, but without knowing the layout and behavior its tough to design a GUI. I hope this helps some

  11. #9
    Junior Member
    Join Date
    Nov 2009
    Posts
    12
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Need help creating a a simple 'credit' system to a game

    I got it!! Kind of anyway. Thanks for all the help, was a real treat that!

    Heres the finished code anyway, works as i wanted it to. please, have a look and try and run it if you like.

    Here is the first main class, Diceroller

    import java.applet.Applet;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.TextField;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.JTextField;
     
    /**
     * Simple game to guess sum of 2 dice
     * @author Gary
     *
     */
    public class DiceRoller extends Applet implements ActionListener{
     
     
    	// We neeclass1 2 dice
    	private Die d1,d2;
    	// a button to roll the dice
    	private Button btnRoll, reset;
     
    	private TextField txfGuess; 
    	private int guess; 
    	private int total; 
    	private boolean win;
     
    	private int credits = 10;
     
    	/**
    	 * Initialise the applet
    	 */
    	public void init(){
    		setSize(600,400);  
    		setBackground(Color.cyan); 
    		setLayout(null); 
     
    		// Create the 2 dice
    		d1 = new Die(100,40); 
    		d2 = new Die(320,40); 
     
    		// Create the button and add it to the GUI
    		btnRoll = new Button("ROLL THE DICE"); 
    		btnRoll.addActionListener(this);
    		btnRoll.setBounds(470, 50, 100, 20); 
    		add(btnRoll); 
     
    		reset = new Button ("Reset");
    		reset.setBounds (470, 100, 100, 20);
    		add (reset);
    		reset.addActionListener (this);
     
     
    		txfGuess = new TextField(""); 
     
    		txfGuess.setBounds(500,17,40,20);
    		add(txfGuess);
    	}
     
    	/**
    	 * Display the current values of the 2 dice
    	 */
    	public void paint(Graphics g){ 
    		g.drawString("Please enter a sum, between 2 and 12, what you think the dice roller will achieve", 40,30);
    		d1.display(g);
    		d2.display(g); 
     
    		if(win){ 
    			g.drawString("You Win!", 25,180);
    		}
    		else {
    			g.drawString("You Lose!", 25,180);
    		}
     
    		g.drawString("Credits : " + credits, 25, 250);
    	}
     
    	/**
    	 * When the button is clicked roll the dice.
    	 * 
    	 */
    	public void actionPerformed(ActionEvent ae) {
    		if(ae.getSource() == btnRoll)
    		{
    			d1.roll();
    			d2.roll();
    			total = d1.getValue() + d2.getValue();
    			guess = Integer.parseInt(txfGuess.getText()); 
     
    			if(guess == total){ 
    				System.out.println("WIN");
    				win = true;
    				credits+=3;
    			}
    			else {
    				System.out.println("LOSE");
    				win = false;
    				credits--;
    				if(credits <=0)
    					btnRoll.setEnabled(false);
    			}
    		}
    		if(ae.getSource() == reset)
    		{
    			credits = 10;
    			btnRoll.setEnabled(true);
    		}
    		repaint();
    	}
    }


    Here is the second class

    Dice class

    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
     
    /**
     * Simple class to demonstrate a Die for use within the dice roller project.
     * 
     * @author Gary 
     *
     */
    public class Die {
     
    	private int value;
    	private int posX, posY;
    	private Font font;
     
    	/**
    	 * Create a new die at the given position and 
    	 * set the starting value to 1
    	 * 
    	 * @param posX
    	 * @param posY
    	 */
    	public Die(int posX, int posY) {
    		this.posX = posX;
    		this.posY = posY;
    		value = 1;
    		font = new Font("Courier", Font.BOLD, 60);
    	}
     
    	/**
    	 * Set the top left position to display the die
    	 * @param posX
    	 * @param posY
    	 */
    	public void setPos(int posX, int posY){
    		this.posX = posX;
    		this.posY = posY;		
    	}
     
    	/**
    	 * @return the value
    	 */
    	public int getValue() {
    		return value;
    	}
     
    	/**
    	 * @param value the value to set
    	 */
    	public void setValue(int value) {
    		this.value = value;
    	}
     
    	/**
    	 * @param font the font to set
    	 */
    	public void setFont(Font font) {
    		this.font = font;
    	}
     
    	/**
    	 * Roll the dice to get a random value between 1& 6
    	 */
    	public void roll(){
    		value = (int)(Math.random()*4 + 1 + 1);
    	}
    	/**
    	 * @param g, Graphics object, draws the die.
    	 */
    	public void display(Graphics g){
    		g.setColor(Color.yellow);
    		g.fillRect(posX, posY, 80, 80);
    		g.setColor(Color.black);
    		g.drawRect(posX, posY, 80, 80);
    		g.setFont(font);
    		g.drawString(""+value, posX + 20, posY+60);	
    	}
    }

Similar Threads

  1. Simple Game In Java (Head and Tails).
    By drkossa in forum Java Theory & Questions
    Replies: 5
    Last Post: November 28th, 2009, 11:40 AM
  2. Credit and thrift society application(urgent)
    By 5723 in forum Java Theory & Questions
    Replies: 1
    Last Post: November 3rd, 2009, 03:44 AM
  3. System.CurrentTimeMilliseconds
    By Dave in forum Java SE APIs
    Replies: 1
    Last Post: August 26th, 2009, 11:02 AM
  4. [SOLVED] Mobile operating system using Java technology
    By blackJava in forum Java ME (Mobile Edition)
    Replies: 3
    Last Post: April 16th, 2009, 02:44 PM
  5. Problem while programming a simple game of Car moving on a road
    By rojroj in forum Java Theory & Questions
    Replies: 3
    Last Post: April 2nd, 2009, 10:24 AM