Hangman game: stuck on randomly selecting players - java

For my school examn I have to make a console-application game of Hangman in Java, in which a player should be able to play against another player or a computer (2 players). A player should however also be able to play against a computer/AI. On top of that computers should be able to play against a computer as well.
Given the above, I have defined HashMaps with the player's names as String indexes and respective objects as values, like so:
private HashMap<String, PlayerHuman> humans = new HashMap<>(2);
private HashMap<String, PlayerComputer> computers = new HashMap<>(2);
Since both 2 players and 2 computers can play against each other, both HashMaps have a capacity of 2. Now when creating the players, there should either be real names entered (e.g. "John", "Mary") or a simple "C" if a player is computer-controlled. I then run a check on wether the input given was a "C" or not, resulting in creating the respective class for that player, like so:
Scanner scanner = new Scanner(System.in);
System.out.println("First create the players for the game!");
//
System.out.println("Type the name of player 1 (type C for computer): ");
String playerName1 = scanner.nextLine();
System.out.println("Type the nam of player 2 (type C for computer): ");
String playerName2 = scanner.nextLine();
if (playerName1.equals("C")) {
PlayerComputer player1 = new PlayerComputer();
player1.setPlayerName(playerName1);
if (playerName2.equals("C")) {
playerName1 = "C1";
playerName2 = "C2";
PlayerComputer player2 = new PlayerComputer();
player1.setPlayerName(playerName1);
player2.setPlayerName(playerName2);
this.computers.put(playerName2, player2);
} else {
PlayerHuman player2 = new PlayerHuman();
player2.setPlayerName(playerName2);
this.humans.put(playerName2, player2);
}
this.computers.put(playerName1, player1);
} else {
PlayerHuman player1 = new PlayerHuman();
player1.setPlayerName(playerName1);
if (playerName2.equals("C")) {
PlayerComputer player2 = new PlayerComputer();
player2.setPlayerName(playerName2);
this.computers.put(playerName2, player2);
} else {
PlayerHuman player2 = new PlayerHuman();
player2.setPlayerName(playerName2);
this.humans.put(playerName2, player2);
}
this.humans.put(playerName1, player1);
}
String startingPlayer = raffle(playerName1, playerName2);
There is definitely an easier way to do this, I have just run completely stuck and do not see a way out anymore. I then have to randomly select either of 2 players to be the first to play. I do this in the following method "raffle".
private String raffle(String nameOne, String nameTwo) {
Random random = new Random();
String raffledName = random.nextBoolean() ? nameOne : nameTwo;
System.out.println(raffledName + " may begin!");
return raffledName;
}
After this is where I run stuck. I'm getting the expected result from the "raffle" method; one of two given player's names, however I'm lost on how to make the code know which array to retrieve the returned player from, as a computer could either be named "C", or "C1" and "C2" when both players are computer-controlled, to know which computer represents which player. How do I make my code take this into consideration when retrieving the player's respective instance?
Any suggestions on creating the players are welcome too, since I feel the above written code is dirty and too procedural.
Thanks in advance!

I would like to suggest that you define a super class "Player" that your two player types derive from.
abstract class Player {
private String name;
public void setPlayerName(String name) {
this.name = name;
}
public String getPlayerName() { return name; }
abstract public boolean isCPU();
...
}
class PlayerHuman extends Player {
public boolean isCPU() { return false; }
...
}
class PlayerComputer extends Player {
public boolean isCPU() { return true; }
...
}
HashMap<String, Player> players = ...
Or, you can just use an array for players:
Player[] players = new Player[2];
You don't have to refer to player by name, then, and you can shuffle the array to decide who goes first.

Related

How do I search for null in this ArrayList and then replace it with another Object?

I have been writing code of a car parking structure for a bit now and i've gotten kinda stuck. So far I have an ArrayList that the user adds Vehicle properties to aswell as an ArrayList for a parking space with a "SpaceID" and the "Vehicle" from earlier.
So far I can make it so that the user adds the vehicle, and the vehicle gets added to a parking space, However I have made a temporary parking space with the index 0: and the element (vehicle) being null.
From here, I wanted to check the parking space ArrayList for "null" and then if it's found, replace null with the vehicle, However, I do not know how to go about implementing this. I will attach the current code i'm using, or at least a minimal version of it.
I have already tried using a Contains(null) method, but I can't seem to get that to work properly, I'm not sure if it even can work, but I have since then removed it from my code.
First of all, I have the function to create the vehicle and store it in an Array.
```
public void carInfo(Vehicle tempVehicle, parkingSpace vehicle) {
array = new MCP();
System.out.println("Please enter number plate: ");
input = new Scanner(System.in);
String plate = input.nextLine();
System.out.println("Please enter car make: ");
input = new Scanner(System.in);
String make = input.nextLine();
System.out.println("How would you best describe your Vehicle? ");
System.out.println("(Car, Small Van, Tall Van, Long Van, Coach,
Motorbike)");
type = new Scanner(System.in);
String type1 = input.nextLine();
if (type1.equalsIgnoreCase(vehicleType.CAR.toString())) {
tempVehicle.setPlate(plate);
tempVehicle.setCarMake(make);
tempVehicle.setVehicle(vehicleType.CAR);
inv.createInvoice();
tempVehicle.setInvoiceNumber(inv.invoiceNumber);
array.addStandard(tempVehicle);
array.parkVehicle(vehicle);
System.out.println(tempVehicle.toString());
System.out.println(vehicle.toString());
```
I also have my Arrays, which are on another class.
```
public MCP(){
vehicles = new ArrayList<>();
parkingSpaces = new ArrayList<>();
parkingSpaces.add(0, null);
parkingSpaces.add(1, null);
}
public void addStandard(Vehicle tempVehicle) {
vehicles.add(tempVehicle);
}
public void parkVehicle(parkingSpace vehicle) {
parkingSpaces.add(vehicle);
}
```
This is the way I tried to do it, but I couldn't figure this way out, so I stopped, i'm open to any other ways too.
// public void checkIfEmpty(parkingSpace vehicle){
// if(parkingSpaces.contains(null)){
// parkingSpaces.add(vehicle);
// }
// else{
// System.out.println("There is no room in this Zone");
// }
// }
I am also looking for a better way to populate parking spaces, but that's not the main concern, just something else just incase someone has any ideas
Thanks in Advance.
Since you are using an array list, when an item is deleted from it, there will be no empty element between two elements in it. When you delete an element, the elements shift. So in the case of this code, it checks if the number of elements in the array list is smaller than maximum number of cars
int maxSize = 10; //suppose that the maximum number of cars is 10
public void checkIfEmpty(parkingSpace vehicle){
if(parkingSpaces.size() < maxSize){
parkingSpaces.add(vehicle);
}
else{
System.out.println("There is no room in this Zone");
}
}
Try doing something like this:
public void checkIfEmpty(parkingSpace vehicle) {
boolean addedVehicle = false;
for (int i = 0; i < parkingSpaces.size(); i++){
if (parkingSpaces.get(i) == null) {
parkingSpaces.add(vehicle);
addedVehicle = true;
break;
}
}
if (!addedVehicle)
System.out.println("There is no room in this Zone");
}

Football Team: Objects and Classes

Before I post my question, I just need guidance on how to improve my java program, because I want to learn.
So, for my assignment I need to:
Create 3 classes, app, football player and football team.The application (app) will use the two other classes (football player and football team).
app will
create 11 football players (you can place them in an array or
ArrayList)
create a football team using the players above use the
football team instance (object) to display the information requested
in the lab
a football player class
has at least 5 attributes from
your choice a method that returns the complete info about the player
a football team class has
a name and a mascot
11 football players
any other attributes (optional)
a method that displays all the information about a team including:
name
mascot, and information on each player in the team
a method that display information about a specific player in the team using an input parameter such as the player position or player number for instance. For instance, from team A, displays information about the quarterback, or display information about player number 5.
I'm confused with my team class. I don't know how to add 11 players to the class and provide an input parameter for the player instance. I'm unsure about my app class because I don't know how to use the football team instance (object) to display the information requested in the lab.
Here is what I have so far
public class app {
public static void main(String[] args)
{
player pl1 = new player
("Christian","Campbell","Cornerback","Alabama","Central");
System.out.println(pl1.getInfo());
player pl2 = new player
("Marcus","Allen","Safety","Maryland","Dr. Henry A. Wise, Jr");
System.out.println(pl2.getInfo());
player pl3 = new player
("Tommy","Stevens","Quarterback","Indiana","Decatur Central");
System.out.println(pl3.getInfo());
player pl4 = new player
("Nyeem","Wartman-White", "Linebacker","Pennsylvania","Valley View");
System.out.println(pl4.getInfo());
player pl5 = new player
("George", "Foreman", "Defensive back","Georgia","Parkview");
System.out.println(pl5.getInfo());
player pl6 = new player
("Andre","Robinson","Right Tackle","Pennsylvania","Bishop McDevitt");
System.out.println(pl6.getInfo());
player pl7 = new player
("Malik","Golden","Safety","Connecticut","Chesire Academy");
System.out.println(pl7.getInfo());
player pl8 = new player
("Koa","Farmer","Safety","California","Notre Dame");
System.out.println(pl8.getInfo());
player pl9 = new player
("Jake","Zembiec","Quarterback","New York","Aquinas Institute");
System.out.println(pl9.getInfo());
player pl10 = new player
("Brandon","Polk","Wide Receiver","Virgina","Briar Woods");
System.out.println(pl10.getInfo());
player pl11 = new player
("Trace","McSorley","Quarterback","Virgina","Briar Woods");
System.out.println(pl11.getInfo());
}
}
public class player {
//---------Declaring attributes----
String firstName;
String lastName;
String position;
String State;
String Highschool;
player (String inf_firstName, String inf_lastName, String inf_position, String inf_State, String inf_Highschool)
{
firstName = inf_firstName;
lastName = inf_lastName;
position = inf_position;
State = inf_State;
Highschool = inf_Highschool;
}
String getInfo()
{
return "Name: "+firstName+ " "+lastName+", "+"position: " +position+ ", State: " +State+ ", High School: " +Highschool;
}
}
public class team {
String team = "Penn State";
String mascot = "Nittany Lions";
team(String inf_team, String inf_mascot)
{
team = inf_team;
mascot = inf_mascot;
}
team t1 = new team("Penn State", "Nittany Lions");
String getInfo()
{
return "Team Name: "+team+ "Team Mascot: "+mascot;
}
}
In your team class, below String team and String mascot, you need a player[] players array. And in your constructor, pass in an array that contains all your players.
2 options -
in your main method you create an array and add all of your players to it, and then pass it to your Team constructor, which sets an internal array to the value of the passed in array
or your Team object has a method called something like addPlayer(player) which adds the player to your Team's internal player array. Then you invoke the method after each player creation.
also you should uppercase your class names.. like Team, Player, etc.
I didn't write the getter or setter methods for the instance variables, because I think you can figure those out. But from your description of the Team class, it could look something like this.
public class Team {
//Instance variables and constants
private static final int MAX_PLAYERS = 11;
private Player[] players;
private String name;
private String mascot;
//Constructor
public Team(String name, String mascot) {
this.name = name;
this.mascot = mascot;
this.players = new Player[MAX_PLAYERS];
}
//Add players to the team
public void addPlayers(List<Player> p) {
//Ensures only 11 players are added to the team
for (int i = 0; i < MAX_PLAYERS; i++)
this.players[i] = p.get(i);
}
}
To match the implementation of this Team class, your App should be more of something like this, to be able to pass an already build List<Player> to the addPlayers method of the Team class...
public class app {
public static void main(String[] args) {
List<Player> players = new ArrayList<>();
players.add(new Player(/* Parameters for each player object */));
//Not writing this 11 times!
Team team = new Team("The Bulldogs", "Bull Dog");
team.addPlayers(players);
}
}
Since you have 11 players,It would better of creating an array of objects as they share similar properties. Like this:
Player[] players = new Player[11];
And then add their parameters and then pass it to the constructor class of app, which takes a list of a palyers.
I have updated your solution. This is how you can create your classes and method.
Please see inline comments for more information. Hope this helps.
public class App {
public static void main(String[] args) {
//creating a team
Team t1 = new Team("Penn State", "Nittany Lions");
Player pl1 = new Player("Christian", "Campbell", "Cornerback", "Alabama", "Central");
System.out.println(pl1.getInfo());
//for example, adding one player to the team t1 created above.
t1.addPlayer(pl1);
//you can repeat this step for adding all the teams
Player pl2 = new Player("Marcus", "Allen", "Safety", "Maryland", "Dr. Henry A. Wise, Jr");
System.out.println(pl2.getInfo());
Player pl3 = new Player("Tommy", "Stevens", "Quarterback", "Indiana", "Decatur Central");
System.out.println(pl3.getInfo());
Player pl4 = new Player("Nyeem", "Wartman-White", "Linebacker", "Pennsylvania", "Valley View");
System.out.println(pl4.getInfo());
Player pl5 = new Player("George", "Foreman", "Defensive back", "Georgia", "Parkview");
System.out.println(pl5.getInfo());
Player pl6 = new Player("Andre", "Robinson", "Right Tackle", "Pennsylvania", "Bishop McDevitt");
System.out.println(pl6.getInfo());
Player pl7 = new Player("Malik", "Golden", "Safety", "Connecticut", "Chesire Academy");
System.out.println(pl7.getInfo());
Player pl8 = new Player("Koa", "Farmer", "Safety", "California", "Notre Dame");
System.out.println(pl8.getInfo());
Player pl9 = new Player("Jake", "Zembiec", "Quarterback", "New York", "Aquinas Institute");
System.out.println(pl9.getInfo());
Player pl10 = new Player("Brandon", "Polk", "Wide Receiver", "Virgina", "Briar Woods");
System.out.println(pl10.getInfo());
Player pl11 = new Player("Trace", "McSorley", "Quarterback", "Virgina", "Briar Woods");
System.out.println(pl11.getInfo());
}
}
class Player {
// ---------Declaring attributes----
String firstName;
String lastName;
String position;
String State;
String Highschool;
Player(String inf_firstName, String inf_lastName, String inf_position, String inf_State, String inf_Highschool) {
firstName = inf_firstName;
lastName = inf_lastName;
position = inf_position;
State = inf_State;
Highschool = inf_Highschool;
}
String getInfo() {
return "Name: " + firstName + " " + lastName + ", " + "position: " + position + ", State: " + State
+ ", High School: " + Highschool;
}
}
class Team {
String team = "Penn State";
String mascot = "Nittany Lions";
Player[] playerArr = new Player[11]; //this is the main part. Array of players (11)
int playerCount = 0; //this will track the number of players being added to the team.
Team(String inf_team, String inf_mascot) {
team = inf_team;
mascot = inf_mascot;
}
public String getInfo() {
return "Team Name: " + team + "Team Mascot: " + mascot;
}
//Using this method you can add the players to the Player Array.
public void addPlayer(Player player) {
if (playerCount < 11) {
playerArr[playerCount] = player;
playerCount++;
}
}
//Using this method you find out a player with specific quality
//like in this case its position of the player.
//you can iterate through the Players Array and can find out the player
// And after that you can get the information of the player by your method
//getInfo
public String getPlayerInfo(String positionTemp) {
Player player = null;
for (int i = 0; i < playerArr.length; i++) {
if (playerArr[i].position.equals(positionTemp)) {
player = playerArr[i];
break;
}
}
return player.getInfo();
}
}

java println running function not returning function

FULL GITHUB FILES FOUND HERE
This is class Roulette.java
public static void main(String[] args) {
System.out.println("Welcome to roulette " + Casino.player());
}
This is class Casino.java
public static String player() {
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Please enter your name : ");
name = sc.nextLine();
return name;
}
When running Roulette.java it's not printing Casino.player() as a variable of your name, but running the function and asking for your name. I want to run Casino.java first,ask your name, then run roulette and welcome you with your name. NOT ASK YOUR NAME AGAIN.
Note: New to programming
The player() method in the Casino class prints out the message to input the users name. This will happen every time the method is called. To do what you want to do you need to create a conditional that checks if the player has already been set.
NOTE: This is not good practice or class design and in the future you should look into proper practice for class design and setting fields in a class. I would suggest posting this code on Code Review once you get it working to get a full answer on how this design can be improved.
Your Casino class should look something like this:
public class Casino {
private static String player = "";
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
this.player = sc.nextLine();;
}
return player;
}
}
Try something like this
String player = Casino.player();
System.out.println("Welcome to roulette " + player);

Count amount of members in a class

I'm making a small game in java for school purposes.
Now I want to count the number of players, code I have:
Player player1;
player1 = new Player();
player1.name = "Name1";
player1.score = 0;
player1.lives = 100.0;
Player player2;
player2 = new Player();
player2.name = "Name2";
player2.score = 0;
player2.lives = 50.0;
In the players use a static variable count that increments in the player constructor.
private static int playerCount = 0;
//constructor
Player(){
playerCount++;
}
Put all the players in a list:
List<Player> allPlayers = new ArrayList<Player>();
Player player;
player = new Player();
player.name = "Name1";
player.score = 0;
player.lives = 100.0;
allPlayers.add(player);
player = new Player();
player.name = "Name2";
player.score = 0;
player.lives = 50.0;
allPlayers.add(player);
allPlayers.size(); //Number of players
player = allPlayers.get(0); //Player 1
player = allPlayers.get(1); //Player 2
The best way to go about it is to use a container class, something that's a descendent of java.util.Collections.
When a player is added, he is added to the collection. When the player drops out of the game, he is removed from the collection. As a result, to determine the number of players at any moment in time, one only need to count the members of the collection (which is already implemented if you use a java.util pre-implemented Collection).
Even then, there are two techniques. One of these are flawed, and I'll demonstrate the flawed technique first (which is not much better than the static counter example others have provided).
private static HashSet<Player> players = new HashSet<Player>();
public Player() {
players.add(this);
}
public static int getPlayerCount() {
return players.size();
}
This leads to an interesting problem. The Player count will never go down, as even if Player classes are dereferenced, the counting collection holds a reference preventing garbage collection. This leads to the java version of a "garbage leak", but don't confuse it with the C/C++ "garbage leak" which is more nefarious.
The second technique arises from fixing the problems in the first. Basically, it doesn't rely upon construction to register, as destruction is an unsafe means of deregistering. Within a snippet of code you would have
HashSet<Player> players = new HashSet<Player>();
Player player = new Player("bob");
players.add(player);
... later on ...
players.remove(player);
or something equivalent. Basically the main idea is to have your current player list at the same level as the player creation. There are a million variants, depending on where the originating call comes from; however, the main idea is the same: explicit deregistering of the player, not directly tied to object life cycle.

Forgotten terminology regarding making objects from a class

It's several years since I actually took a programming class. I know I can do what I'm thinking of, but I cannot remember the terms, so I cannot look it up.
I'm writing a mock application for a HMI class. It orders pizzas. Right now, I use a separate class to pass the values of the pizza between activities. (Values like toppings, pizza size, etc). The class is named pizzaApplication.class, and an example value would be pizzaApplication.chkPepperoni = true;
The way it's set up now, I can only have one pizza. I'd like to be able to have the pizzaApplication class setup to have more than one pizza. The code (from memory) would then end up looking similar to
pizzaApplication.pizzaOne(chkPepperoni = true);
So, two questions:
What is the exact terminology for this
What is the best way to increment the different objects I'd make? Ie
pizzaApplication.pizzaOne(chkPepperoni = true);
or
pizzaApplication.pizza.1(chkPepperoni = true);
Edit:
For further clarification, I'm writing an Android app. I first ask them to make their selections for their pizza, and save them to a a different java file, named PizzaApplication.java Here are the first lines of code.
public class PizzaApplication extends Application {
private Order order = new Order();
//private final String[] toppings = new String[] { "Pepperoni", "Onion",
// "Sausage", "etc." };
public PizzaApplication() {
}
//Booleans for checking whether the individual pages have been completed.
Boolean vfTop = false;
Boolean vfAdd = false;
Boolean vfBill = false;
//Booleans for whether to add toppings
Boolean cheese = false;
Boolean italian = false;
Boolean pineapple = false;
Boolean ham = false;
Boolean pepperoni = false;
Boolean chicken = false;
//Globally accessible storage strings for various things
public String creditCard = "none";
public String crustType = "";
public String addressLine1 = "";
public String addressLine2 = "";
public String phoneNumber = "";
public String Toppings = "";
public Integer pizzaCount;
public String pizzaSize = "";
Now, here is some sample code from the Toppings class.
public class Toppings_Page extends Activity {
PizzaApplication pizzaApplication;
CheckBox Cheese, Ham, Italian, Pepperoni, Chicken, Pineapple;
Integer intpizzaCount;
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toppings__page);
pizzaApplication = (PizzaApplication) getApplication();
Cheese = (CheckBox)findViewById(R.id.chkCheese);
Italian = (CheckBox)findViewById(R.id.chkItalian);
Ham = (CheckBox)findViewById(R.id.chkHam);
Pepperoni = (CheckBox)findViewById(R.id.chkPepperoni);
Chicken = (CheckBox)findViewById(R.id.chkChicken);
Pineapple = (CheckBox)findViewById(R.id.chkPinapple);
and a little further down that class
public void onChecked(View view){
if (Cheese.isChecked()){pizzaApplication.cheese=true;}
else {pizzaApplication.cheese = false;}
if (Italian.isChecked()){pizzaApplication.italian=true;}
else {pizzaApplication.italian = false;}
if (Ham.isChecked()){pizzaApplication.ham=true;}
else {pizzaApplication.ham = false; }
if (Pepperoni.isChecked()){pizzaApplication.pepperoni=true;}
else {pizzaApplication.pepperoni = false;}
if (Chicken.isChecked()){pizzaApplication.chicken=true;}
else {pizzaApplication.chicken = false; }
You should have a seperate class named Pizza that represents a single pie. It should have no direct connection to your UI/Android code. You might use the builder pattern as shown in this example, which would allow you to create a pizza using something like this:
Pizza pizza = new Pizza.Builder(12).cheese().pepperoni().build();
At that point, working with multiple pizzas simply means using a List<Pizza> (or some other type of Collection):
List<Pizza> order = Arrays.asList(
new Pizza.Builder(9).cheese().ham().pineapple().build(),
new Pizza.Builder(12).cheese().sausage().build()
);

Categories