'Why does my program keep going to the player() method after p1Game() is finished?
Is there any way I'm able to format my code better too? I'm pretty new to programming and want to learn the best optimal way for this program to work. For example: If the word isn't contained in my Words.java then tell the user that the word they're trying to enter doesn't exist.
import java.util.Scanner;
public class WordleApplication
{
static String word = Words.words[(int)(Math.random() * Words.words.length)];
static Scanner s = new Scanner(System.in);
static String guess = "";
static int g = 6;
static String p1Name = "";
static String p2Name = "";
static int p1Score = 0;
static int p2Score = 0;
public static void main(String[] args)
{
Rules.rules();
// System.out.println("Please enter your name Player 1");
// Player p1 = new Player(s.nextLine(), 0);
// System.out.println(p1.getName());
}
public static void player(){
System.out.println("Player 1 Enter your name: ");
Player p1 = new Player(s.nextLine(), p1Score);
p1Name = p1.getName();
System.out.println();
System.out.println("Player 2 Enter your name: ");
Player p2 = new Player(s.nextLine(), p2Score);
p2Name = p2.getName();
p1Game();
p2Game();
}
public static void p1Game() {
System.out.println("Alright " + p1Name + " you're up!");
while (!guess.equals(word) && g > 0) {
System.out.println("\nGuesses Left: " + g);
guess = s.nextLine().toLowerCase();
if (guess.length() != 5) {
System.out.println("Must be 5 characters");
continue;
}
for (int i = 0; i < word.length(); i++) {
boolean didBreak = false;
for (int j = 0; j < word.length(); j++) {
if (guess.charAt(i) == word.charAt(i)) {
System.out.print("Y");
didBreak = true;
break;
}
if (guess.charAt(i) == word.charAt(j)) {
System.out.print("C");
didBreak = true;
break;
}
}
if (!didBreak) {
System.out.print("X");
}
}
System.out.println("\n" + word); //test
g--;
if(guess.equals(word)){
p1Score += 10;
System.out.println("Nicely done! You have " + p1Score + " points!");
p2Game();
}
if(g == 0){
System.out.println("\nThe word was: " + word);
p2Game();
}
}
}
public static void p2Game() {
System.out.println("Alright " + p2Name + " you're up!");
while (!guess.equals(word) && g > 0) {
System.out.println("\nGuesses Left: " + g);
guess = s.nextLine().toLowerCase();
if (guess.length() != 5) {
System.out.println("Must be 5 characters");
continue;
}
for (int i = 0; i < word.length(); i++) {
boolean didBreak = false;
for (int j = 0; j < word.length(); j++) {
if (guess.charAt(i) == word.charAt(i)) {
System.out.print("Y");
didBreak = true;
break;
}
if (guess.charAt(i) == word.charAt(j)) {
System.out.print("C");
didBreak = true;
break;
}
}
if (!didBreak) {
System.out.print("X");
}
}
System.out.println("\n" + word); //test
g--;
if(guess.equals(word)){
System.out.println("Nicely done!");
p2Score += 10;
}
if(g == 0){
System.out.println("\nThe word was: " + word);
}
}
}
public static void results(){
System.out.println("test");
}
}
Just the rules to describe what to the user.
import java.util.Scanner;
public class Rules {
public static void rules() {
Scanner s = new Scanner(System.in);
String enterkey;
System.out.println("Welcome to Wordle!");
System.out.println("Each player will be given 6 tries to guess a 5 letter word.");
System.out.println("If you can't guess the word in 6 tries. GAME OVER :(");
System.out.println("Do you have what it takes to guess the word?");
System.out.println("Go ahead and press y when you're ready!");
while(true){
enterkey = s.nextLine();
if(!enterkey.equals("y")){
System.out.println("Please press y to continue...");
continue;
}
if(enterkey.equals("y")){
WordleApplication.player();
}
}
}
}
public class Player {
protected String name;
protected int score;
public Player(String name, int score) {
this.name = name;
this.score = 10;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String toString() {
return name + ": " + score;
}
}
public class Words {
public static String[] words = {
"abuse",
"adult",
"agent",
"anger",
"apple",
"award",
"basis",
"beach",
"birth",
"block",
"blood",
"board",
"brain",
"bread",
"break",
"brown",
"buyer",
"cause",
"chain",
"chair",
"chest",
"chief",
"child",
"china",
"claim",
"class",
"clock",
"coach",
"coast",
"court",
"cover",
"cream",
"crime",
"cross",
"crowd",
"crown",
"cycle",
"dance",
"death",
"depth",
"doubt",
"draft",
"drama",
"dream",
"dress",
"drink",
"drive",
"earth",
"enemy",
"entry",
"error",
"event",
"faith",
"fault",
"field",
"fight",
"final",
"floor",
"focus",
"force",
"frame",
"frank",
"front",
"fruit",
"glass",
"grant",
"grass",
"green",
"group",
"guide",
"heart",
"henry",
"horse",
"hotel",
"house",
"image",
"index",
"input",
"issue",
"japan",
"jones",
"judge",
"knife",
"laura",
"layer",
"level",
"lewis",
"light",
"limit",
"lunch",
"major",
"march",
"match",
"metal",
"model",
"money",
"month",
"motor",
"mouth",
"music",
"night",
"noise",
"north",
"novel",
"nurse",
"offer",
"order",
"other",
"owner",
"panel",
"paper",
"party",
"peace",
"peter",
"phase",
"phone",
"piece",
"pilot",
"pitch",
"place",
"plane",
"plant",
"plate",
"point",
"pound",
"power",
"press",
"price",
"pride",
"prize",
"proof",
"queen",
"radio",
"range",
"ratio",
"reply",
"right",
"river",
"round",
"route",
"rugby",
"scale",
"scene",
"scope",
"score",
"sense",
"shape",
"share",
"sheep",
"sheet",
"shift",
"shirt",
"shock",
"sight",
"simon",
"skill",
"sleep",
"smile",
"smith",
"smoke",
"sound",
"south",
"space",
"speed",
"spite",
"sport",
"squad",
"staff",
"stage",
"start",
"state",
"steam",
"steel",
"stock",
"stone",
"store",
"study",
"stuff",
"style",
"sugar",
"table",
"taste",
"terry",
"theme",
"thing",
"title",
"total",
"touch",
"tower",
"track",
"trade",
"train",
"trend",
"trial",
"trust",
"truth",
"uncle",
"union",
"unity",
"value",
"video",
"visit",
"voice",
"waste",
"watch",
"water",
"while",
"white",
"whole",
"woman",
"world",
"youth",
"alcon",
"aught",
"hella",
"one’s",
"ought",
"thame",
"there",
"thine",
"thine",
"where",
"which",
"whose",
"whoso",
"yours",
"yours",
"admit",
"adopt",
"agree",
"allow",
"alter",
"apply",
"argue",
"arise",
"avoid",
"begin",
"blame",
"break",
"bring",
"build",
"burst",
"carry",
"catch",
"cause",
"check",
"claim",
"clean",
"clear",
"climb",
"close",
"count",
"cover",
"cross",
"dance",
"doubt",
"drink",
"drive",
"enjoy",
"enter",
"exist",
"fight",
"focus",
"force",
"guess",
"imply",
"issue",
"judge",
"laugh",
"learn",
"leave",
"let’s",
"limit",
"marry",
"match",
"occur",
"offer",
"order",
"phone",
"place",
"point",
"press",
"prove",
"raise",
"reach",
"refer",
"relax",
"serve",
"shall",
"share",
"shift",
"shoot",
"sleep",
"solve",
"sound",
"speak",
"spend",
"split",
"stand",
"start",
"state",
"stick",
"study",
"teach",
"thank",
"think",
"throw",
"touch",
"train",
"treat",
"trust",
"visit",
"voice",
"waste",
"watch",
"worry",
"would",
"write",
"above",
"acute",
"alive",
"alone",
"angry",
"aware",
"awful",
"basic",
"black",
"blind",
"brave",
"brief",
"broad",
"brown",
"cheap",
"chief",
"civil",
"clean",
"clear",
"close",
"crazy",
"daily",
"dirty",
"early",
"empty",
"equal",
"exact",
"extra",
"faint",
"false",
"fifth",
"final",
"first",
"fresh",
"front",
"funny",
"giant",
"grand",
"great",
"green",
"gross",
"happy",
"harsh",
"heavy",
"human",
"ideal",
"inner",
"joint",
"large",
"legal",
"level",
"light",
"local",
"loose",
"lucky",
"magic",
"major",
"minor",
"moral",
"naked",
"nasty",
"naval",
"other",
"outer",
"plain",
"prime",
"prior",
"proud",
"quick",
"quiet",
"rapid",
"ready",
"right",
"roman",
"rough",
"round",
"royal",
"rural",
"sharp",
"sheer",
"short",
"silly",
"sixth",
"small",
"smart",
"solid",
"sorry",
"spare",
"steep",
"still",
"super",
"sweet",
"thick",
"third",
"tight",
"total",
"tough",
"upper",
"upset",
"urban",
"usual",
"vague",
"valid",
"vital",
"white",
"whole",
"wrong",
"young",
"afore",
"after",
"bothe",
"other",
"since",
"slash",
"until",
"where",
"while",
"aback",
"abaft",
"aboon",
"about",
"above",
"accel",
"adown",
"afoot",
"afore",
"afoul",
"after",
"again",
"agape",
"agogo",
"agone",
"ahead",
"ahull",
"alife",
"alike",
"aline",
"aloft",
"alone",
"along",
"aloof",
"aloud",
"amiss",
"amply",
"amuck",
"apace",
"apart",
"aptly",
"arear",
"aside",
"askew",
"awful",
"badly",
"bally",
"below",
"canny",
"cheap",
"clean",
"clear",
"coyly",
"daily",
"dimly",
"dirty",
"ditto",
"drily",
"dryly",
"dully",
"early",
"extra",
"false",
"fatly",
"feyly",
"first",
"fitly",
"forte",
"forth",
"fresh",
"fully",
"funny",
"gaily",
"gayly",
"godly",
"great",
"haply",
"heavy",
"hella",
"hence",
"hotly",
"icily",
"infra",
"intl.",
"jildi",
"jolly",
"laxly",
"lento",
"light",
"lowly",
"madly",
"maybe",
"never",
"newly",
"nobly",
"oddly",
"often",
"other",
"ought",
"party",
"piano",
"plain",
"plonk",
"plumb",
"prior",
"queer",
"quick",
"quite",
"ramen",
"rapid",
"redly",
"right",
"rough",
"round",
"sadly",
"secus",
"selly",
"sharp",
"sheer",
"shily",
"short",
"shyly",
"silly",
"since",
"sleek",
"slyly",
"small",
"so-so",
"sound",
"spang",
"srsly",
"stark",
"still",
"stone",
"stour",
"super",
"tally",
"tanto",
"there",
"thick",
"tight",
"today",
"tomoz",
"truly",
"twice",
"under",
"utter",
"verry",
"wanly",
"wetly",
"where",
"wrong",
"wryly",
"abaft",
"aboon",
"about",
"above",
"adown",
"afore",
"after",
"along",
"aloof",
"among",
"below",
"circa",
"cross",
"furth",
"minus",
"neath",
"round",
"since",
"spite",
"under",
"until",
"aargh",
"adieu",
"adios",
"alack",
"aloha",
"avast",
"bakaw",
"basta",
"begad",
"bless",
"blige",
"brava",
"bravo",
"bring",
"chook",
"damme",
"dildo",
"ditto",
"frick",
"fudge",
"golly",
"gratz",
"hallo",
"hasta",
"havoc",
"hella",
"hello",
"howay",
"howdy",
"hullo",
"huzza",
"jesus",
"kapow",
"loose",
"lordy",
"marry",
"mercy",
"night",
"plonk",
"psych",
"quite",
"salve",
"skoal",
"sniff",
"sooey",
"there",
"thiam",
"thwap",
"tough",
"twirp",
"viola",
"vivat",
"wacko",
"wahey",
"whist",
"wilma",
"wirra",
"woops",
"wowie",
"yecch",
"yeeha",
"yeesh",
"yowch",
"zowie"
};
}
Solution 1:[1]
Well, it goes to p2Game
because you tell it to several times.
In player()
you call p1Game
then you call p2Game
that's cool, that'd work. When p1Game
finishes, it goes back to player
, and the next line is p2Game
which is probably what you want.
BUT, you call p2Game
a number of times within p1Game
which is probably what's causing the problem. The two times in p1Game
that you call p2Game
are probably unnecessary.
What happens right now, is player 1 guesses the correct word. You say "Nicely done!" then call p2Game
. Player 2 has a go, when that finishes, control goes back into p1Game
carries on, it rolls out of p1Game
eventually finishes, goes back to player
and p2Game
gets another call.
So, ditch those calls to p2Game
inside the p1Game
method.
In terms of organising your code better. Yes, there are a couple of things:
- avoid repeating code.
p1Game
andp2Game
look almost identical. If you find yourself writing code like that, you should think about a different way to go. There's a programming principle called "DRY - Don't Repeat Yourself" - avoid
static
when you're using an object oriented language like Java. Might as well be writing BASIC in 1986.
Normally the main
method is the only static
method.
public static void main()
{
WordleApplication wa = new WordleApplication();
wa.player();
}
You'd take static
off your player
method.
Change your p1Game
method so it accepts a Player
object as a parameter:
public static void OneGame(Player p) {
System.out.println("Alright " + p.getName() + " you're up!");
while (!guess.equals(word) && g > 0) {
System.out.println("\nGuesses Left: " + g);
...
See how it uses the parameter for the name in the "you're up" line? extend that through out the method.
So then, at the bottom of the player
method,
instead of
p1Game()
p2Game()
you can instead do
OneGame (p1);
OneGame (p2);
And that means you can delete p2Game
entirely. And that's good because less code is better code.
The static variables are also bad form. They're basically "Global Variables" in your app, and it's really hard to keep track of global variables once your app gets a lot bigger. It's better to minimise who can modify the variable. One example is g
. This is only need inside the game method. So if you move it to the start of the OneGame
method and set it to 6, you'll be good. As it is, it looks like both players get 6 guesses between them. If player 1 takes 5 guesses, Player 2 is only going to get 1 guess.
So
- move the variables that could be inside the 'game' method in there. That's
guess
andg
and probablyword
unless you do want both players guessing the same word? - move the variables that belong to the player into the player object. So instead of the
p1Name
variable refer togetName()
method of thep
parameter. Instead ofp1Score
usesetScore
andgetScore
It looks like you've put a chunk of effort into this. I think with a bit more it'll all just fall into place.
Good luck.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | GregHNZ |