Page 1 of 3 123 LastLast
Results 1 to 20 of 58
  1. #1
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Exclamation New to java and does not know how to write the code ...

    Hi, I'm new to Java and new to forums too as I'm currently learning object oriented programming java in school and the teacher is kinda "not helpful" as there's like 40 to 50 students in the class and yea ...

    I was given a project to do and it's to create a scrabble-like game, except it's not scrabble, more of a word game for 2 players.

    It's easy to create a menu such that the players can choose to play the game, view scores or exit the program by typing in "1" or "2" and so on. But after which, i got stuck ...

    My problem is that I do not know how to make the game in a way that 2 players can play them and the Player 1 goes first and if he/she type a valid word, it will move on to Player 2, if he or she type an invalid word, the program would prompt it to try again or PASS.

    I have attached a file ...

    :confused:

  2. #2
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    off the top of my head...
    Create a class called Player that has all the players info etc
    quick skeleton....
    Java Code:
    private boolean isPlayersTurn;
    private String player name;
    
    public Player(String name)
    {
       isPlayersTurn=false;
       // initialise other stuff you might create
    }
    
    public void setPlayersTurn()
    {
       isPlayersTurn=! isPlayersTurn;
    }
    
    public boolean isItPlayersTurn()
    {
       return isPlayersTurn;
    }
    inside main create 2 instances of Player e.g.

    Java Code:
    Player p1=new Player("his/her name");
    Player p2=new Player("his/her name");
    GameEngine ge=new GameEngine(p1,p2)
    Create a class called GameEngine or something like that will hold the rules of the game etc

    Java Code:
    // constructor
    private Player p1,p2;
    public GameEngine(Player p1,Player p2)
    {
      //initialise players
      this.p1=p1;
      this.p2=p2;
    
      // set one of the players turn to true to begin with
      p1.setPlayersTurn();
     
     // initialise other stuff as needed by the class
    }
    
    // player takes a turn take a turn
    public void takeAturn()
    {
       if(p1.isItPlayersTurn)
       {
           //do stuff with player 1
           p1.setPlayersTurn();
       }
       else{
           //do stuff with player 2
           p2.setPlayersTurn();
        }
    }
    this should give you an idea of what you can do....

  3. #3
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Default

    Thanks for the tip! I'll figure it out on how I can use this, thanks!!

    And by the way, how do I generate 13 random letters in an array(26 alphabets)instead of just one letter on its own? And how do i modify it so that there would be at least one vowel listed out instead of :

    Expected Results displayed/list out horizontally:
    Letters generated : b, r, t, p, k, l, w, m, n, s, m, y, d

    Without at least one vowel, no words could be formed ...

    This is the array i created with all 26 of the alphabets inside.
    String[] alphabetArray = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
    "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};

    String alphabetArray = alphabetArray.nextLine(12);

  4. #4
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    6

    Default

    Quote Originally Posted by poisson View Post
    And by the way, how do I generate 13 random letters in an array(26 alphabets)instead of just one letter on its own?

    can each letter be drawn only once or multiple times? in scrabble game each letter has its own frequency of occurence.
    Last edited by j2me64; 06-01-2010 at 11:58 AM.

  5. #5
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Default

    It's similar to a Scrabble game. The points given to each alphabet is exactly the same as scrabble.

    Lets say :
    Letters of Player A : a c n h e w s r y d f m n
    Enter your word (or enter ‘#’ to pass or ‘@’ to quit) : manners
    Total points for word : 9
    Total points for game : 9

    And for the next round after Player B gets a shot at it, Player A will get only 7 newly generated letters because the other letters not used in the first round will still be present until it's used up.

    Yes, so it's like a scrabble game.

    So that is kind of tough to write, since the first time it generates 13 random letters, and for the next round and so on, it will only generate the amount of letters that the player had used up. As from the example above, and since only 7 letters will used, so only 7 random letters will be generated.

  6. #6
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    6

    Default

    Quote Originally Posted by poisson View Post
    This is the array i created with all 26 of the alphabets inside.
    String[] alphabetArray = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
    "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};

    this frequency doesn't correspond to the letters in scrabble game. looking at this source you can see how the frequency of each letter

    English-language editions of Scrabble contain 100 letter tiles, in the following distribution is:

    * 2 blank tiles (scoring 0 points)
    * 1 point: E 12, A 9, I 9, O 8, N 6, R 6, T 6, L 4, S 4, U 4
    * 2 points: D 4, G 3
    * 3 points: B 2, C 2, M 2, P 2
    * 4 points: F 2, H 2, V 2, W 2, Y 2
    * 5 points: K 1
    * 8 points: J 1, X 1
    * 10 points: Q 1, Z 1

    This distribution of letters has not changed since Alfred Butts invented the game in 1938.

    so, a method to generate a list with 13 letters should use this frequency. i will try, to write a method for you.

  7. #7
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    6

    Default

    the TestClass will generate an array of chars containing your 13 letters

    Java Code:
    public class TestClass {
    	static char[] scrabbleArr = new char[100];
    	static int count = 0;
    
    	public static void addChar(char[] scrabble, char c, int times) {
    		for (int i = 0; i < times; i++) {
    			scrabble[count++] = c;
    		}
    	}
    
    	public static char[] getLetters() {
    		// 2 blank tiles (scoring 0 points)
    		// 1 point: E 12, A 9, I 9, O 8, N 6, R 6, T 6, L 4, S 4, U 4
    		// 2 points: D 4, G 3
    		// 3 points: B 2, C 2, M 2, P 2
    		// 4 points: F 2, H 2, V 2, W 2, Y 2
    		// 5 points: K 1
    		// 8 points: J 1, X 1
    		// 10 points: Q 1, Z 1
    
    		addChar(scrabbleArr, 'e', 12);
    		addChar(scrabbleArr, 'a', 9);
    		addChar(scrabbleArr, 'i', 9);
    		addChar(scrabbleArr, 'o', 8);
    		addChar(scrabbleArr, 'n', 6);
    		addChar(scrabbleArr, 'r', 6);
    		addChar(scrabbleArr, 't', 6);
    		addChar(scrabbleArr, 'l', 4);
    		addChar(scrabbleArr, 's', 4);
    		addChar(scrabbleArr, 'u', 4);
    		addChar(scrabbleArr, 'd', 4);
    		addChar(scrabbleArr, 'g', 3);
    		addChar(scrabbleArr, 'b', 2);
    		addChar(scrabbleArr, 'c', 2);
    		addChar(scrabbleArr, 'm', 2);
    		addChar(scrabbleArr, 'p', 2);
    		addChar(scrabbleArr, 'f', 2);
    		addChar(scrabbleArr, 'h', 2);
    		addChar(scrabbleArr, 'v', 2);
    		addChar(scrabbleArr, 'w', 2);
    		addChar(scrabbleArr, 'y', 2);
    		// _ means blank, so when printed is shown
    		addChar(scrabbleArr, '_', 2);
    		addChar(scrabbleArr, 'k', 1);
    		addChar(scrabbleArr, 'j', 1);
    		addChar(scrabbleArr, 'x', 1);
    		addChar(scrabbleArr, 'q', 1);
    		addChar(scrabbleArr, 'z', 1);
    
    		char[] s = new char[13];
    
    		int n = 0;
    		for (int i = 0; i < 13; i++) {
    			while (true) {
    				n = (int) (Math.random() * 100);
    				// drawn letter is set to 'N' so that
    				// this letter is drawn only once
    				if (scrabbleArr[n] != 'N') {
    					s[i] = scrabbleArr[n];
    					// set the letter to "" so that
    					scrabbleArr[n] = 'N';
    					break;
    				}
    			}
    		}
    		return s;
    	}
    
    	public static void main(String[] args) {
    
    		char[] myLetters = new char[13];
    		myLetters = getLetters();
    		System.out.print("Letters generated: ");
    		for (int i = 0; i < 13; i++) {
    			// if the letter is not the last one set a comma, else nothing
    			System.out.print(myLetters[i] + ((i < 12) ? ", " : ""));
    		}
    	}
    }

  8. #8
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Default

    So can you explain to me the codes, 'cause I do not really understand even though I have run the program, changed some numbers to see what I get and still get the same good results by your codes?

    ================================================== ==
    static int count = 0;
    Just to clarify, does it mean that it initializes the number or count value to be zero, like the starting value before the numbers are generated?

    ================================================== ==
    public static void addChar(char[] scrabble, char c, int times) {
    for (int i = 0; i < times; i++) {
    scrabble[count++] = c;
    And what does this mean? addChar(char[] scrabble, char c, int times) is a method and how does the rest functions?

    ================================================== ==
    char[] s = new char[13];

    int n = 0;
    for (int i = 0; i < 13; i++) {
    while (true) {
    n = (int) (Math.random() * 100);
    // drawn letter is set to 'N' so that
    // this letter is drawn only once
    if (scrabbleArr[n] != 'N') {
    s[i] = scrabbleArr[n];
    // set the letter to "" so that
    scrabbleArr[n] = 'N';
    break;
    }
    }
    }
    return s;
    }
    Can you explain this in layman terms on how it functions .. sorry ...

    ================================================== ==
    public static void main(String[] args) {

    char[] myLetters = new char[13];
    myLetters = getLetters();
    System.out.print("Letters generated: ");
    for (int i = 0; i < 13; i++) {
    // if the letter is not the last one set a comma, else nothing
    System.out.print(myLetters[i] + ((i < 12) ? ", " : ""));
    This is the part where the letters in the addChar array gets generated right or?

  9. #9
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Exclamation how can i modify or improve my codes with some of ur codes to make the program work?

    Java Code:
    import java.util.Scanner;
    import java.util.Random;
    public class FindYourLetters {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub		
    		int InputChoice = 0;
    		int gameChoiceInput = 0;
    		 //===========Menu=====================================================================+
    		int menuChoice = InputChoice;
    		Random r = new Random();
    		Scanner playerInput = new Scanner(System.in);
    		//=========creating a list=============================================================+
    		int[] arrayRdomAlph= new int[5];
    		//=========To indicate the initiate value==============================================+
    		int playerPlays;
    		//=======to indicate the initiate score================================================+
    		int score=0;
    			
    			//==================Alphabet letters array(26 alphabets)===========================+
    			String[] alparray = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
    					"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
    			//=================================================================================+
    			//======================Introduction panel=========================================+
    			System.out.println(" Welcome to the wordgame!!  ");
    			System.out.println("");
    			//=================================================================================+
    			
    			//=====================Instructions of the game====================================+
    			
    			System.out.println("*This game is for two players*");  //instructions
    			System.out.println("*Each player will go into the 1 of 5 rounds whereby each are to form a word with 10 random letters given to them*");
    			System.out.println("*If the first player types in an invalid word, he/she can try again or be given the option to pass*");
    			System.out.println("*If the first player decides to pass, the total score will be shown,*");
    			System.out.println("and it will be Player 2's turn*");
    			System.out.println("*If the Player 1 types in a valid word, the total score will be shown and it will be Player 2's turn, vice versa*");
    			System.out.println("*At the end of 5 rounds, the score will sum up and both players' scores will be shown.*");
    			System.out.println("*If player 1 score is higher than Player 2's, he will be declared winner*");
    			System.out.println("*However, if both players have the same score, it will be a draw.*");
    			//=================================================================================+
    			//Menu where user chooses whether to play the game, play another round or exit.====+
    			//=============Exception(Try and catch)to detect errors such as entering a ========+
    			//=============number which the array does not contain ============================+
    			while (InputChoice != 3) {
    				try {
    
    					System.out.println("Menu :");
    					System.out.println("\t1 - Play game! ^______^");
    					System.out.println("\t2 - Play again!^______^");
    					System.out.println("\t3 - Exit -_-");
    					//Pormpts user to enter their choice
    					System.out.println("Please enter your choice : ");
    					InputChoice = playerInput.nextInt();
    			  				
    			//==========It leads the user to whichever choice he/she chooses===================+
    							if (InputChoice == 1) {
    								// Choice 1 actions displays!
    								System.out.println("You have chosen to play the game!");
    							} else if (InputChoice == 2) {
    								// Choice 2 actions displays!
    								System.out.println("You have chosen to play again!");
    							} else if (InputChoice == 3) {
    								// Option 'Exit' actions here
    								System.out.println("You have chosen to exit.\nThe game will exit now.");
    							} else {
    								// Invalid option
    								System.out.println("**Invalid choice, please choose again.**");
    							}
    							//To stop=========================================================+
    							break;
    				} catch (Exception e) {
    						// catch \n of the scan error exception===============================+
    						String junk = playerInput.nextLine();
    						System.out.println(" ** ERROR!!! There's no such choice. ** ");
    						System.out.println(" ** Please try again!!! ** ");
    				}
    				//===================To get the words from the list, "words.txt"==============+
    				String[] wordList = FileUtil.readDictFromFile("words.txt");
    				for (int i = 0; i < wordList.length; i++){
    					System.out.println(wordList[i]);
    				//============================================================================+
    			}
    				
    				}
    
    						
    				}
    			}
    How can I modify my code or at least improve on it because I do not think my code is good as my codes only contain the menu part and does not even include the whole game infrastructure and the rest ... :(:confused:

    Thanks to those who are able to assist me!!!


    :confused::confused:

  10. #10
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Exclamation I have tried to use some of ur codes to combine with mine, help!! <read more..>

    Java Code:
    import java.util.Scanner;
    import java.util.Random;
    public class wordgame {
    	
    		static char[] lettersArray = new char[26];
    		//declare a variable called count and initializes count a value
    		static int count = 0;
    		
    		public static void addChar(char[] wordgame, char c, int times) {
    			for (int i = 0; i < times; i++) {
    				wordgame[count++] = c;
    			}
    		}
    
    		//==================Alphabet letters array(26 alphabets)===========================+
    		public static char[] getLetters() {
    			// letters worth 1 point: E, A, I, O, N, R, T, L, S, U
    			addChar(lettersArray, 'e', 1);
    			addChar(lettersArray, 'a', 1);
    			addChar(lettersArray, 'i', 1);
    			addChar(lettersArray, 'o', 1);
    			addChar(lettersArray, 'n', 1);
    			addChar(lettersArray, 'r', 1);
    			addChar(lettersArray, 't', 1);
    			addChar(lettersArray, 'l', 1);
    			addChar(lettersArray, 's', 1);
    			addChar(lettersArray, 'u', 1);
    			// letters worth 2 points: D, G
    			addChar(lettersArray, 'd', 1);
    			addChar(lettersArray, 'g', 1);
    			// letters worth 3 points: B, C, M, P
    			addChar(lettersArray, 'b', 1);
    			addChar(lettersArray, 'c', 1);
    			addChar(lettersArray, 'm', 1);
    			addChar(lettersArray, 'p', 1);
    			// letters worth 4 points: F, H, V, W, Y
    			addChar(lettersArray, 'f', 1);
    			addChar(lettersArray, 'h', 1);
    			addChar(lettersArray, 'v', 1);
    			addChar(lettersArray, 'w', 1);
    			addChar(lettersArray, 'y', 1);
    			// letters worth 5 points: K
    			addChar(lettersArray, 'k', 1);
    			// letters worth 8 points: J,X
    			addChar(lettersArray, 'j', 1);
    			addChar(lettersArray, 'x', 1);
    			// letters worth 10 points: Q,Z 
    			addChar(lettersArray, 'q', 1);
    			addChar(lettersArray, 'z', 1);
    
    			//=================================================================================+
    			int InputChoice = 0;
    			int gameChoiceInput = 0;
    			 //===========Menu=====================================================================+
    			int menuChoice = InputChoice;
    			Random x = new Random();
    			Scanner scan = new Scanner(System.in);
    			//=========creating a list=============================================================+
    			
    			//=========To indicate the initiate value==============================================+
    			int playerPlays;
    			//=======to indicate the initiate score================================================+
    			int score=0;
    			String playerName;
    			//======================Introduction panel=========================================+
    			System.out.println("Welcome to the WORDGAME!!! Enjoy!");
    			//=================================================================================+
    			
    			//=====================Instructions of the game====================================+
    			
    			System.out.println("*This game is for two players*");  //instructions
    			System.out.println("*Each player will go into the 1 of 5 rounds whereby each are to form a word with 10 random letters given to them*");
    			System.out.println("*If the first player types in an invalid word, he/she can try again or be given the option to pass*");
    			System.out.println("*If the first player decides to pass, the total score will be shown,*");
    			System.out.println("and it will be Player 2's turn*");
    			System.out.println("*If the Player 1 types in a valid word, the total score will be shown and it will be Player 2's turn, vice versa*");
    			System.out.println("*At the end of 5 rounds, the score will sum up and both players' scores will be shown.*");
    			System.out.println("*If player 1 score is higher than Player 2's, he will be declared winner*");
    			System.out.println("*However, if both players have the same score, it will be a draw.*");
    			//=================================================================================+
    			//System.out.println("Please enter your choice or option: ");
    			//InputChoice = scan.nextInt();
    			//Menu where user chooses whether to play the game, play another round or exit.====+
    			//=============Exception(Try and catch)to detect errors such as entering a ========+
    			//=============number which the array does not contain ============================+
    			while (InputChoice != 3) {
    				try {
    
    					System.out.println("Menu :");
    					System.out.println("\t1 - Play game! ^______^");
    					System.out.println("\t2 - View Scores^______^");
    					System.out.println("\t3 - Exit -_-");
    					//Pormpts user to enter their choice
    					System.out.println("Please enter your choice : ");
    					InputChoice = scan.nextInt();
    			  				
    			//==========It leads the user to whichever choice he/she chooses===================+
    							if (InputChoice == 1) {
    								// Choice 1 actions displays!
    								//enter name
    								System.out.println("Please enter your name: ");
    								playerName=scan.nextLine();
    								
    							} else if (InputChoice == 2) {
    								// Choice 2 actions displays!
    								System.out.println("Here are the scores:");
    							} else if (InputChoice == 3) {
    								// Option 'Exit' actions here
    								System.out.println("You have chosen to exit.\nThe game will exit now.");
    							} else {
    								// Invalid option
    								System.out.println("**Invalid choice, please choose again.**");
    							}
    							//To stop=========================================================+
    							break;
    				} catch (Exception e) {
    						// catch \n of the scan error exception===============================+
    						String junk = scan.nextLine();
    						System.out.println(" ** ERROR!!! There's no such choice. ** ");
    						System.out.println(" ** Please try again!!! ** ");
    				}
    				
    				char[] s = new char[10];
    
    				int n = 0;
    				for (int i = 0; i < 10; i++) {
    					while (true) {
    						n = (int) (Math.random() * 26);
    						// drawn letter is set to 'N' so that
    						// this letter is drawn only once
    						if (lettersArray[n] != 'N') {
    							s[i] = lettersArray[n];
    							// set the letter to "" so that
    							lettersArray[n] = 'N';
    							break;
    						}
    					}
    				}
    				return s;
    				}
    			return lettersArray;
    			}
    
    			private static void addChar(char[] letterArr2, char c) {
    				// TODO Auto-generated method stub
    				
    			}
    
    			public static void main(String[] args) {
    
    				char[] myLetters = new char[10];
    				myLetters = getLetters();
    				System.out.print("Letters for Player: ");
    				for (int i = 0; i < 10; i++) {
    					// if the letter is not the last one set a comma, else nothing
    					System.out.print(myLetters[i] + ((i < 9) ? ", " : ""));
    				}
    				
    				System.out.println("\nEnter your word:");
    			}
    				//===================To check for the words from "words.txt"==============+
    				String[] wordList = FileUtil.readDictFromFile("words.txt");{
    				for (int i = 0; i < wordList.length; i++){
    					System.out.println(wordList[i]);
    				//============================================================================+
    			}	
    				
    		}
    
    						
    	}
    I have tried to use your code, j2me64, to combine with my current codes.
    But i changed it to 10 random letters instead, and in the "addChar segment, i changed the tiles to value of 1 each" so that there would not be seen as fixed amount of tiles to calculate with.

    And the codes were kinda good, but there's still lots of errors such as when I want to enter a player's name before continuing or having two players instead of one ...

    I'm not good with 'constructors' and 'methods' as my school have not taught me that and I have tried searching it up on the internet, but the explanation and examples was a little too profound to absorb.

    So i posted a few replies yesterday as I needed to understand what you were doing, how the codes functions and as a beginner, when i look at codes, i do not know what I'm looking at, looking for ... etc

    So if anyone besides " j2me64 (who helped me out a lot)" who have any idea or able to explain or assist me in the errors and improvements to my codes, please shoot!

  11. #11
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    well poisson if you aint one bit interested in completing this project in time but really interseted in learning java that in time you leave your whole class behind than reply to this message. im only interested in dedicated learners so if you are dead interested in learning java reply nd i will show you how to solve a problem like this from beggining to end.

  12. #12
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Question I created some classes for the players and gameRules, how do I correct these errors?

    Java Code:
    public class Player 
    {
    	private boolean playersTurn;
    	private String playersName;
    	private Player player1;
    	private Player player2;
    	//Initialize the above by creating a constructor
    	//Constructor
    	public Player(String playersName)
    	{
    		this.playersTurn = playersTurn;
    		this.playersName = playersName;
    	}
    	public void setplayersTurn(boolean playersTurn)
    	{
    	this.playersTurn = !playersTurn;
    	}
    
    	public boolean playersTurn()
    	{
    	return playersTurn;
    	}
    }
    This is the class for Player in which I've created ...
    =========================================
    Java Code:
    //This is a class for GameRules which it holds the rules of the game
    public class GameRules
    {
    	public class Player {
    
    		public void setplayersTurn() {
    			
    		}
    
    	}
    
    	public String GameRules;
    	private Player player1;
    	private Player player2;
    	
    	//Constructor for GameRules to initialize the above
    	public GameRules(String GameRules)
    	{
    		this.GameRules = GameRules;
    		
    	public void rulesOfGame(String GameRules)
    	{
    	System.out.println("*Each player will go into the 1 of 5 rounds whereby each are to form a word with 10 random letters given to them\n");
    	System.out.println("*If the first player types in an invalid word, he/she can try again or be given the option to pass\n");
    	System.out.println("*If the first player decides to pass, the total score will be shown,\n");
    	System.out.println("and it will be Player 2's turn\n");
    	System.out.println("*If the Player 1 types in a valid word, the total score will be shown and it will be Player 2's turn, vice versa\n");
    	System.out.println("*At the end of 5 rounds, the score will sum up and both players' scores will be shown.\n");
    	System.out.println("*If player 1 score is higher than Player 2's, he will be declared winner\n");
    	System.out.println("*However, if both players have the same score, it will be a draw.\n");
    	}
    	public GameRules(Player player1)
    	}
    
    	public GameRules(Player player1, Player player2) 
    	{
    		public GameRules(Player player1,Player player2)
    		{
    		  //initialize players
    		  this.player1=player1;
    		  this.player2=player2;
    		  
    		//Set one of the players turn to "true" to begin with
    		  player1.setplayersTurn();
    
    		}
    		
    	}
    }
    This is a class for GameRules which it holds the rules of the game ...
    ================================================== ==
    Java Code:
    public class PlayerMain 
    {
    
    	public static void main(String[] args)
    	{
    		Player player1 = new Player("1");
    		Player player2 = new Player("2");
    		GameRules gr = new GameRules(Player player1,Player player2)
    	}
    
    }
    This is the object from the player class and the game rules class ... it's not done as both my classes for Player and GameRules seem to be having lots of errors or mistakes ...
    ================================================== ===
    I learned some stuffs on YouTube ... so understood more on constructors and methods ... but there's lots of errors as I'm pretty weak in constructors and methods ...

    Can anyone please help me, thanks !!

    :confused::confused::confused:
    Last edited by poisson; 06-05-2010 at 03:03 PM. Reason: forgotten an "!" symbol in the codes ..

  13. #13
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    can you post the rules of the Game in its entirety so I can guide you through the whole thing. The most important thing in any program is making everything into its own little workable unit. remember that.

  14. #14
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Question Is it like that?

    can you post the rules of the Game in its entirety
    As in displaying the rules of the game in this format or :
    - Each player will go into the 1 of 5 rounds whereby each are to form a word with 10 random letters given to them.

    - If the first player types in an invalid word, he/she can try again or be given the option to pass

    - If the first player decides to pass, the total score will be shown and it will be Player 2's turn.

    - If the Player 1 types in a valid word, the total score will be shown and it will be Player 2's turn, vice versa.

    - At the end of 5 rounds, the score will sum up and both players' scores will be shown

    - If player 1 score is higher than Player 2's, he will be declared winner.

    - However, if both players have the same score, it will be a draw.


    Java Code:
    public class GameRules
    {
    	public class Player {
    
    		public void setplayersTurn(boolean b) {
    		}
    
    	}
    
    	public String GameRules;
    	private Player player1;
    	private Player player2;
    	
    	//Constructor for GameRules to initialize the above
    	public GameRules(String GameRules)
    	{
    		this.GameRules = GameRules;
    		
    	public void rulesOfGame(String GameRules)
    	{
    	System.out.println("*Each player will go into the 1 of 5 rounds whereby each are to form a word with 10 random letters given to them\n");
    	System.out.println("*If the first player types in an invalid word, he/she can try again or be given the option to pass\n");
    	System.out.println("*If the first player decides to pass, the total score will be shown,\n");
    	System.out.println("and it will be Player 2's turn\n");
    	System.out.println("*If the Player 1 types in a valid word, the total score will be shown and it will be Player 2's turn, vice versa\n");
    	System.out.println("*At the end of 5 rounds, the score will sum up and both players' scores will be shown.\n");
    	System.out.println("*If player 1 score is higher than Player 2's, he will be declared winner\n");
    	System.out.println("*However, if both players have the same score, it will be a draw.\n");
    	}
    	public GameRules(Player player1)//it told me that's it's an invalid modifier .. so i'm not sure what've gone wrong ..
    	}
    
    	public GameRules(Player player1, Player player2) 
    	{
    		public GameRules(Player player1,Player player2)
    		{
    		  //initialize players
    		  this.player1 = player1;
    		  this.player2 = player2;
    		  
    		//Set one of the players turn to true to begin with
    		  player1.setplayersTurn(true);
    
    		  //set player2 to false .. i think ..
    		  player2.setplayersTurn(false);
    		}
    		public void nexTurn()
    		{
    		   if(p1.playersTurn)
    		   {
    		       //Player 1's turn 
    		       player1.setPlayersTurn();
    		   }
    		   else{
    			 //Player 2's turn 
    		       player2.setPlayersTurn();
    		    }
    		}
    	}
    }
    I have a week before the deadline ... so .. i sound kinda desperately lost .. dun mind me .. but ...
    I'm not sure whether it's complete or not.. i added a method which is : "public void nexTurn()" to see which player goes first.. provide more hints ...
    "Set one of the players turn to true to begin with" would allow the method i added to help in deciding the player's turn i think ...

    :(
    Last edited by poisson; 06-05-2010 at 02:43 PM.

  15. #15
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    alright poisson do not panic, and please do me a favour, do not worry about getting this in at the correct time, most of the class will get it in at the correct time but we are going to do something better you are going to understand every piece of code we write
    Each player will go into the 1 of 5 rounds whereby each are to form a word with 10 random letters given to them.

    If I understand you at the beggining of the game each player should have 10 random letters from the alphabet, and they use these letters to form a word??

    Right so lets start thinking, we first need a function to create the alphabet? how do you think we can achieve this? reply with your best code and I will guide you from here...Try your best dont be afraid to make mistakes I promise I will guide you at all stages if you make an effort at every stage..

    Make the best effort you can....right or wrong and we will go through your code until you understand...

  16. #16
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Default Ok

    Ok, that will take some time. be right back here later ..

  17. #17
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Exclamation This is the function to create or generate the random alphabet

    Java Code:
    //This is the function that I think would create the alphabets and generate 10 random letters for the player ... 
    
    import java.util.Scanner;
    import java.util.Random;
    public class createAlpha {
    
    	public static void main(String[] args) {
    //[=====================[INITIALISE RANDOM AND SCANNER]==========================================================]
    		Random randi = new Random();
    		Scanner scan = new Scanner(System.in);
    //[=====================[CHECKS LETTERS FOR ITS EXISTENCE IN THE "WORDS.TXT"]========================]	
    		String wordLog[] = FileUtil.readDictFromFile("words.txt");
    //[==================================================================================================]
    //[=====================[ARRAY FOR LETTERS AND ARRAY FOR ASSIGNED LETTER SCORE RESPECTIVELY]======================]
    		char [] alphaArray = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','e','i','o','u'};
    		int [] alphaScore = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
    		
    		//This is to assign the letters and place it within numbers of 10
    		char[] shuffleLetter = new char[10];
    		int[] blender = new int[10];
    //[=====================[RANDOM LETTERS!!!]==========================================================]
    			System.out.println("Letters for Player:");
    		//This would produce the ten random letters it's supposed to
    		//This is to initialise "i" and the condition part where i is less than the length of shuffleLetter and the iterator
    		for (int i = 0; i < shuffleLetter.length; i++) 
    			{
    			int n = randi.nextInt(blender.length); 
    			shuffleLetter[i] = alphaArray[n];
    			//This would print out the letters and I added the function 
    			//Whereby the comma would be printed out for every letter
    			//until the last letter where there would not be any comma
    			System.out.print(shuffleLetter[i] + ((i < 9) ? ", " : ""));
    			}
    		}
    	}
    
    //Though it prints out 10 random letters, it sometimes print out one vowels, two vowels or no vowels at all!!!
    //I kind of require at least 2 vowels to appear in the output
    And this is the output :
    Letters for Player:
    c, j, k, o, d, b, p, w, r, w
    But i want to make the output look like this :
    Letters for Player: c, j, k, o, d, b, p, w, r, w

  18. #18
    coyne20 is offline Member
    Join Date
    Feb 2009
    Posts
    20
    Rep Power
    0

    Default

    Remove the ln in the line 'System.out.println("Letters for Player: ");'

  19. #19
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Thumbs up Removed the ln from system.out.println("..."); works!!!

    Remove the ln in the line 'System.out.println("Letters for Player: ");'
    It works!! thanks Coyne20!!

  20. #20
    poisson is offline Member
    Join Date
    May 2010
    Location
    Singapore
    Posts
    31
    Rep Power
    0

    Question Managed to figure out and did on my own ... how do i enable the [read on]

    Java Code:
    import java.util.Scanner;
    import java.util.Random;
    public class thePrettyReckless {
    
    	public static void main(String[] args) {
    //[=====================[INTRODUCTION PANEL]========================================================]
    		System.out.println(" Welcome to the word game!!!");
    //[==================================================================================================]
    //[=====================[INITIALISE RANDOM]==========================================================]
    		Random randi = new Random();
    		Scanner scan = new Scanner(System.in);
    //[==================================================================================================]
    
    //[=====================[CHECKS LETTERS FOR ITS EXISTENCE IN THE "WORDS.TXT"]========================]	
    		String wordLog[] = FileUtil.readDictFromFile("words.txt");
    //[==================================================================================================]
    //[=====================[ARRAY FOR LETTERS, ARRAY FOR ASSIGNED LETTER SCORE AND VOWELS]==============]
    		char [] alphaArray = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    		int [] alphaScore = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
    		char[] Vowels = {'a', 'e', 'i', 'o', 'u'}; 
    		//This is to assign the letters and place it within numbers of 10 ===========================]
    		char[] shuffleLetter = new char[10];
    		int[] blender = new int[31];
    		//Initialise playerName input
    		String playerName = null;
    		//Initialise index/position
    		int index;
    //[=====================[PRINTS OUT "FINDYOURLETTERS" AND "LETTERS FOR PLAYER"]======================]
    			System.out.println("FindYourLetters");
    			//Player will be able to enter their name to be refer as in the game=====================]
    			System.out.print("Enter your name: ");
    			playerName = scan.nextLine();
    			//Prints out statement "Letters for{the name the player entered earlier}:"===============]
    			System.out.print("Letters for " + (playerName) +": ");
    //[==================================================================================================]
    //[=====================[POOL OF 10 RANDOM LETTERS!!!]===============================================]
    			//Ensure that there are at least 2 vowels in the generated words
    			for (int k = 0; k < 2; k++){
    			index = randi.nextInt(Vowels.length);
    			shuffleLetter[k] = Vowels[index];
    		}
    			
    		//This would produce the ten random letters it's supposed to
    		//This is to initialise "i" and i is less than the length of shuffleLetter and the iterator
    		for (int i = 0; i < shuffleLetter.length; i++) 
    			{
    			int xx = randi.nextInt(alphaArray.length); 
    			//Check whether the above code works 
    			if (shuffleLetter[i] == '\u0000')
    			{
    				shuffleLetter[i] = alphaArray[xx];
    			}
    			//This would print out the letters and I added the function 
    			//Whereby the comma would be printed out for every letter
    			//until the last letter where there would not be any comma
    			System.out.print(shuffleLetter[i]+ ((i < 9) ? ", " : " " ));
    			}
    //[==================================================================================================]
    //[=====================[PASS OR QUIT - PLAYER'S CHOICE]=============================================]
    		System.out.println("");
    		System.out.println("Enter your word (or ‘$’ to pass or ‘#’ to quit): ");
    //[==================================================================================================]
    		}
    	}
    Managed to figure out something after days (yayy!!)and gave my best shot so far ...

    and .. how do i enable the part where there are 2 players ==> who goes first, check whether word is invalid or valid before giving the score and next turn,

    furthermore when the player decides to pass or quit the game and also the total score for the words and total score for player in each round ... who won and maybe there's a draw
    So where do i improve , go next, or ... ?

    Thanks in advance!!
    Last edited by poisson; 06-09-2010 at 07:37 AM.

Page 1 of 3 123 LastLast

Similar Threads

  1. What are you using to write your code?
    By CaptainMorgan in forum New To Java
    Replies: 996
    Last Post: 09-27-2014, 02:32 AM
  2. How To Write Unmaintainable Code
    By tim in forum Forum Lobby
    Replies: 2
    Last Post: 02-07-2010, 09:19 PM
  3. Can I write code in 2 different files ?
    By fartek in forum New To Java
    Replies: 2
    Last Post: 02-14-2009, 03:48 PM
  4. Help me to write a secure code
    By Bhavis in forum Advanced Java
    Replies: 4
    Last Post: 01-21-2009, 06:06 AM
  5. How to write code comments
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 08:06 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •