How to validate the user input

  • (8 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »

113 Replies - 3766 Views - Last Post: 25 June 2017 - 03:50 AM Rate Topic: -----

#1 dag72  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 197
  • Joined: 02-March 11

How to validate the user input

Posted 10 June 2017 - 11:46 AM

Hey guys, I'm implementing a three piles nim game but struggling to understand the logic to determine the winner, ensure a valid user input is entered into the text field and prevent user from changing pile. The strategy should be something like so:
Compute the nimSum of the piles: int nimSum = p1^p2^p3
If nimSum is not zero, a smart strategy is possible
Compute the three numbers p1^nimSum,p2^nimSum,p3^nimSum
Find one of these that is numerically smaller than the original pile number. Pick this as your move. Use it to update p1,p2 or p3 as the case may be.
If the strategy is not possible (eg if nimSum was 0) do a random legal move like the computer player.

Please see the codes i'm using. I'm able to deduct from piles but not sure how to ensure the valid input is entered or prevent user from changing pile.

 
/*
 * This is the main class used for starting game.
 * It contains the main() method which is automatically executed 
 * whenever the program is called
 */

public class MainDrive {
    public static void main (String[] args) {
        GUIFrame startGameSession = new GUIFrame();
       // GetPlayer x = new GetPlayer();
       //System.out.println(x.GetPlayerInput());

    }
}



import javax.swing.JOptionPane;
import java.util.Random;
/*
 * This class allows Player to choose selection.
 *This is also the logic class that basically setup the engine of the game
 */
public class GameLogic {

    //defining three sets of piles
    private int pile_1,pile_2,pile_3;
    //defining and initializing Random stones generater
    private int stones = 100;
    //selecting human or computer
    private String playerSelection;
    //Temporary stored the selected player
    static private int selection;
    //Globally instantiating the GetPlayer object
    GetPlayer selectPlayer = new GetPlayer();
    /*
     * Player chooses selection.
     */
    public GameLogic() {

        selection = selectPlayer. GetPlayerInput();

        if(selection == 0 ){
            JOptionPane.showMessageDialog(null, "Human Turn");
            playerSelection = "Human";

        }
        else{
            JOptionPane.showMessageDialog(null, "Computer Turn");
            playerSelection = "Computer";

        }

    }

    public String getPlayerSelection(){
        return playerSelection;
    }

    //Method to generate the Random piles of three stones
    public int generatePiles(){
        Random randPile = new Random();
        int pile = randPile.nextInt(stones)+1;
        return pile;

    }

    //this method return the first pile to the GUI
    public int generateFirstPile(){
        pile_1 = generatePiles();
        return pile_1;
    }
    //this method return the second pile to the GUI
    public int generateSecondPile(){
        pile_2 = generatePiles();
        return pile_2;
    }
    //this method return the third pile to the GUI
    public int generateThirdPile(){
        pile_3 = generatePiles();
        return pile_3;
    }

    public int getPile1(){
        return pile_1;
    }

    public int getPile2(){
        return pile_2;
    }

    public int getPile3(){
        return pile_3;
    }

    public void move(int firstPileDeduction) {

        while (firstPileDeduction < 0
        || firstPileDeduction > (100)) {
            JOptionPane.showMessageDialog(null,"Illegal move! - please try again!");

        }
        pile_1 = pile_1 - firstPileDeduction;

    }

    public void secondPileMove(int secondPileDeduction) {

        while (secondPileDeduction < 1
        || secondPileDeduction > (100)) {
            JOptionPane.showMessageDialog(null,"Illegal move! - please try again!");

        }
        pile_2 = pile_2 - secondPileDeduction;

    }

    public void thirdPileMove(int thirdPileDeduction) {

        while (thirdPileDeduction < 1
        || thirdPileDeduction > (100)) {
            JOptionPane.showMessageDialog(null,"Illegal move! - please try again!");

        }
        pile_3 = pile_3 - thirdPileDeduction;

    }

    //Determine the winner of the game
    public int printWinner(){
        boolean gameComplete = true;
        int winner = -1;

        //Checking to see if the piles are empty
        if((pile_1 == 0)&&(pile_2 == 0)&&(pile_3 == 0))

            winner = GameLogic.selection;
        gameComplete = false;

        if(gameComplete == false && winner == 0)
        {
            //Display the result of human palyer winning
            System.out.println(selection + " Human wins!");
            winner = 0;

        }

        if(gameComplete == false && winner == 1)
        {
            //Display the result of computer winning
            System.out.println(selection + " Computer wins!");
            winner = 0;

        }
        return winner;
    }

}



import java.awt.*;
import javax.swing.*;
import javax.swing.JLabel;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
 * Write a description of class TestFrame1 here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class GUIFrame extends JFrame implements ActionListener
{
    //creating JButton1
    private JButton quit;
    //creating JButton2
    private JButton newGame;
    //first pile lable
    private JLabel pile_1 = new JLabel("pile 1: ") ;
    //first text entry
    private JTextField firstPile = new JTextField(5);
    //second pile label
    private JLabel pile_2 = new JLabel("pile 2: ") ;
    //second pile entry
    private JTextField secondPile = new JTextField(5);
    //third pile label
    private JLabel pile_3 = new JLabel("pile 3: ");
    //third pile entry
    private JTextField thirdPile = new JTextField(5);
    //Game header
    private JLabel headerLabel = new JLabel("Game in progress!!");
    //creating text area
    private JTextArea textArea = new JTextArea(17,30);
    GameLogic gameLogic = new GameLogic();  

    private String whoseMove = "Initial State";

    int pile1, pile2, pile3;
    //constructor
    public GUIFrame(){
        super("Multi - Nim Game");

        mainFrame();

    }

    private void mainFrame(){
        // setting the FlowLayout
        setLayout(new FlowLayout());

        //adding text labels
        add(pile_1);
        add(pile_2);
        add(pile_3);
        //adding text fields
        add(firstPile);
        add(secondPile);
        add(thirdPile);
        //adding the header label
        add(headerLabel);
        //adding the text area
        add(textArea);
        //setting up the size 
        setSize(400,400);
        //setting the visibility to true
        setVisible(true);
        //this means you cannot resize the gui
        setResizable(false);

        textArea.setEditable(false);
        //setting line wrap
        textArea.setLineWrap(true);
        //setting wrap style
        textArea.setWrapStyleWord(true);
        //enable the frame to be closed upon clicking close
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //getting the background colour
        getContentPane().setBackground(Color. green);       

        firstPile.addActionListener(this);//adding the firstPile to the addActionListener method
        secondPile.addActionListener(this);//adding the secondPile to the addActionListener method
        thirdPile.addActionListener(this);//adding the thirdPile to the addActionListener method

        quit = new JButton("Quit");
        add(quit);
        quit.addActionListener(this);
        newGame = new JButton("New Game");
        add(newGame);
        newGame.addActionListener(this);

        //making a connection to the GameLogic class, by referrence

        pile1 = gameLogic.generateFirstPile();
        firstPile.setText(pile1 +"");//calling the generateFirstPile() method
        pile2 = gameLogic.generateSecondPile();
        secondPile.setText(pile2+"");//calling the generateSecondPile() method
        pile3 = gameLogic.generateThirdPile();
        thirdPile.setText(pile3+"");//calling the generateThirdPile() method
        updateStage();
    } 

    public void updateStage(){
        textArea.setText(whoseMove + ":\t " + pile1+" "+pile2+" "+pile3);
        whoseMove = gameLogic.getPlayerSelection();
    }

    @Override
    public void actionPerformed(ActionEvent evt)
    {       
        if (evt.getActionCommand().equals("Quit")){
            System.exit(0);
        }

        if(pile1 != Integer.parseInt(firstPile.getText())){
            pile1 = pile1 - Integer.parseInt(firstPile.getText());
        }
        if(pile2 != Integer.parseInt(secondPile.getText())){
            pile2 = pile2 - Integer.parseInt(secondPile.getText());
        }
        if(pile3 != Integer.parseInt(thirdPile.getText())){
            pile3 = pile3 - Integer.parseInt(thirdPile.getText());
        }
        updateStage();

    }

}




import javax.swing.JOptionPane;
/**
 * Write a description of class GetPlayer here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class GetPlayer
{
    public  int GetPlayerInput(){
        Object[] options = {"Human",
                "Computer"};
        int n = JOptionPane.showOptionDialog(null,
                "Select human or computer player",
                "Player selection",
                JOptionPane.YES_NO_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                options,
                options[1]);
                return n;
    }
}



import javax.swing.JOptionPane;
import java.util.Random;
class NaiveComputerPlayer extends ComputerPlayer {

    // use superclass constructor
    public NaiveComputerPlayer(int player, String playerRace) { 
        super(player, playerRace); 
    }

    /*
     * Computer player randomly takes a legal amount of stones.
     */
    public int move(int firstPileDeduction) {
        Random myRandom = new Random();
        int nPile = myRandom.nextInt(firstPileDeduction / 2) + 1;
        try {
            Thread.sleep(2000L); // pause so player can see what computer does
        }
        catch (Exception e) {}
        JOptionPane.showMessageDialog(null,this + " takes " + nPile + " stone(s).");
        return nPile;
    }
}



import javax.swing.JOptionPane;
/*
 * SmartComputerPlayer is subclass of ComputerPlayer class.
 */
class SmartComputerPlayer extends ComputerPlayer {

    // use superclass constructor
    public SmartComputerPlayer(int playerN, String playerRace) { 
        super(playerN, playerRace); 
    }

    /*
     * Player is forced to take a legal amount of stones.
     */
    public int move(int firstPileDeduction) {

        while (firstPileDeduction < 1
        || firstPileDeduction > (2)) {
            JOptionPane.showMessageDialog(null,"Illegal move! - please try again!");

        }

        return firstPileDeduction;
    }
}



Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: How to validate the user input

#2 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 633
  • View blog
  • Posts: 4,773
  • Joined: 25-December 13

Re: How to validate the user input

Posted 10 June 2017 - 12:53 PM

On the coderanch site I suggested:

Quote

One approach would be to have a separate listener for each text field.
Update the pile from the field associated with the listener and leave the piles for other fields unchanged.
Before using the value from the text field, make sure it has a valid value: less than current pile and >= 0.


Did you try that?
Was This Post Helpful? 0
  • +
  • -

#3 dag72  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 197
  • Joined: 02-March 11

Re: How to validate the user input

Posted 10 June 2017 - 01:10 PM

I haven't tried that because i feel its a little out of y depth at the moment and i'm just looking for some simpiler advice, i don't have much time on this project
Was This Post Helpful? 0
  • +
  • -

#4 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 633
  • View blog
  • Posts: 4,773
  • Joined: 25-December 13

Re: How to validate the user input

Posted 10 June 2017 - 01:18 PM

Sorry, there aren't always simpler solutions.
I'd start with Carey Brown's suggestion and use arrays for the text fields and piles.
Was This Post Helpful? 0
  • +
  • -

#5 dag72  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 197
  • Joined: 02-March 11

Re: How to validate the user input

Posted 10 June 2017 - 01:36 PM

Yes, the array would prevent the use of discrete variables but this is not the particular issue that i'm having right now

This post has been edited by dag72: 10 June 2017 - 01:38 PM

Was This Post Helpful? 0
  • +
  • -

#6 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 633
  • View blog
  • Posts: 4,773
  • Joined: 25-December 13

Re: How to validate the user input

Posted 10 June 2017 - 01:46 PM

It will simplify the code and remove some of the problems.
Was This Post Helpful? 1
  • +
  • -

#7 dag72  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 197
  • Joined: 02-March 11

Re: How to validate the user input

Posted 10 June 2017 - 02:03 PM

yes, i would simplify the code but not necessarily resolve my problem
Was This Post Helpful? 0
  • +
  • -

#8 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 633
  • View blog
  • Posts: 4,773
  • Joined: 25-December 13

Re: How to validate the user input

Posted 10 June 2017 - 02:10 PM

Quote

would simplify the code but not necessarily resolve my problem

Whatever you say. I'm sure you know best.

What about separate listeners for each of the text fields? What is your opinion on that?
Was This Post Helpful? 1
  • +
  • -

#9 dag72  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 197
  • Joined: 02-March 11

Re: How to validate the user input

Posted 10 June 2017 - 02:27 PM

I don't believe i know best otherwise i wouldn't have posted stuff here, would I? I kinda know in my head what i need to achieve but just struggling to implement it. I believe the separate listeners makes sense but i spent over a week trying to figure out gui and now i only have a few days for this project so i just need a much simplier guidance to follow.

This post has been edited by dag72: 10 June 2017 - 02:28 PM

Was This Post Helpful? 0
  • +
  • -

#10 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 633
  • View blog
  • Posts: 4,773
  • Joined: 25-December 13

Re: How to validate the user input

Posted 10 June 2017 - 02:31 PM

Sorry, I don't have another simpler way. The resulting code with the arrays and the separate listeners will be simpler. This is what I have in the actionPerformed method that uses arrays and separte listeners:
       public void actionPerformed(ActionEvent evt) 
       {
           int amtToDeduct = Integer.parseInt(pileTF[idx].getText());
           if(amtToDeduct < 0 || amtToDeduct > piles[idx]) {
              textArea.append("invalid amount "+amtToDeduct+ " for pile "+(idx+1)+"\n");
              return;
           }
           piles[idx] -= amtToDeduct;  // reduce the pile by user given amount
           updateStage();
        }



This post has been edited by NormR: 10 June 2017 - 02:35 PM

Was This Post Helpful? 1
  • +
  • -

#11 dag72  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 197
  • Joined: 02-March 11

Re: How to validate the user input

Posted 10 June 2017 - 02:55 PM

Thank you, isn't this declaration correct? I'm getting error ']' expected

 
private int[] piles = new int[3];
piles[0]=  1;
piles[1] = 2;
piles[2] = 3;    



Was This Post Helpful? 0
  • +
  • -

#12 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 633
  • View blog
  • Posts: 4,773
  • Joined: 25-December 13

Re: How to validate the user input

Posted 10 June 2017 - 03:02 PM

Statements 2-4 must be in a method.
You can define an array an give it values in a single statement:
      int[] anA = {11,21,31};


Was This Post Helpful? 0
  • +
  • -

#13 dag72  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 197
  • Joined: 02-March 11

Re: How to validate the user input

Posted 10 June 2017 - 03:37 PM

Sorry still struggling somewhat, could you please explain this line of code? Thanks

int amtToDeduct = Integer.parseInt(pileTF[idx].getText());

Was This Post Helpful? 0
  • +
  • -

#14 NormR  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 633
  • View blog
  • Posts: 4,773
  • Joined: 25-December 13

Re: How to validate the user input

Posted 10 June 2017 - 03:41 PM

int amtToDeduct = Integer.parseInt(pileTF[idx].getText());
// broken down
pileTF[idx].getText();  // call the getText() method for the JTextField  in the array pileTF at slot idx
Integer.parseInt(...  // convert the String returned by getText to an int
int amtToDeduct = ...  // assign the int value from parseInt to an int variable

    JTextField[] pileTF = {firstPile, secondPile, thirdPile};    // array of text fields


This post has been edited by NormR: 10 June 2017 - 03:42 PM

Was This Post Helpful? 0
  • +
  • -

#15 dag72  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 197
  • Joined: 02-March 11

Re: How to validate the user input

Posted 10 June 2017 - 03:48 PM

Ahh, thanks and is 'idx' the array element say 0?
Was This Post Helpful? 0
  • +
  • -

  • (8 Pages)
  • +
  • 1
  • 2
  • 3
  • Last »