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:
how can i modify or improve my codes with some of ur codes to make the program work?
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:
I have tried to use some of ur codes to combine with mine, help!! <read more..>
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!
I created some classes for the players and gameRules, how do I correct these errors?
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 ...
=========================================
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 ...
================================================== ==
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:
This is the function to create or generate the random alphabet
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 :
Quote:
Letters for Player:
c, j, k, o, d, b, p, w, r, w
But i want to make the output look like this :
Quote:
Letters for Player: c, j, k, o, d, b, p, w, r, w
Removed the ln from system.out.println("..."); works!!!
Quote:
Remove the ln in the line 'System.out.println("Letters for Player: ");'
It works!! thanks Coyne20!!
Managed to figure out and did on my own ... how do i enable the [read on]
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!!