I'm having trouble getting the graphics to show up with my hangman program.
This is the code for my engine class:
public static void main(String[] args)
{
//hangman viewer stuff
//////////////////////////////////////////////////////////////
JFrame frame = new JFrame();
frame.setSize(200,375); //invoked the method setSize on the implicit parameter frame
frame.setTitle("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
HangmanComponent g = new HangmanComponent();
frame.add(g);
frame.setVisible(true);
///////////////////////////////////////////////////////////////
String wordd = JOptionPane.showInputDialog("Type in a word.");
int length = wordd.length();
String blank = "_ ";
String word2 = new String("");
int guesscount = 10;
ArrayList<String>answers=new ArrayList<String>(); //creates reference to empty structure that will contain references
char blanks[]=new char[wordd.length()]; //creates an array with the same number of terms as the length of the word
for (int i=0; i<length; i++)//fills the array with blanks corresponding to the length of the word
{
blanks[i] = '_';
}
HangmanComponent y = new HangmanComponent();
while (true)
{
String letter = JOptionPane.showInputDialog("Guess a letter! You have "+guesscount+" guesses."+"\n"+answers+"\n"+Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")); //Prints a space
char letterchar = letter.charAt(0); //converts string letter to char letterchar
int idx = 0;
boolean found = false;
answers.add(letter); //adds the string to the arraylist answers
while (idx >= 0 && idx < length) //idx is greater than or equal to 0 but less than the length of the word
{
//System.out.println("idx = " + idx);
idx = wordd.indexOf(letter, idx); //idx is the index of "letter" in "wordd" and finds all instances of the letter
//System.out.println("idx = " + idx + ", guesscount = " + guesscount);
if (idx != -1) //if idx is not -1 (the letter exists in the word)
{
found = true;
blanks[idx] = letterchar; //sets the term in the array equal to the letter
idx += 1; //idx=idx+1
}
else
{
guesscount=guesscount-1;
y.nextStage();
y.printStage();
frame.add(y);
frame.setVisible(true);
break;
}
}
if (found)
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"You found a letter!"+"\n"+answers);
}
else
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"That letter is not in the word! Guess again!"+"\n"+answers);
if (guesscount == 0)
{
JOptionPane.showMessageDialog(null, "Sorry, you're all out of guesses. The answer was '"+wordd+".' Thanks for playing!");
break;
}
}
char [] lettersArray = wordd.toCharArray(); //converts word to array of chars
if (Arrays.equals(blanks, lettersArray))//compares array of blanks to array of letters
{
JOptionPane.showMessageDialog(null, "You guessed the word! Thanks for playing!");
break;
}
}
}
and this is the code for my HangmanComponent class (with the graphics)
int stage=0;
public void nextStage()
{
stage++;
}
public void printStage()
{
System.out.println("Your stage number is:"+stage);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(5,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
g2.setColor(Color.BLACK);
g.drawLine(50, 30, 50, 10);
g.drawLine(50, 10, 130, 10);
g.drawLine(130, 10, 130, 300);
g.drawLine(20, 300, 150, 300);
if (stage==1)
{
//draws the head
g2.setStroke(new BasicStroke(3,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
Ellipse2D.Double head = new Ellipse2D.Double(25, 30, 50, 50);
g2.draw(head);
}
else if (stage==2)
{
//draws the body
g.drawLine(50, 80, 50, 180);
}
else if (stage==3)
{
//draws the left arm
g.drawLine(10, 150, 50, 100);
}
else if (stage==4)
{
//draws the right arm
g.drawLine(50, 100, 90, 150);
}
else if (stage==5)
{
//draws the left leg
g.drawLine(30, 250, 50, 180);
}
else if (stage==6)
{
//draws the right leg
g.drawLine(50, 180, 70, 250);
}
else if (stage==7)
{
//draws the left eye
Ellipse2D.Double lefteye = new Ellipse2D.Double(40, 50, 1, 1);
g2.draw(lefteye);
g2.fill(lefteye);
}
else if (stage==8)
{
//draws the right eye
Ellipse2D.Double righteye = new Ellipse2D.Double(58, 50, 1, 1);
g2.draw(righteye);
g2.fill(righteye);
}
else if (stage==9)
{
//draws the mouth
Arc2D.Double mouth = new Arc2D.Double(40.00, 50.00, 20.00, 20.00, 180.00, 190.00, Arc2D.OPEN);
g2.draw(mouth);
}
}
Right now, the hangman program runs perfectly fine, but the graphic is only added the first time the user inputs a wrong letter. How do I get the graphics to be inputted for every time a wrong letter is inputted?
Related
Nothing appears to be wrong with this from what I have seen
Code for Driver:
import javax.swing.JFrame;
import java.util.Scanner;
import java.util.Random;
public class rpsDriver{
public static void main(String[] args){
//jpanel stuff
JFrame frame = new JFrame("Rock Paper Scissors Game");
frame.setSize(1280,720);
frame.setLocation(250, 50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new rpsPanel());
frame.setVisible(true);
}//end main
}//end class
The problem I have is that when I run the code and me or the computer gets to 3 wins the end screen that says you win/lose appears but the rock, paper, scissors button on the left is still there (and I would like for it to disappear). Also, I would like to add buttons below the thing that says you win/lose that will let you restart the game (making userScore, tieScore, and compScore = 0), and a button that ends the game (closes the panel and ends the run). I'd appreciate any help.
Code for the JPanel (the one I have problem with):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon.*;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class rpsPanel extends JPanel{
Random rand = new Random();
//variables used in code
String compChoice = "";
int userNum; //number that corresponds to a choice
int compNum; //number that corresponds to a choice
int num;
int score; //score to decide who wins
String result = "";
String userChoice = "";
//win and tie count
int userScore = 0;
int compScore = 0;
int tieScore = 0;
//boolean variables for each choice
static JFrame frame;
boolean rock = false;
boolean paper = false;
boolean scissors = false;
public void paintComponent(Graphics g){
setLayout(null);
//background
// setLayout(new BoxLayout());
ImageIcon wooden = new ImageIcon("woodenBG.jpg");
g.drawImage(wooden.getImage(), 0, 0, 1280, 720, null);
g.setFont(new Font("Serif", Font.BOLD, 30));
g.setColor(Color.BLACK);
g.drawString("VS" , 630, 385);
//images for rock,paper, scissors
ImageIcon rockChoice = new ImageIcon("rock.png");
ImageIcon paperChoice = new ImageIcon("paper.jpg");
ImageIcon scissorsChoice = new ImageIcon("scissors.jpg");
/*displays the choice the user made*/
if (rock){
g.drawImage(rockChoice.getImage(), 350, 300, 200, 200, null);
}
else if (paper){
g.drawImage(paperChoice.getImage(), 350, 300, 200, 200, null);
}
else if (scissors){
g.drawImage(scissorsChoice.getImage(), 350, 300, 200, 200, null);
}
/**********************************/
/* computer makes choice after user */
if(rock || paper || scissors){
num = rand.nextInt(9);
if(num == 1 || num == 4 || num == 7){ //rock choice
compChoice = "rock";
compNum = 1;
g.drawImage(rockChoice.getImage(), 800, 300, 200, 200, null);
}
else if (num == 2 || num == 5 || num == 8){//paper choice
compChoice = "paper";
compNum = 2;
g.drawImage(paperChoice.getImage(), 800, 300, 200, 200, null);
}
else if(num == 3 || num == 6 || num == 0){//scissors choice
compChoice = "scissors";
compNum = 3;
g.drawImage(scissorsChoice.getImage(), 800, 300, 200, 200, null);
}
}
/**********************************/
/*the logic part to decide the winner*/
score = userNum - compNum;
if(score == -2 || score == 1){
result = "win";
userScore++;
}
if(score == 2 || score == -1){
result = "loss";
compScore++;
}
if ((score == 0) && (rock || paper || scissors)){
result = "tie";
tieScore++;
}
/***************************************/
//Displays the outcome
g.setFont(new Font("Serif", Font.BOLD, 40));
g.setColor(Color.BLACK);
g.drawString("The outcome: " + result, 425, 100);
//This shows the score of you and the computer
g.setFont(new Font("Serif", Font.BOLD, 30));
g.setColor(Color.BLACK);
g.drawString("Your score is " + userScore, 25, 50);
g.setFont(new Font("Serif", Font.BOLD, 30));
g.setColor(Color.BLACK);
g.drawString("The computer's score is " + compScore, 925, 50);
g.setFont(new Font("Serif", Font.BOLD, 30));
g.setColor(Color.BLACK);
g.drawString("The amount of ties that occured are " + tieScore, 400, 50);
//user wins the game after user wins 3 rounds
if(userScore >= 3){
g.setColor(new Color(0, 0, 0, 150));
g.fillRect(0,0,1280,720);
g.setFont(new Font("Serif", Font.BOLD, 75));
g.setColor(new Color(57, 255, 20));
g.drawString("You WIN!", 300, 330);
}
//computer wins the game after computer wins 3 rounds
if(compScore >= 3){
g.setColor(new Color(0, 0, 0, 150));
g.fillRect(0,0,1280,720);
g.setFont(new Font("Serif", Font.BOLD, 75));
g.setColor(Color.RED);
g.drawString("You LOSE! Try again", 400, 330);
}
}//ends the paintcomponent class
public rpsPanel(){
setLayout(null);
//images for rock, paper, scissors
Icon rPic = new ImageIcon(new ImageIcon("rock.png").getImage().getScaledInstance(70, 70, Image.SCALE_DEFAULT));
Icon pPic = new ImageIcon(new ImageIcon("paper.jpg").getImage().getScaledInstance(70, 70, Image.SCALE_DEFAULT));
Icon sPic = new ImageIcon(new ImageIcon("scissors.jpg").getImage().getScaledInstance(70, 70, Image.SCALE_DEFAULT));
/* buttons for rock paper scissors */
JButton rockBTN = new JButton(rPic); //rock button
rockBTN.addActionListener(new rockListener());
rockBTN.setBounds(20, 200, 70, 70);
add(rockBTN);
JButton paperBTN = new JButton(pPic); //paper button
paperBTN.addActionListener(new paperListener());
paperBTN.setBounds(20, 300, 70, 70);
add(paperBTN);
JButton scissorsBTN = new JButton(sPic); //scissors button
scissorsBTN.addActionListener(new scissorsListener());
scissorsBTN.setBounds(20, 400, 70, 70);
add(scissorsBTN);
/*************************************/
/* Creates the buttons to restart or end the game when one team has 3 wins */
JButton restartBTN = new JButton("RESTART");
restartBTN.addActionListener(new restartListener());
JButton endGameBTN = new JButton("END");
endGameBTN.addActionListener(new endGameListener());
endGameBTN.setBounds(300,500,50,50);
/*****************************************************/
if(userScore < 3 || compScore < 3){
rockBTN.setVisible(true);
paperBTN.setVisible(true);
scissorsBTN.setVisible(true);
restartBTN.setVisible(false);
endGameBTN.setVisible(false);
}
else if (userScore >= 3 || compScore >= 3){
rockBTN.setVisible(false);
paperBTN.setVisible(false);
scissorsBTN.setVisible(false);
restartBTN.setVisible(true);
endGameBTN.setVisible(true);
}
}
/* listeners for each button */
private class rockListener implements ActionListener{ //rock
public void actionPerformed(ActionEvent e){
//repaints game with the rock choice
rock = true;
repaint();
revalidate();
paper = false;
scissors = false;
userNum = 1;
}
}
private class paperListener implements ActionListener{ //paper
public void actionPerformed(ActionEvent e){
//repaints game with the paper choice
paper = true;
repaint();
revalidate();
rock = false;
scissors = false;
userNum = 2;
}
}
private class scissorsListener implements ActionListener{//scissors
public void actionPerformed(ActionEvent e){
//repaints game with the scissors choice
scissors = true;
repaint();
revalidate();
paper = false;
rock = false;
userNum = 3;
}
}
private class restartListener implements ActionListener{//restartBTN
public void actionPerformed(ActionEvent e){
//if button is clicked it will restart game with score at 0
}
}
private class endGameListener implements ActionListener{//restartBTN
public void actionPerformed(ActionEvent e){
//if button is clicked it will end the game, remove panel, and end the run
}
}
/**********************************************/
}//ends rpsPanel
I am trying to make a little mini game, where u can move around. I have written a code, which did work. But when I tried to shorten my code and make it looks nicer, I stumble upon a error I could not solve by myself.
Main:
package eksamenstest;
import javax.swing.JFrame;
public class Eksamenstest extends JFrame {
public Eksamenstest() throws InterruptedException
{
JFrame SOJ = new JFrame("Sword Of Justice");
SOJ.pack();
SOJ.setSize(1000,700);
SOJ.setVisible(true);
SOJ.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SOJ.add(new Grafik());
}
public static void main(String[] args) throws InterruptedException
{
new Eksamenstest();
new Musik();
new SpillerOne();
}
}
Graphics:
package eksamenstest;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
public class Grafik extends JPanel
{
int Menu = 1;
int Player1Liv = 3;
int Player2Liv = 3;
int DødP1 = 1;
int DødP2 = 1;
int WeaponON2;
int WeaponON1;
int Skjold;
int Skjold1;
int x = 100;
int y = 360;
int x_1 = 820;
int y_1 = 360;
public Grafik(){}
public void paint(Graphics g)
{
//Grafikken af banen
Image Bane2 = Toolkit.getDefaultToolkit().getImage("Bane2.png");
g.drawImage(Bane2, 0, 0, 1000, 800, this);
Image Plank = Toolkit.getDefaultToolkit().getImage("Plank.jpg");
g.drawImage(Plank, 100, 500, 800, 10, this);
Image lava = Toolkit.getDefaultToolkit().getImage("lava.png");
g.drawImage(lava, 0, 520, 1000, 260, this);
if(Menu == 1)
{
Image Menu2 = Toolkit.getDefaultToolkit().getImage("Menu.png");
g.drawImage(Menu2, 100, -30, 900, 700, this);
}
//Player 1 - Grafikken der viser hvordan spilleren står.
if(WeaponON1 == 0){
Image PlayerStå = Toolkit.getDefaultToolkit().getImage("Stå.png");
g.drawImage(PlayerStå, x, y, 80, 140, this);
}
if(WeaponON1 == 1){
Image PlayerSværdOP = Toolkit.getDefaultToolkit().getImage("OP.png");
g.drawImage(PlayerSværdOP, x, y, 80, 140, this);
}
if(WeaponON1 == 2){
Image PlayerSværdFrem = Toolkit.getDefaultToolkit().getImage("Frem.png");
g.drawImage(PlayerSværdFrem, x, y, 80, 140, this);
}
if(Skjold == 1){
Image Player1Skjold = Toolkit.getDefaultToolkit().getImage("Player1Skjold.png");
g.drawImage(Player1Skjold, x, y, 80, 140, this);
}
if(Player1Liv == 0){
Image DødP = Toolkit.getDefaultToolkit().getImage("DødP.png");
g.drawImage(DødP, x, y, 80, 140, this);
}
if(Player2Liv == 0){
Image Jubel = Toolkit.getDefaultToolkit().getImage("Jubel.png");
g.drawImage(Jubel, x, y, 80, 140, this);
}
//Player 2 - Grafikken der viser hvordan spilleren står.
if(WeaponON2 == 0){
Image PlayerStå1 = Toolkit.getDefaultToolkit().getImage("Stå1.png");
g.drawImage(PlayerStå1, x_1, y_1, 80, 140, this);
}
if(WeaponON2 == 1){
Image PlayerSværdOP1 = Toolkit.getDefaultToolkit().getImage("OP1.png");
g.drawImage(PlayerSværdOP1, x_1, y_1, 80, 140, this);
}
if(WeaponON2 == 2){
Image PlayerSværdFrem1 = Toolkit.getDefaultToolkit().getImage("Frem1.png");
g.drawImage(PlayerSværdFrem1, x_1, y_1, 80, 140, this);
}
if(Skjold1 == 1){
Image Player2Skjold = Toolkit.getDefaultToolkit().getImage("Player2Skjold.png");
g.drawImage(Player2Skjold, x_1, y_1, 80, 140, this);
}
if(Player2Liv == 0){
Image DødPA = Toolkit.getDefaultToolkit().getImage("DødP.png");
g.drawImage(DødPA, x_1, y_1, 80, 140, this);
}
if(Player1Liv == 0){
Image Jubel = Toolkit.getDefaultToolkit().getImage("Jubel.png");
g.drawImage(Jubel, x_1, y_1, 80, 140, this);
}
//Health Bars / Stamina / Navne / Win
//Player 1
Image PlayerNavn = Toolkit.getDefaultToolkit().getImage("Player1Navn.png");
g.drawImage(PlayerNavn, 30, 50, 70, 30, this);
if(Player1Liv == 3){
Image Liv100B = Toolkit.getDefaultToolkit().getImage("Liv100B.png");
g.drawImage(Liv100B, 30, 80, 120, 40, this);
}
if(Player1Liv == 2){
Image Liv75B = Toolkit.getDefaultToolkit().getImage("Liv75B.png");
g.drawImage(Liv75B, 30, 80, 120, 40, this);
}
if(Player1Liv == 1){
Image Liv50B = Toolkit.getDefaultToolkit().getImage("Liv25B.png");
g.drawImage(Liv50B, 30, 80, 120, 40, this);
}
if(Player1Liv == 0){
Image Liv0B = Toolkit.getDefaultToolkit().getImage("Liv0B.png");
g.drawImage(Liv0B, 30, 80, 120, 40, this);
DødP1 = 0;
Image Player2Win = Toolkit.getDefaultToolkit().getImage("Player2Wins.png");
g.drawImage(Player2Win, 350, 80, 350, 110, this);
}
// Player 2
Image PlayerNavn1 = Toolkit.getDefaultToolkit().getImage("Player2Navn.png");
g.drawImage(PlayerNavn1, 900, 50, 70, 30,this);
if(Player2Liv == 3){
Image Liv100R = Toolkit.getDefaultToolkit().getImage("Liv100R.png");
g.drawImage(Liv100R, 850, 80, 120, 40, this);
}
if(Player2Liv == 2){
Image Liv75R = Toolkit.getDefaultToolkit().getImage("Liv75R.png");
g.drawImage(Liv75R, 850, 80, 120, 40, this);
}
if(Player2Liv == 1){
Image Liv50R = Toolkit.getDefaultToolkit().getImage("Liv25R.png");
g.drawImage(Liv50R, 850, 80, 120, 40, this);
}
if(Player2Liv == 0){
Image Liv0R = Toolkit.getDefaultToolkit().getImage("Liv0R.png");
g.drawImage(Liv0R, 850, 80, 120, 40, this);
DødP2 = 0;
Image Player1Win = Toolkit.getDefaultToolkit().getImage("Player1Wins.png");
g.drawImage(Player1Win, 350, 80, 350, 110, this);
}
}
}
Player Movement
package eksamenstest;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class SpillerOne extends JFrame implements ActionListener, KeyListener {
int x = 100;
int y = 360;
int xHøjre;
int xVenstre;
int DødP1;
int Player1Liv;
int iLava;
int x_1;
int Player2Liv;
int Skjold1;
int WeaponON1;
int Menu = 1;
int SværdTid;
int Sværd;
int Skjold;
public SpillerOne()
{
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public void actionPerformed(ActionEvent e)
{
PlayerOneMove();
repaint();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
//Menu
if(c == KeyEvent.VK_O){
Menu = 1;
}
if(c == KeyEvent.VK_P){
Menu = 0;
}
// Player
if(DødP1 == 1){
if(c == KeyEvent.VK_A){
xVenstre = 1;
WeaponON1 = 0;
Sværd = 0;
}
if(c == KeyEvent.VK_D){
xHøjre = 1;
WeaponON1 = 0;
}
if(WeaponON1 == 1){
if(SværdTid < 3){
if(c == KeyEvent.VK_W){
WeaponON1 = 2;
SværdTid++;
}
}
}
if(c == KeyEvent.VK_S){
WeaponON1 = 1;
Sværd = 1;
}
if(c == KeyEvent.VK_Q){
Skjold = 1;
SværdTid++;
}
}
if(c == KeyEvent.VK_E){
SværdTid--;
WeaponON1 = 0;
}
}
#Override
public void keyReleased(KeyEvent e)
{
int c = e.getKeyCode();
// Spiller 1
if(c == KeyEvent.VK_A){
xVenstre = 0;
}
if(c == KeyEvent.VK_D){
xHøjre = 0;
}
if(c == KeyEvent.VK_Q){
Skjold = 0;
SværdTid = SværdTid;
}
if(c == KeyEvent.VK_W){
if(Sværd == 1)
WeaponON1 = 1;
}
if(c == KeyEvent.VK_E){
SværdTid = SværdTid;
WeaponON1 = 0;
}
}
public void PlayerOneMove()
{
// Spiller et Bevægelse
x = x + xHøjre; //Højre
x = x - xVenstre; //Venstre
if(WeaponON1 == 2){ //Tjekker om spilleren har våbnet fremme og hvis ja, så tjekker den om modspilleren har skjold på, hvis ikke, mister person 2 liv.
if(Skjold1 == 0){
if(x > x_1-80 && x < x_1 + 80){
x = 100;
x_1 = 820;
Player2Liv--;
}
}
if(WeaponON1 == 2){
if(Skjold1 == 1){
if(x > x_1-80 && x < x_1 + 80){
x_1 = x_1 + 60;
}
}
}
}
// Falder ned i lava
if(x < 100 && 100 > x + 80){ //Tjekker om player 1 er i lava ved venstre side.
DødP1 = 0;
Player1Liv = 0;
iLava = 1;
if(y < 500){
y++;
}
}
if(x > 900){ //Tjekker om player 1 er i lava ved højre side.
DødP1 = 0;
Player1Liv = 0;
iLava = 1;
if(y < 500){
y++;
}
}
}
}
I have a feeling that this error is caused because I have not repainted somewhere.
So, a list of issues...
First
There are two JFrames - which one is actually been used for what? As far as I can tell, SpillerOne is never displayed, so there is no possible way for it to be able to react to key events. Equally, your ActionListener doesn't seem to be attached to anything which can actually generate actions.
This also raises a bunch of questions about the relationship between SpillerOne and Grafik. They seem to be sharing variable names, but there is no way for them to be sharing state, so even if the KeyListener worked, Grafik would never reflect the changes in SpillerOnes state
Second
You've implemented your custom painting the wrong way. It's highly discouraged to override paint, instead, you should be overriding paintComponent AND calling super.paintComponent to ensure that requirements of the paint chain are upheld
See Performing Custom Painting and Painting in AWT and Swing for more details
You also seem to be putting a lot of state logic into your Grafik class, this is going to become exponentially more difficult to maintain as the complexity increases. Instead, each distinct operation should be it's own class, focused on performing as few dedicated operations as possible
Thirdly
KeyListener is a poor choice for monitoring for key events. While there are "hacks" that attempt to "solve" the focus related issues with KeyListener, none of them can achieve a reliable result.
If you do any research into KeyListener related issues, you will quickly find that the Key bindings API is often sighted as the most reliable solution to the problem
Overall
You code makes no sense. Why are there two frames? What is the ActionListener for and how is it attached to something that generates actions? Why doesn't the Grafik act as the key/action listener?
I think you have some significant thinking and redesigning to do
I'm having problems with my java applet. I've made a Rock paper scissors game and i have 2 problems which I can't solve:
1. how to load the applet without the rock image on the left (players choice)
2. the score for player and computer does not reduce by 1 for every lost game
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class RockScissorsPaper extends Applet implements ActionListener
{
private Button rockButton;
private Button scissorsButton;
private Button paperButton;
private String buttonPressed = "";
private int computerValue = -1;
private int myValue;
private int playerScore = 10;
private int computerScore = 10;
private int drawScore = 0;
private Image imgRock;
private Image imgScissors;
private Image imgPaper;
public void init()
{
rockButton = new Button("Rock");
scissorsButton = new Button("Scissors");
paperButton = new Button("Paper");
add(rockButton);
add(scissorsButton);
add(paperButton);
rockButton.addActionListener(this);
scissorsButton.addActionListener(this);
paperButton.addActionListener(this);
imgRock = getImage(getCodeBase(), "rock.jpg");
imgScissors = getImage(getCodeBase(), "scissors.jpg");
imgPaper = getImage(getCodeBase(), "paper.jpg");
}
public void actionPerformed(ActionEvent event)
{
buttonPressed = ((Button)event.getSource()).getLabel();
computerValue = randomNumber012();
translator(buttonPressed);
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
rockButton.setLocation(20,260);
rockButton.setSize(70,35);
paperButton.setLocation(210, 260);
paperButton.setSize(70, 35);
scissorsButton.setLocation(380, 260);
scissorsButton.setSize(90, 35);
choice(g);
g.drawString("Player's Wins: " + playerScore, 10, 20);
g.drawString("Computer's Wins: " + computerScore, 180, 20);
g.drawString("Draws: " + drawScore, 400, 20);
g.drawString("Your Choice: " + buttonPressed, 20, 60);
g.drawString("Computer's Pick: ", 350, 60);
winner(g, computerValue, myValue);
}
int randomNumber012()
{
return (int)(Math.random()*3);
}
public void translator(String s)
{
if(s.equals("Rock"))
{
myValue = 0;
}
else if(s.equals("Scissors"))
{
myValue = 1;
}
else if(s.equals("Paper"))
{
myValue = 2;
}
}
public void choice(Graphics g)
{
if(myValue == 0)
{
g.drawImage(imgRock, 20, 100, 100, 60, this);
}
else if(myValue == 1)
{
g.drawImage(imgScissors, 20, 100, 100, 60, this);
}
else if(myValue == 2)
{
g.drawImage(imgPaper, 20, 100, 100, 60, this);
}
if(computerValue == 0)
{
g.drawString("Computer's Pick: Rock", 350, 60);
g.drawImage(imgRock, 350, 100, 100, 60, this);
}
else if(computerValue == 1)
{
g.drawString("Computer's Pick: Scissors", 350, 60);
g.drawImage(imgScissors, 350, 100, 100, 60, this);
}
else if(computerValue == 2)
{
g.drawString("Computer's Pick: Paper", 350, 60);
g.drawImage(imgPaper, 350, 100, 100, 60, this);
}
}
public void winner(Graphics g, int cv, int mv)
{
if(cv == -1)
{
g.drawString("", 200, 100);
}
else if(cv == mv)
{
g.drawString("Draw", 200, 250);
drawScore = drawScore + 1;
}
else if(cv == 0 && mv == 1 || cv == 2 && mv == 0 || cv == 1 && mv == 2)
{
g.drawString("Computer Wins", 200, 250);
playerScore = playerScore - 1;
}
else
{
g.drawString("You Win!", 200, 250);
computerScore = computerScore - 1;
}
if (playerScore == 0)
{
System.out.println("You lost!");
playerScore = 10;
computerScore = 10;
drawScore = 0;
}
else if(computerScore == 0)
{
System.out.println("You won!");
playerScore = 10;
computerScore = 10;
drawScore = 0;
}
}
}
how to load the applet without the rock image on the left (players choice)
You need to have a fourth case for your myValue variable, when the player has not made a choice yet. Right now you only have three potential values, and the default is 0, which is why you see a rock image before you make a choice.
the score for player and computer does not reduce by 1 for every lost game
You're using ints where you should be using enums and booleans, which is making your code harder to understand. I'd highly recommend refactoring your code to use enums and booleans instead of ints.
Also, you're always calling every method from the paint() method. Don't do that. Instead, only call the functions that check for a winner when the player actually makes a choice, presumably from a button click.
Finally, you're also calling setLocation() inside your paint() method, which is a bad idea. You should only call setLocation() once, or better yet, use a layout manager.
I am working on a poker game in Java.
I would like to know how to make the diamond and heart symbol red instead of white filled, since I cannot find it in the unicode list.
Any help is appreciated.
EDIT: I would like to know how to paint the symbols to red.
This is my code so far:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class PokerHand extends Frame implements ActionListener {
Button b = new Button("Click for new hand");
boolean dealt[] = new boolean[52];
String[] playercard = new String[10];
String[] playersuit = new String[10];
Random r = new Random();
int drawn;
public static void main(String args[]) {
PokerHand ph = new PokerHand();
ph.doIt();
}
public void doIt() {
int ct;
for (ct = 0; ct <= 9; ++ct) { // first loop that you learned tonight
playercard[ct] = " ";
playersuit[ct] = " ";
} // ends for loop
b.addActionListener(this);
this.setLayout(new FlowLayout());
this.add(b);
this.setSize(500, 500);
this.setVisible(true);
}// ends doIt method
public void paint(Graphics g) {
g.setFont(new Font(null, 1, 30));
g.drawString("Me", 400, 100);
g.drawString(playercard[0], 30, 100);
g.drawString(playersuit[0], 60, 100);
g.drawString(playercard[1], 90, 100);
g.drawString(playersuit[1], 120, 100);
g.drawString(playercard[2], 150, 100);
g.drawString(playersuit[2], 180, 100);
g.drawString(playercard[3], 210, 100);
g.drawString(playersuit[3], 240, 100);
g.drawString(playercard[4], 270, 100);
g.drawString(playersuit[4], 300, 100);
g.drawString("You", 400, 200);
g.drawString(playercard[5], 30, 200);
g.drawString(playersuit[5], 60, 200);
g.drawString(playercard[6], 90, 200);
g.drawString(playersuit[6], 120, 200);
g.drawString(playercard[7], 150, 200);
g.drawString(playersuit[7], 180, 200);
g.drawString(playercard[8], 210, 200);
g.drawString(playersuit[8], 240, 200);
g.drawString(playercard[9], 270, 200);
g.drawString(playersuit[9], 300, 200);
}
public void actionPerformed(ActionEvent ae) {
int ct;
ct = 0;
int card;
int suit;
// we draw 10 cards here
while (ct < 10) { // a while loop in practice
drawn = r.nextInt(52);
if (dealt[drawn] != true) { // if in practice
card = drawn % 13 + 1;
suit = drawn / 13;
dealt[drawn] = true;
playercard[ct] = String.valueOf(card);
if (card == 1) {
playercard[ct] = "A";
}
if (card == 11) {
playercard[ct] = "J";
}
if (card == 12) {
playercard[ct] = "Q";
}
if (card == 13) {
playercard[ct] = "K";
}
if (suit == 0) {
playersuit[ct] = "\u2660";
}
if (suit == 1) {
playersuit[ct] = "\u2661"; //change to red heart
}
if (suit == 2) {
playersuit[ct] = "\u2662"; //change to red diamond
}
if (suit == 3) {
playersuit[ct] = "\u2663";
}
ct = ct + 1;
} // ends if
}// ends while
repaint();
for (int x = 0; x <= 51; ++x)
dealt[x] = false;
}// ends method
}// ends the class
If your Unicode font has the hearts, clubs, diamonds and spades symbols, then all you need to do to draw them in the color of your choice is the same as drawing any other character in the color of your choice: simply use setColor.
Now you should start from the "filled" version of spades, hearts, diamonds and clubs, they are:
- spade: \u2660
- heart: \u2665 (use 2665 instead of 2661)
- diamonds: \u2666 (use 2666 instead of 2662)
- clubs: \u2663b
Then you simply do:
g.setColor(Color.RED);
g.drawString("\u2665");
And then you change the color, say, back to black to draw text and back to red/black for suits (or red, black, blue and green if you want to use a "four-color deck").
This is (FINALLY) working for me! Ultimately the unicode doesn't change for the suits themselves, it's the \uFE0F that makes it "pop" and give it the color.
public enum Suit {
SPADES("\u2660\uFE0F"), HEARTS("\u2665\uFE0F"), DIAMONDS("\u2666\uFE0F"), CLUBS("\u2663\uFE0F");
private final String icon;
Suit(String icon) {
this.icon = icon;
}
public String getIcon() {
return icon;
}
}
I'm having a difficult time understanding where and when to repaint() in my Craps game. I understand that after every instance of an event, like when Start Game or Roll Dice is selected, I need to put repaint(). However when I change the string output from "" to "You've Won!!" in each case and then reprint, the app does not recognize it. I have scanned the site for possible remedies, but cannot find anything like what I'm trying to do, as I'm using .gif's for the dice images and am writing an applet, thus I cannot just sysout in a main method. Any and all criticism is of course welcome, I can handle the heat..
What I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.*;
import java.util.Random;
public class Craps extends JApplet implements ActionListener {
Random gen = new Random();
// constant variables for game status
final int WON = 0, loss = 1, CONTINUE = 2;
// other variables used
boolean firstRoll = true; // true if first roll of dice
int diceSum = 1; // sum of the dice
int aPoint = 1; // point if no win/loss on first roll
int stillGame = CONTINUE; // game not over yet
int dice1 = gen.nextInt(6) + 1;
int dice2 = gen.nextInt(6) + 1;
int diceSec, dice2Sec;
int Horizon = gen.nextInt(260) + 25;
int secHorizon = gen.nextInt(260) + 25;
int Vertical = gen.nextInt(150) + 40;
int SecVerto = gen.nextInt(150) + 40;
Image[] dice = new Image[6];
int Low = 35, High = 335;
int Up = 50, Down = 250;
int wins = 0;
String s1 = "";
// GUI
JButton rollButton, startButton;
public void init() {
Button rollButton = new Button("Roll Dice");
Button startButton = new Button("Start Game");
setSize(400, 400);
setLayout(null);
for (int i = 0; i < 6; i++) {
dice[i] = getImage(getCodeBase(), "dice" + (i + 1) + ".gif");
}
// create button to start the game
startButton.setBounds(40, 300, 100, 20);
add(startButton);
startButton.addActionListener(this);
startButton.setEnabled(true);
// create button to roll dice
rollButton.setBounds(230, 300, 100, 20);
add(rollButton);
rollButton.addActionListener(this);
rollButton.setEnabled(true);
} // end of init
public void paint(Graphics g) {
super.paint(g);
// draw craps table
g.setColor(Color.red);
g.fillRect(1, 1, 400, 400);
// draw playing field
g.setColor(Color.green);
g.fillRoundRect(25, 40, 310, 210, 75, 75);
// paint the images of the dice
g.drawImage(dice[dice1 - 1], Horizon, Vertical, 32, 32, this);
g.drawImage(dice[dice2 - 1], secHorizon, SecVerto, 32, 32, this);
g.setColor(Color.black);
g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 22));
g.drawString(s1, 33, 280);
}
public void actionPerformed(ActionEvent e) {
// first roll of dice
Horizon = gen.nextInt(260) + 25;
secHorizon = gen.nextInt(260) + 25;
Vertical = gen.nextInt(150) + 40;
SecVerto = gen.nextInt(150) + 40;
if (e.getSource() == rollButton) {
// while (stillGame == CONTINUE) {
if (firstRoll) {
diceSum = diceRoller(); // roll dice
// repaint();
switch (diceSum) {
// user victory on first roll
case 7:
case 11:
stillGame = WON;
s1 = "You Win";
wins++;
break;
// user loss on first roll
case 2:
case 3:
case 12:
stillGame = loss;
s1 = "You Lose";
break;
default:
stillGame = CONTINUE;
aPoint = diceSum;
firstRoll = false;
s1 = "The Point is " + aPoint + "";
break;
} // end switch
// end if (firstRoll) statement
repaint();
}
else {
diceSum = diceRoller(); // roll dice
// determine game status
if (diceSum == aPoint) // win by making point
s1 = "You Win!!";
else if (diceSum == 7) // lose by rolling seven
s1 = "Suck It";
}
// end while loop
} // end if structure body
// subsequent roll of dice
else {
diceSum = diceRoller(); // roll dice
// determine game status
if (diceSum == aPoint) { // win by making point
s1 = "You Win!!";
stillGame = WON;
} else if (diceSum == 7) { // lose by rolling seven
s1 = "You've Lost";
stillGame = loss;
}
}// end else structure
if (e.getSource() == startButton) {
s1 = "";
}
repaint();
}
// roll dice, calculate sum and display results
public int diceRoller() {
int sum;
dice1 = gen.nextInt(6) + 1; // pick random dice values
dice2 = gen.nextInt(6) + 1;
sum = dice1 + dice2; // sum die values
return sum; // return the sum of dice
} // end method rollDice
} // end
Seems your problem in next: in init() method you declare local variables:
Button rollButton = new Button("Roll Dice");
Button startButton = new Button("Start Game");
and add ActionListener to them, but in your actionPerformed(ActionEvent e) method you compare source with null :
e.getSource() == rollButton
e.getSource() == startButton
here : rollButton == null and startButton == null, because of that, your if statement never execute, only else statement.
Declare your buttons in init() method like next:
rollButton = new JButton("Roll Dice");
startButton = new JButton("Start Game");
I think it helps you.
Also read about variables in java.