My assignment is to try and create a card game and I'm stuck at the point where I am trying to display the cards in a jframe. I have a Displayable instance and a Displayble hand deck and card which implements this. I'm stuck at what to put inside the display method that they have to override and also what I should put in the jframe class/jpanel. Any help is much appreciated thanks a lot.
public interface Displayable {
public void display(Graphics g, int x, int y);
}
Example of one of the displayable classes.
public class DisplayableCard extends Card implements Displayable {
Graphics g;
String filename = "\\images\\classic-cards\\7.png";
Image image = new ImageIcon(getClass().getResource(filename)).getImage();
#Override
public void display(Graphics G, int x,int y)
{
}
}
We got given this code to use and told to- "Test your new classes by creating a simple subclass of JFrame, which contains an instance of CardGamePanel. Simply construct and add an appropriate Displayable object to the CardGamePanel instance to test each Displayable"
public class CardGamePanel extends JPanel{
private Displayable theItem;
private int x, y;
#Override
public void paint(Graphics g) {
if (theItem != null)
{
theItem.display(g, x, y);
}
}
public void setItem(Displayable item, int x, int y) {
theItem = item;
this.x = x;
this.y = x;
}
}
So I tried this:
public class simple extends JFrame
{
CardGamePanel c = new CardGamePanel();
Displayable d;
DisplayableDeck d1 = new DisplayableDeck();
}
public class mainclass {
public static void main(String args[])
{
DisplayableDeck d1 = new DisplayableDeck();
simple s1 = new simple();
s1.c.setItem(d1, 50, 50); // like this?
}
}
Any help much appreciated :)
You can try this program
public class HighLow {
public static void main(String[] args) {
System.out.println("This program lets you play the simple card game,");
System.out.println("HighLow. A card is dealt from a deck of cards.");
System.out.println("You have to predict whether the next card will be");
System.out.println("higher or lower. Your score in the game is the");
System.out.println("number of correct predictions you make before");
System.out.println("you guess wrong.");
System.out.println();
int gamesPlayed = 0; // Number of games user has played.
int sumOfScores = 0; // The sum of all the scores from
// all the games played.
double averageScore; // Average score, computed by dividing
// sumOfScores by gamesPlayed.
boolean playAgain; // Record user's response when user is
// asked whether he wants to play
// another game.
do {
int scoreThisGame; // Score for one game.
scoreThisGame = play(); // Play the game and get the score.
sumOfScores += scoreThisGame;
gamesPlayed++;
TextIO.put("Play again? ");
playAgain = TextIO.getlnBoolean();
} while (playAgain);
averageScore = ((double)sumOfScores) / gamesPlayed;
System.out.println();
System.out.println("You played " + gamesPlayed + " games.");
System.out.printf("Your average score was %1.3f.\n", averageScore);
} // end main()
/**
* Lets the user play one game of HighLow, and returns the
* user's score on that game. The score is the number of
* correct guesses that the user makes.
*/
private static int play() {
Deck deck = new Deck(); // Get a new deck of cards, and
// store a reference to it in
// the variable, deck.
Card currentCard; // The current card, which the user sees.
Card nextCard; // The next card in the deck. The user tries
// to predict whether this is higher or lower
// than the current card.
int correctGuesses ; // The number of correct predictions the
// user has made. At the end of the game,
// this will be the user's score.
char guess; // The user's guess. 'H' if the user predicts that
// the next card will be higher, 'L' if the user
// predicts that it will be lower.
deck.shuffle(); // Shuffle the deck into a random order before
// starting the game.
correctGuesses = 0;
currentCard = deck.dealCard();
TextIO.putln("The first card is the " + currentCard);
while (true) { // Loop ends when user's prediction is wrong.
/* Get the user's prediction, 'H' or 'L' (or 'h' or 'l'). */
TextIO.put("Will the next card be higher (H) or lower (L)? ");
do {
guess = TextIO.getlnChar();
guess = Character.toUpperCase(guess);
if (guess != 'H' && guess != 'L')
TextIO.put("Please respond with H or L: ");
} while (guess != 'H' && guess != 'L');
/* Get the next card and show it to the user. */
nextCard = deck.dealCard();
TextIO.putln("The next card is " + nextCard);
/* Check the user's prediction. */
if (nextCard.getValue() == currentCard.getValue()) {
TextIO.putln("The value is the same as the previous card.");
TextIO.putln("You lose on ties. Sorry!");
break; // End the game.
}
else if (nextCard.getValue() > currentCard.getValue()) {
if (guess == 'H') {
TextIO.putln("Your prediction was correct.");
correctGuesses++;
}
else {
TextIO.putln("Your prediction was incorrect.");
break; // End the game.
}
}
else { // nextCard is lower
if (guess == 'L') {
TextIO.putln("Your prediction was correct.");
correctGuesses++;
}
else {
TextIO.putln("Your prediction was incorrect.");
break; // End the game.
}
}
/* To set up for the next iteration of the loop, the nextCard
becomes the currentCard, since the currentCard has to be
the card that the user sees, and the nextCard will be
set to the next card in the deck after the user makes
his prediction. */
currentCard = nextCard;
TextIO.putln();
TextIO.putln("The card is " + currentCard);
} // end of while loop
TextIO.putln();
TextIO.putln("The game is over.");
TextIO.putln("You made " + correctGuesses
+ " correct predictions.");
TextIO.putln();
return correctGuesses;
} // end play()
} // end class
You can try out the game in this applet, which simulates the program:
Related
I am working through Head First Java, and my Random generator is amounting to 0. Here are my classes:
This is my class with the main method.
public class GameLauncher {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
This is my player object class:
import java.util.Random;
public class Player {
int number = 0; //Where the guess goes
public void guess() {
//random1 is in GuessGame
Random random2 = new Random();
int number = random2.nextInt(10);
System.out.println("I'm guessing " + number);
}
}
Finally, this is the class where most of the code is happening.
import java.util.Random;
public class GuessGame {
//Guessgame has three instance variables for the three Player objects
Player p1;
Player p2;
Player p3;
public void startGame() {
//Create three Player objects and assign them to the three Player instance variables
p1 = new Player();
p2 = new Player();
p3 = new Player();
//Declare three variables to hold the three guesses the players make
int guessp1 = 0;
int guessp2 = 0;
int guessp3 = 0;
//Declare three variables to hold a true or false based on the player's answer
boolean p1isRight = false;
boolean p2isRight = false;
boolean p3isRight = false;
//Make a "target" number that the players have to guess
Random random = new Random();
//Generate a number between 0 and 9
int targetNumber = random.nextInt(10);
System.out.println("I'm thinking of a number between 0 and 9...");
while (true) {
System.out.println("Number to guess is " + targetNumber);
//Call each player's guess() method
p1.guess();
p2.guess();
p3.guess();
/*
Get each player's guess (the result of their guess() method
running) by accessing the number variable of each player
*/
guessp1 = p1.number;
guessp2 = p2.number;
guessp3 = p3.number;
System.out.println("Player one guessed " + guessp1);
System.out.println("Player two guessed " + guessp2);
System.out.println("Player three guessed " + guessp3);
/*
Check each player's guess to see if it matches the target number. If a player is right, then set that player's variable to be true (remember, we set it false by default)
*/
if (guessp1 == targetNumber) {
p1isRight = true;
}
if (guessp2 == targetNumber) {
p2isRight = true;
}
if (guessp3 == targetNumber) {
p3isRight = true;
}
//If player one OR player two OR player three is right... (the || operator means OR)
if (p1isRight || p2isRight || p3isRight) {
System.out.println("We have a winner!");
System.out.println("Player one got it right? " + p1isRight);
System.out.println("Player two got it right? " + p2isRight);
System.out.println("Player three got it right? " + p3isRight);
System.out.println("Game is over.");
break; //Game over, so break out of the loop
}
else {
//We must keep going because nobody got it right!
System.out.println("Players will have to try again.");
} //end if/else
} //end loop
} //end method
} //end class
I am new to these forums, so if I did something wrong please let me know :)
Does anyone know why this isn't working?
Thanks,
Lyfe
You are storing random number in local variable and you think you set it in instance variable
at line
int number = random2.nextInt(10);
change it to
this.number = random2.nextInt(10);
that atleast solves stated problem.
Also See
Java Variables
So what I have here is a fully functioning roulette game in java, running on eclipse. I want to improve it beyond What it was supposed to be by allowing the user to specify how many players they want to be in the same game, as opposed to the two hardcoded players. currently I put a way to set individual names for player 1 and 2 so me and a friend could play but I feel this would make it more universal. The goal is to take the code I have now and learn how to take a specified number, throw it into a loop to generate player objects (each with their own name) and have the program still function.
I have three classes, the Player class witch holds my constructors and payment methods, and getName() getMoney() methods as well. the Roulette class witch is the main method for the program where this loop to add player objects should be added. and the Wheel class where the randomly generated ball position is held and so forth.
here is the first class:
import java.util.Scanner;
//************************************************************************
// Class Player represents one roulette player.
//************************************************************************
public class Player
{
private int bet, money, betType, number, betNet;
#SuppressWarnings("unused")
private static int houseWins;
private String name;
private Scanner scan = new Scanner(System.in);
//=====================================================================
// The Player constructor sets up name and initial available money.
//=====================================================================
public Player (String playerName, int initialMoney)
{
name = playerName;
money = initialMoney;
} // constructor Player
//=====================================================================
// Returns this player's name.
//=====================================================================
public String getName()
{
return name;
} // method getName
//=====================================================================
// Returns this player's current available money.
//=====================================================================
public int getMoney()
{
return money;
} // method getMoney
//=====================================================================
// returns the net bets for that player
//=====================================================================
public int getNet()
{
return betNet;
}
//=====================================================================
// Prompts the user and reads betting information.
//=====================================================================
#SuppressWarnings("static-access")
public void makeBet(Wheel Wheel)
{
Scanner scan = new Scanner(System.in);
System.out.print("How much do you want to bet " + name + "? : ");
bet = scan.nextInt();
if(bet>=money)
{
System.out.println("im going all in!");
bet= money;
money = money-bet;
}
else
{
money = money-bet;
}
Wheel.betOptions();
System.out.println("Choose your bet type: ");
betType = scan.nextInt();
if(betType == 3){
System.out.println("your'e betting on: a number");
while(true){
System.out.println("Please enter the number you "
+ "wish to bet on from 1 to 36: ");
number = scan.nextInt();
if(number <1 || number > 36)
{
System.out.println("This Number is not in "
+ "the desired range.");
}
else
{
break;
}
}
}
}
// method makeBet
//=====================================================================
// Determines if the player wants to play again.
//=====================================================================
public boolean playAgain(Scanner scan)
{
String answer;
System.out.println (name + " Play again [Y/N]? ");
answer = scan.nextLine();
return (answer.equals("y") || answer.equals("Y"));
}
// method playAgain
public void payment(Wheel Wheel2)
{
int winnings = Wheel2.payoff(bet, betType, number);
money += winnings;
if(winnings > 0)
{
betNet += (winnings-bet);
Roulette.setHouseWins(-(winnings-bet));
}
else
{
betNet -= bet;
Roulette.setHouseWins((bet));
}
// =========================================================
// if player runs out of money.
// =========================================================
if(money < 1)
{
Scanner scan = new Scanner(System.in);
System.out.println(name + ", you're out of money. "
+ "Do you want to bet more? [Y/N] ");
String answer= scan.nextLine();
if(answer.equals("y") || answer.equals("Y"))
{
if (betNet>-200)
{
System.out.println("You bought back in for 100");
money +=100;
}
else {
System.out.println("Sorry buddy, your cutt off from the credit line.");
money = 0;
}
}
}
//setHouseWins(betNet);
System.out.println(" Testing to see how much is "
+ "betNet keeping track of: " + betNet);
}
}
Then here is the Wheel class:
//************************************************************************
// Class Wheel represents a roulette wheel and its operations. Its
// data and methods are static because there is only one wheel.
//************************************************************************
public class Wheel
{
// public name constants -- accessible to others
public final static int BLACK = 0; // even numbers
public final static int RED = 1; // odd numbers
public final static int GREEN = 2; // 00 OR 0
public final static int NUMBER = 3; // number bet
public final static int MIN_NUM = 1; // smallest number to bet
public final static int MAX_NUM = 36; // largest number to bet
// private name constants -- internal use only
private final static int MAX_POSITIONS = 38; // number of positions on wheel
private final static int NUMBER_PAYOFF = 35; // payoff for number bet
private final static int COLOR_PAYOFF = 2; // payoff for color bet
// private variables -- internal use only
private static int ballPosition; // 00, 0, 1 .. 36
private static int color; // GREEN, RED, OR BLACK
//=====================================================================
// Presents welcome message
//=====================================================================
public static void welcomeMessage()
{
System.out.println("Welcome to a simple version of roulette game.");
System.out.println("You can place a bet on black, red, or a number.");
System.out.println("A color bet is paid " + COLOR_PAYOFF + " the bet amount.");
System.out.println("A number bet is paid " + NUMBER_PAYOFF + " the bet amount.");
System.out.println("Have fun and good luck!\n");
}
//=====================================================================
// Presents betting options
//=====================================================================
public static void betOptions()
{
System.out.println("Betting Options:");
System.out.println(" 1. Bet on black");
System.out.println(" 2. Bet on red");
System.out.println(" 3. Bet on a number between " + MIN_NUM +
" and " + MAX_NUM);
System.out.println();
}
//=====================================================================
// method spins the wheel
//=====================================================================
public int spin()
{
ballPosition= (int)(Math.random() * MAX_POSITIONS + 1);;
if(ballPosition < 37)
{
if(ballPosition % 2 == 0)
{
color = BLACK;
}
else
{
color = RED;
}
}
else
{
color = GREEN;
}
System.out.print("the Result is: "+ ballPosition
+ " and color is: ");
if (color == BLACK)
{
System.out.println("BLACK.");
}
else if (color == RED)
{
System.out.println("RED.");
}
else
{
System.out.println("GREEN.");
}
return ballPosition;
}
//=====================================================================
// calculates the payoff
//=====================================================================
public int payoff( int bet, int betType, int number)
{
if (color == GREEN)
{
return 0;
}
else if (betType == 1 && color == BLACK)
{
return bet * COLOR_PAYOFF;
}
else if (betType == 2 && color == RED)
{
return bet * COLOR_PAYOFF;
}
else if (betType == 3 && number == ballPosition)
{
return bet * NUMBER_PAYOFF;
} else return 0;
}
}
and Finally the main method roulette class:
import java.util.*;
//************************************************************************
// Class Roulette contains the main driver for a roulette betting game.
//************************************************************************
public class Roulette
{
private static int houseMoney=0;
//=====================================================================
// Contains the main processing loop for the roulette game.
//=====================================================================
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String name1 = "jane"; String name2 = "don";
Wheel wl1 = new Wheel();
System.out.println("please enter a name for player 1: ");
name1 = scan.nextLine();
System.out.println("please enter a name for player 2: ");
name2 = scan.nextLine();
Player player1 = new Player (name1, 100); // $100 to start for Jane
Player player2 = new Player (name2, 100); // $100 to start for Dave
boolean bl1 = true;
boolean bl2 = true;
Wheel.welcomeMessage();
while (bl1 || bl2)
{
System.out.println ("Money available for " + player1.getName()
+ ": " + player1.getMoney());
if(bl1)player1.makeBet(wl1);
System.out.println ("Money available for " + player2.getName()
+ ": " + player2.getMoney());
if(bl2)player2.makeBet(wl1);
wl1.spin();
if(bl1 == true)
{
//initiate the payment
player1.payment(wl1);
System.out.println ("Money available for " + player1.getName() + ": "
+ player1.getMoney());
// check weather play the game again
if(!player1.playAgain(scan))
{
bl1 = false;
System.out.println(player1.getName()+" total wins/losses: "
+ player1.getNet());
}
}
// check the boolean value
if(bl2 == true)
{
//initiate the payment
player2.payment(wl1);
System.out.println ("Money available for " +
player2.getName() + ": " + player2.getMoney());
// check weather play the game again
if(!player2.playAgain(scan))
{
bl2 = false;
System.out.println(player2.getName()+ " total wins/losses: "
+ player2.getNet());
}
}
}
System.out.println();
System.out.printf("House %s: $%d", houseMoney > 0 ? "Wins" : "Losses", houseMoney);
System.out.println();
System.out.println ("Game over! Thanks for playing.");
}
public static void setHouseWins(int Winnings)
{
houseMoney += Winnings;
}
}
ive tried a few different ways to generate the player objects but I think the real issue is coming up with a boolean object for each respective player that wants to quit to be able to stop playing. please help a guy out! (Ps: feel free to use this program as a basis for your own roulette games as it does function quite well as is.)
There are a couple of tasks I need to complete and I need a little guidance.
First, I have to have the T command which allows the player to take the item that is in the current room they are in. The items for each room are in their respective Locale arrays. By using itemPresent it takes the item that the player1 current room is originally set to and the room is not updated throughout the game, instead it is updated within the move() method. I wanted to use roomData[2] to get the item that way, but since I can't take a variable from another method, I am unable to do this. So, how would I be able to take the item from the current room?
Second, I need to remove the item from the room once it is taken so that an item can't be taken twice.
Third, I would have to add this taken item to the player's inventory which I tried to set up using an ArrayList. I am not sure how to set up the code so that I can take the item I just found and add it to the inventory.
Thank you for all help!!
Here is my main class:
import java.util.Scanner;
import java.util.ArrayList;
public class GameEngine {
static Scanner userInput = new Scanner(System.in);
static String[] playerInfo = {"playerName"};
static Player player1 = new Player("playerName", null, 0, 0);
//Welcome Message
public static void displayIntro(){
System.out.println("\tWelcome to Power Outage!");
System.out.println("=================================================");
System.out.print("\tLet's start by creating your character.\n\tWhat is your name? ");
//Will read what name is entered and return it
playerInfo[0]= userInput.nextLine();
System.out.println("\tHello, " +playerInfo[0]+ ". Let's start the game! \n\tPress any key to begin.");
System.out.print("=================================================");
//Will move to next line when key is pressed
userInput.nextLine();
System.out.print("\tYou wake up in your bedroom. \n\tThe power has gone out and it is completely dark. \n"
+"\tYou must find your way to the basement to start the generator. \n\tMove in any direction by typing, "
+ "'N', 'S', 'E', or 'W'.\n\tType 'H' at any time for help and 'Q' "
+ "to quit the game. Good luck!\n\tPress any key.");
userInput.nextLine();
}
//Locations {roomName, description, item}
static String[][] Locale ={
{"bedroom","You see the outline of a bed with your childhood stuffed bear on it.","map"},
{"hallway","A carpeted floor and long pictured walls lie ahead of you.",null},
{"kitchen","The shining surface of your stove reflects the pale moonlight coming in the window over the sink.","battery"},
{"bathroom","You find yourself standing in front of a mirror, looking back at yourself.","flashlight"},
{"living room","You stub your toe on the sofa in the room, almost falling right into the TV.","battery"},
{"dining room","You bump the china cabinet which holds your expensive dishes and silverware.","key"},
{"office","The blinking light from the monitor on your desk can be seen in the dark",null},
{"library","The smell of old books surrounds you.","battery"},
{"basement","You reach the top of some stairs and upon descending down, you find the large metal generator.",null},
};
//Matrix for rooms
static int[][] roomMap = {
// N,E,S,W
{6,1,-1,-1}, //Bedroom (room 0)
{4,2,3,0}, //Hallway (room 1)
{-1,-1,5,1}, //Kitchen (room 2)
{1,-1,-1,-1}, //Bathroom (room 3)
{-1,7,1,-1}, //Living Room (room 4)
{2,-1,-1,-1}, //Dining Room (room 5)
{-1,-1,0,-1}, //Office (room 6)
{8,-1,-1,4}, //Library (room 7)
{-1,-1,7,-1} //Basement (room 8)
};
//Items
private String paperMap = "map";
private String key = "key";
private String flashlight = "flashlight";
private String battery = "battery";
static int currentLocation = player1.currentRoom;
//take method
//String[] currentInventory = {};
// player1.inventory = currentInventory;
/*
private static int[] itemNames = {"map","key","flashlight","battery"};
for(int i=0; i<itemNames.length; i++){
if(itemNames[i].equals("map")){
}
}
*/
//inventory
ArrayList<String> inventory = new ArrayList<String>();
//static String[] itemPresent = roomData[2];
//move method
private static String[] dirNames = {"North", "East", "South", "West"};
private static void move(int dir) {
int dest = roomMap[currentLocation][dir];
if (dest >= 0 && dest != 8) {
System.out.println("=================================================");
System.out.println("\tYou have moved " + dirNames[dir]);
currentLocation = dest;
String[] roomData = Locale[currentLocation];
System.out.println("\tYou are in the "+roomData[0]+".");
System.out.println("\t"+roomData[1]);
String itemPresent = roomData[2];
}
else if (dest == 8){
System.out.println("\tCongratulations!! You have found the basement and turned on the generator! \n\tYou have won the game!");
System.out.println("\tTHANKS FOR PLAYING!!!!!!");
System.out.println("\tCopyright 2016 \n\n");
stillPlaying = false;
}
else {
System.out.println("\tThere is no exit that way, please try again.");
}
}
//All possible responses to keys pressed
public static void pressedKey(){
while(stillPlaying){
String response = userInput.nextLine();
if(player1.currentRoom != 8 && !response.equalsIgnoreCase("Q") ){
if(response.equalsIgnoreCase("M")){
//only print if the player has the map
System.out.println("Here is your map: \n\n\t\t\tbasement\n\noffice\t living room\tlibrary\n\nbedroom\t hallway\tkitchen\n\n\t bathroom \tdining room");
break;
}
else if(response.equalsIgnoreCase("T")){
// check if there is an item in the player's current room
if( itemPresent != null){
// if there is, then add it to the player's inventory and remove it from the locale
System.out.println("You have gained: " +itemPresent+ ". This adds the item to your inventory and you get 5 points added to your score!");
//add to inventory--- player1.inventory itemPresent;
player1.score = +5;
//remove item from the locale
}
else{
System.out.println("There is no item to take in this room.");
}
}
else if(response.equalsIgnoreCase("H")){
System.out.println("To move, type 'N' for North, 'S' for South, 'W' for West, or 'E' for East."
+"\nTry to navigate to the basement to turn on the generator."
+"\nTake an item from the room you are in by pressing 'T'."
+"\nCheck your inventory by pressing 'I'."
+ "\nYou can type 'Q' at any time to quit the game.\n");
break;
}
else if(response.equalsIgnoreCase("I")){
System.out.println("These are the items in your inventory: "+player1.inventory+".");
}
else if(response.equalsIgnoreCase("N")){
move(0);
break;
}
else if(response.equalsIgnoreCase("E")){
move(1);
break;
}
else if(response.equalsIgnoreCase("S")){
move(2);
break;
}
else if(response.equalsIgnoreCase("W")){
move(3);
break;
}
else{
System.out.println("\tInvalid command!");
}
}//End of if statement
else if(response.equalsIgnoreCase("Q")){
System.out.println("Thanks for playing!\n\n");
stillPlaying = false;
}
}//End of while
}//End of pressedKey method
static boolean stillPlaying = true; //When this is true, the game continues to run
public static void main(String[] args) {
displayIntro();
System.out.println("=================================================");
System.out.println("\tYou are in the bedroom.");
while(stillPlaying){//This makes the game continue to loop
System.out.println("=================================================");
System.out.println("\tMove in any direction.");
pressedKey();
} //End of while
} //End of main
} //End of class
This is my Player class
public class Player {
//import java.util.Scanner;
//Player class must have name, location, inventory, and score
//Instead of array of descriptions, use array of Locale objects
private String playerName;
public String inventory;
public int score;
public int currentRoom;
public Player(String playerName, String inventory, int score, int currentRoom){
this.playerName = playerName;
this.inventory = inventory;
this.score = 0;
this.currentRoom = currentRoom;
}
}
This is my Locale class
public class Locale {
//Locale must have name, description, and item
private String roomName;
private String description;
private String item;
public Locale(String roomName, String description, String item){
this.roomName = roomName;
this.description = description;
this.item = item;
}
}
I am working on building a simplified version of this game. The problem states that you can have a computer that is smart or stupid but i have decided that to exclude that feature for now and decided to only go with a computer that picks a random amount of objects. I posted a question earlier and worked on it. (https://softwareengineering.stackexchange.com/questions/244680/object-oriented-design-of-a-small-java-game/244683#244683)
So initially i only had designed one class. But now i have designed 3 classes as stated by the problem. I have a pile class , a player class and a game class (also my main class).
I have so far coded the Pile and Player class. I started coding the Game class aswell however i am stuck now as i dont know how to make the game class interact with the Player and Pile class. I basically determine who's turn it is first and then rotate turns till the pile of objects is complete and declare a winner...I don't know how to make the different classes interact with each other . SO i would highly appreciate if someone can guide me further and help me finish this simple game.
I sincerely apologize if i have asked a bad question. This is my first such program i am doing in java dealing with multiple classes so it is a little confusing. I do not want anyone write code but even mentioning or telling me i should make so and so methods etc will be great !
HERE IS THE CODE I HAVE SO FAR.
PILE CLASS
package Nim;
import java.util.Random;
public class Pile {
private int initialSize;
public Pile() {
}
Random rand = new Random();
public void setPile() {
initialSize = (rand.nextInt(100 - 10) + 10);
}
public void reducePile(int x) {
initialSize = initialSize - x;
}
public int getPile() {
return initialSize;
}
public boolean hasStick() {
if (initialSize > 0) {
return true;
}
else {
return false;
}
}
}
PLAYER CLASS
package Nim;
import java.util.Scanner;
import java.util.Random;
public class Player {
public static final int HUMAN = 0;
public static final int COMPUTER = 1;
private int type;
public Player(int theType) {
type = theType;
}
Scanner in = new Scanner(System.in);
// n is number of marbles left in the pile
public int makeMove(int n) {
int max = n / 2;
int grab;
if (type == HUMAN) {
System.out.println("There are " + n
+ " marbles in total. However you can only"
+ "grab no more than " + max + " marbles");
System.out.println("Please Enter the number of marbles to grab: ");
grab = in.nextInt();
while (grab > max || grab < 0) {
System.out.println("You have entered a illelgal value. Please enter a legal value: ");
grab = in.nextInt();
}
return grab;
}
else {
Random rand = new Random();
grab = (rand.nextInt(n / 2 - 1) + 1);
System.out.println("Computer has grabbed: " + grab + " marbles");
return grab;
}
}
public void updateTurn(int n) {
type = n;
}
}
GAME CLASS (in progress)
package Nim;
import java.util.Scanner;
import java.util.Random;
public class Game {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.println(welcome());
Pile marbles = new Pile();
Player human = new Player(Player.HUMAN);
Player computer = new Player(Player.COMPUTER);
marbles.setPile();
System.out.println("There are total: " + marbles.getPile()
+ " marbles in the Pile.");
System.out.println("Time for a toin coss to see who goes first!");
System.out.println("Please Select heads(0) or Tails(1): ");
int choice = in.nextInt();
int tossResult = rand.nextInt(2);
boolean playerTurn = false;
boolean computerTurn = false;
if (choice == tossResult) {
System.out.println("You have won the Coin Toss! You will go first!");
human.updateTurn(0);
playerTurn = true;
}
else {
System.out.println("Computer has won the coin toss! Computer will go first");
computer.updateTurn(1);
computerTurn = true;
}
while (marbles.getPile() > 0 && marbles.hasStick()) {
while (playerTurn) {
int removeMarbles = human.makeMove(marbles.getPile());
marbles.reducePile(removeMarbles);
computerTurn = true;
playerTurn = false;
}
while (computerTurn) {
int removeMarbles = computer.makeMove(marbles.getPile());
marbles.reducePile(removeMarbles);
playerTurn = true;
computerTurn = false;
}
}
}
private static String welcome() {
return "Welcome to the Game of Nim";
}
}
So I'm going to take a step back and look at your class diagram.
You have three classes: Pile, Player, and Game. Pile can represent the pile at the center. Game can be the class with the main method that manages everything. And Player? Well, since you're having one Player class for all three (or two) possible states (Human, Dumb, and Smart) it should be pretty easy to implement.
Let's start with Game. It need to contain two instances of Player (human and computer), and an instance of Pile. It also needs to have a loop that goes until the game is over. So let's start to come up with a basic implementation:
Starting with Pile:
private int size;
public Pile(int newSize) {
size = newSize;
}
public boolean takeMarbles(int amount) {
size -= amount;
if (size < 1)
return false;
return true;
}
The constructor is pretty self explanatory. The takeMarbles method is returning false if the player lost, and true if they're still in the game.
Now on to Player:
public static final int HUMAN = 0;
public static final int COMPUTER = 1;
private int type;
public Player(int type) {
this.type = type;
}
Those two static fields may seem a little out of place, but it will come together in a second. On to the Game class:
Pile pile = new Pile(size);
Player human = new Player(Player.HUMAN);
Player computer = new Player(Player.COMPUTER);
Now we have a pile with a certain size, and two players that differ by type. This is how we're using the classes.
Now we need to get the main game loop working. Basically, just add an update() method to Player that depends on it's type (ie prompts for input if player, randomly decides if computer). The update method should return the amount of marbles to take. Then create a loop in the main method in Game. The loop will call update of the player and the computer repeatedly until someone loses (takeMarbles returns false). Then it will break out of the loop and print the output.
This is the basic idea, good luck and feel free to ask more questions!
This is a code to play a guessing game that i made, but the problem is that there were several issues which me as a beginner in java are not good at and need some guidance with. along the code there were some errors that i highlighted with an arrow on the side.
import java.util.*;
public class GuessingGame
{
private static Player house;
private static Player player;
private static int wins;
private static int loses;
private String name;
int card1,card2;
private int value;
public void Player(String name){
this.name=name;
card1 = (Integer) null;
card2 = (Integer) null;
}
public void Card(int value){
this.value = value;
}
public int getValue(){
return value;
}
public void acceptDeal(Card card1, Card card2){
Random r = new Random();
int value = r.nextInt(13) + 1;
card1 = new Card(value); <<<<<<<<======= Error 1
value = r.nextInt(13) + 1;
card2 = new Card(value); <<<<<<<<======= Error 2
}
public static void init()
{
house = new Player("House"); <<<<<<<<======= Error 3
player = new Player("Player"); <<<<<<<<======= Error 4
wins = 0;
loses = 0;
}
public static void playGame()
{
Scanner scan = new Scanner(System.in);
char option, playAgain;
int houseHandStrength, playerHandStrength;
System.out.println("Welcome to our card guess 1.0 game!");
System.out.println();
do {
// Deal cards to the house and player.
house.acceptDeal(new Card(houseHandStrength), new Card(houseHandStrength)); <<<<<=== Error 5
player.acceptDeal(new Card(playerHandStrength), new Card(playerHandStrength)); <<<<<=== Error 6
System.out.println(house);
// Determine whether the player wants to play this hand.
do {
System.out.print("Deal cards? (Y/N) ");
option = Character.toLowerCase(scan.next().charAt(0));
}
while (option != 'n' && option != 'y');
if (option == 'y')
{
System.out.println(player);
// Display hand strength of both players.
houseHandStrength = house.getHandStrength(); <<<<<=== Error 7
playerHandStrength = player.getHandStrength(); <<<<<=== Error 8
System.out.println("The dealer's hand strength is: " + houseHandStrength);
System.out.println("Your hand strength is: " + playerHandStrength);
System.out.println();
// If the player has a stronger hand.
if (player.getHandStrength() > house.getHandStrength())
{
System.out.println("** You won the hand! **");
wins++;
}
else {
System.out.println("The house wins this round!");
loses++;
}
}
// Display the win/lose statistics.
System.out.println("Current wins: " + wins);
System.out.println("Current loses: " + loses);
// Prompt whether the user wants to play again.
do {
System.out.print("Would you like to play again? (Y/N) ");
playAgain = Character.toLowerCase(scan.next().charAt(0));
}
while (playAgain != 'n' && playAgain != 'y');
System.out.println();
System.out.println("*******************************************************");
}
while (playAgain == 'y');
System.out.println();
System.out.println("Thank you for playing!");
}
public static void main(String[] args)
{
init();
playGame();
}
}
First of all welcome to StackOverflow. It's nice to see that you have found and used the homework tag. Keep in mind that for people to be able to help you, you need to give more information. What do you mean by error, what happens when you run the code etc
regarding the errors you get, it appears as you haven't really defined classes Card and Player, what you have there in your code are two methods GuessingGame.Card() and GuessingGame.Player() in your GuessingGame class. Change them to inner (or outer) classes and it should be fine ;)
Maybe you need to import your other classes at the top?
The problems seem to be only in your own classes, what do the program output say about the errors?
public void Player(String name)...
and
public void Card(int value)...
should be classes right? Declare them as classes in another file and include them to the main file.
In your previous Question card1 and card2 were of type Card. That was right, now you have changed this and now it is wrong.
You seemed to have bunched up your code. You've combined the Player, Card and Game classes. I don't have a Java compiler handy, but what you're looking to do is to break out the three models.
Error 1-6 were a result of trying to instantiate new objects when the class doesn't even exist. Error 7-8 were a result of trying to call a methods on the same.
import java.util.*;
class Player {
int card1, card2;
private String name;
public void Player(String name){
this.name=name;
card1 = (Integer) null;
card2 = (Integer) null;
}
public void acceptDeal(Card card1, Card card2){
Random r = new Random();
int value = r.nextInt(13) + 1;
card1 = new Card(value); <<<<<<<<======= Error 1
value = r.nextInt(13) + 1;
card2 = new Card(value); <<<<<<<<======= Error 2
}
}
class Card {
private int value;
public void Card(int value){
this.value = value;
}
public int getValue(){
return value;
}
}
public class GuessingGame
{
private static Player house;
private static Player player;
private static int wins;
private static int loses;
public static void init()
{
house = new Player("House"); <<<<<<<<======= Error 3
player = new Player("Player"); <<<<<<<<======= Error 4
wins = 0;
loses = 0;
}
public static void playGame()
{
Scanner scan = new Scanner(System.in);
char option, playAgain;
int houseHandStrength, playerHandStrength;
System.out.println("Welcome to our card guess 1.0 game!");
System.out.println();
do {
// Deal cards to the house and player.
house.acceptDeal(new Card(houseHandStrength), new Card(houseHandStrength)); <<<<<=== Error 5
player.acceptDeal(new Card(playerHandStrength), new Card(playerHandStrength)); <<<<<=== Error 6
System.out.println(house);
// Determine whether the player wants to play this hand.
do {
System.out.print("Deal cards? (Y/N) ");
option = Character.toLowerCase(scan.next().charAt(0));
}
while (option != 'n' && option != 'y');
if (option == 'y')
{
System.out.println(player);
// Display hand strength of both players.
houseHandStrength = house.getHandStrength(); <<<<<=== Error 7
playerHandStrength = player.getHandStrength(); <<<<<=== Error 8
System.out.println("The dealer's hand strength is: " + houseHandStrength);
System.out.println("Your hand strength is: " + playerHandStrength);
System.out.println();
// If the player has a stronger hand.
if (player.getHandStrength() > house.getHandStrength())
{
System.out.println("** You won the hand! **");
wins++;
}
else {
System.out.println("The house wins this round!");
loses++;
}
}
// Display the win/lose statistics.
System.out.println("Current wins: " + wins);
System.out.println("Current loses: " + loses);
// Prompt whether the user wants to play again.
do {
System.out.print("Would you like to play again? (Y/N) ");
playAgain = Character.toLowerCase(scan.next().charAt(0));
}
while (playAgain != 'n' && playAgain != 'y');
System.out.println();
System.out.println("*******************************************************");
}
while (playAgain == 'y');
System.out.println();
System.out.println("Thank you for playing!");
}
public static void main(String[] args)
{
init();
playGame();
}
}