Hangman
I need help, my hangman works, but I want the hangman to show a GUI shape for each wrong answer. help me out! thanks
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
import javax.swing.*;
public class Hangman extends Applet implements KeyListener, Runnable, MouseListener
final int maxNumTries = 5;
final int wordGuessed = 20;
final int Image1 = 0;
final int Image2 = 1;
final int gameboardWidth = 40;//default size of the game board
final int gameboardHeight = 60;
int danceSequenceNum = -1;
int danceDirection = 1;
char secretWord[];
int secretWordGuessed;
char wrongLetters[];
int wrongLettersCount;
char word[];
int wordLen;
Font wordFont;
FontMetrics wordFontMetrics;
MediaTracker mediaTracker;
Image hangImages[];
Thread hangmanThread;
Image hangmanImages[];
int danceHeight = 68;
int hangmanImagesLen = 0;
public void init ()
int i;
mediaTracker = new MediaTracker ( this );
hangmanImages = new Image [40];
for ( i = 0; i < 7; i ++)
Image im = getImage( getDocumentBase(), " images/dancing-duke.gif" + i);
mediaTracker . addImage( im , Image1 );
hangmanImages [ hangmanImagesLen ++] = im ;
hangImages = new Image [ maxNumTries ];
for ( i = 0; i < maxNumTries ; i ++)
Image im = getImage( getDocumentBase(), " images/hanging-duke" + ( i + 1) + " .gif");
mediaTracker . addImage( im , Image2 );
hangImages [ i ] = im ;
wrongLettersCount = 0;
wrongLetters = new char [ maxNumTries ];
secretWordGuessed = 0;
secretWord = new char [ wordGuessed ];
word = new char [ wordGuessed ];
wordFont = new java.awt.Font ("Serif", Font . BOLD, 22);
wordFontMetrics = getFontMetrics(wordFont);
addMouseListener( this );
addKeyListener( this );
String wordlist[] = {" abstraction", " ambiguous", " arithmetic", " backslash", " bitmap",
" circumstance", " combination", " consequently", " consortium", " decrementing",
" dependency", " disambiguate", " dynamic", " encapsulation", " equivalent",
" expression", " facilitate", " fragment", " hexadecimal", " implementation",
" indistinguishable", " inheritance", " internet", " java", " localization",
" microprocessor", " navigation", " optimization", " parameter", " patrick"};
public void paint (Graphics g)//creates the hangman gameboard
int imageW = gameboardWidth ;
int imageH = gameboardHeight ;
int baseWidth = 30;
int baseHeight = 15;
Font font;
FontMetrics fontMetrics;
int i, x, y;
g . drawLine(baseWidth / 2, 5, baseWidth / 2, 2 * imageH - baseHeight / 2);
g . drawLine(baseWidth / 2, 5, baseWidth + imageW / 2, 0);
g . drawLine(baseWidth + imageW / 2, 0, baseWidth + imageW / 2, imageH / 6);
g . fillRect(2, 2 * imageH - baseHeight , baseWidth , baseHeight );
font = new java.awt.Font (" SansSerif", Font . BOLD, 14);
fontMetrics = getFontMetrics(font);
x = imageW + baseWidth ;
y = fontMetrics . getHeight();
g . setFont( font );
g . setColor( Color . black);
for ( i = 0; i < wrongLettersCount ; i ++)
g . drawChars( wrongLetters , i , 1, x , y );
x += fontMetrics . charWidth( wrongLetters [ i ]) + fontMetrics . charWidth(' ');
if ( secretWordGuessed > 0)
int Mwidth = wordFontMetrics . charWidth('O');
int Mheight = wordFontMetrics . getHeight();
g . setFont( wordFont );
g . setColor( Color . red);
x = 0;
y = getSize(). height - 1;
for ( i = 0; i < secretWordGuessed ; i ++)
g . drawLine( x , y , x + Mwidth , y );
x += Mwidth + 3;
x = 0;
y = getSize(). height - 3;
g . setColor( Color . blue);
for ( i = 0; i < secretWordGuessed ; i ++)
if ( word [ i ] != 0)
g . drawChars( word , i , 1, x , y );
x += Mwidth + 3;
if ( wordLen < secretWordGuessed && wrongLettersCount > 0)
//g . drawImage( hangImages [ wrongLettersCount - 1], baseWidth , imageH / 3, this );
public void update ( Graphics g)
if ( wordLen == 0)
//g . clearRect(0, 0, getSize(). width, getSize(). height);
paint( g );
else if ( wordLen == secretWordGuessed )
if(danceSequenceNum < 0)
g . clearRect(0, 0, getSize(). width, getSize(). height);
paint( g );
danceSequenceNum = 0;
//updateGame( g );
else
paint( g );
public void newGame ()
int i;
hangmanThread = null ;
String s = wordlist [ ( int ) Math . floor( Math . random() * wordlist . length)];
secretWordGuessed = Math . min( s . length(), wordGuessed );
for ( i = 0; i < secretWordGuessed ; i ++)
secretWord [ i ] = s . charAt( i );
for ( i = 0; i < wordGuessed ; i ++)
word [ i ] = 0;
wordLen = 0;
for ( i = 0; i < maxNumTries ; i ++)
wrongLetters [ i ] = 0;
wrongLettersCount = 0;
repaint();
public void start ()
requestFocus();
try
mediaTracker . waitForID( Image2 );
catch ( InterruptedException e){} mediaTracker . checkAll( true );
if ( secretWordGuessed == wordLen || wrongLettersCount == maxNumTries )
newGame();
public void stop ()
//hangmanThread = null ;
public void run ()
public void keyPressed ( KeyEvent e)
public void keyReleased ( KeyEvent e)
int i;
boolean found = false ;
char key = e . getKeyChar();
if ( secretWordGuessed == wordLen || wrongLettersCount == maxNumTries )
newGame();
e . consume();
return ;
/*if ( key < 'a' || key > 'z')
e . consume();
return ;
for ( i = 0; i < secretWordGuessed ; i ++)
if ( key == word [ i ])
found = true ;
e . consume();
return ;
if (! found )
for ( i = 0; i < maxNumTries ; i ++)
if ( key == wrongLetters [ i ])
found = true ;
e . consume();
return ;
if (! found )
for ( i = 0; i < secretWordGuessed ; i ++)
if ( key == secretWord [ i ])
word [ i ] = ( char ) key ;
wordLen ++;
found = true ;
if ( found ) if ( wordLen == secretWordGuessed )
if (! found ) if ( wrongLettersCount < wrongLetters . length)
wrongLetters [ wrongLettersCount ++] = ( char ) key ;
if ( wrongLettersCount < maxNumTries )
else
for ( i = 0; i < secretWordGuessed ; i ++)
word [ i ] = secretWord [ i ];
if ( wordLen == secretWordGuessed )
//danceSequenceNum = -1;
repaint();
e . consume();
public void keyTyped ( KeyEvent e)
public void mouseClicked ( MouseEvent e)
public void mouseReleased ( MouseEvent e)
public void mousePressed ( MouseEvent e)
int i;
requestFocus();
if ( secretWordGuessed > 0 && ( secretWordGuessed == wordLen || wrongLettersCount == maxNumTries ))
newGame();
else
e . consume();
public void mouseEntered ( MouseEvent e)
public void mouseExited ( MouseEvent e)
}
Look at what you posted and ask yourself whether anyone might be able to read that, a huge pile of statements, unformatted, no comments... and your problem description is not very clear either.
Similar Messages
-
Help with a hangman class with Gui
Gah, so I'm creating a Java Hangman program using a gui program. Everything was working fine till I started adding the program to the gui. I'm hopelessly confused, and I can't seem to get it working. Help appreciated! Thanks guys... I'm really bad at this, sorry for the noob question.
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.Random;
import java.util.Scanner;
import javax.accessibility.AccessibleContext;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.plaf.PanelUI;
public class hmg extends JPanel {
private char[] word;
private int Misses;
private int myWordIndex;
private int index;
private boolean[] used;
protected Image[] i = new Image[8];
protected Image[] s = new Image[3];
private final static char NADA = '_';
private final static int GUESSES = 8;
private String fileName;
i[0] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang1.jpg");
i[1] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang2.jpg");
i[2] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang3.jpg");
i[3] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hange4.jpg");
i[4] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang5.jpg");
i[5] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang6.jpg");
i[6] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang7.jpg");
i[7] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang8.jpg");
s[0] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
s[1] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
s[2] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
protected int x = 0;
protected ImageIcon icon = new ImageIcon(i[x++]);
protected ImageIcon icon2 = new ImageIcon(s[x++]);
private JLabel j = new JLabel(icon);
private JButton b = new JButton();
private JLabel a = new JLabel();
private String[] wordArray;
private String wordChosen;
public void paintComponent(Graphics g) {
super.paintComponents(g);
public hmg() {
this.add(j);
JButton guess = new JButton("The Click of Faith!");
this.add(guess, BorderLayout.WEST);
guess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!(x == i.length)) {
icon = new ImageIcon(i[x++]);
j.setIcon(icon);
JButton guess2 = new JButton("Click here if your almost dead! ");
this.add(guess2, BorderLayout.WEST);
guess2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
icon2 = new ImageIcon(s[x++]);
j.setIcon(icon);
this.add(a, BorderLayout.SOUTH);
a.setText(showWord());
a.setText(play());
Misses = 0;
index = 0;
used = new boolean[Character.MAX_VALUE];
// public void actionPerformed(ActionEvent arg0) {
// if (!(x == i.length)) {
// icon = new ImageIcon(i[x++]);
// j.setIcon(icon);
private void clear() {
int k;
for (k = 0; k < Character.MAX_VALUE; k++) {
used[k] = false;
word = new char[myWords[myWordIndex].length()];
for (k = 0; k < word.length; k++) {
word[k] = NADA;
private void guess(char ch) {
int b;
boolean charFound = false;
ch = Character.toLowerCase(ch);
for (b = 0; b < word.length; b++) {
if (!used[ch] && myWords[index].charAt(b) == ch) {
word[b] = ch;
charFound = true;
if (!used[ch] && !charFound) {
Misses++;
used[ch] = true;
private void chooseRandomWord()
// myWords[];
// loadFileList();
Random generator = new Random();
int x = generator.nextInt(wordArray.length);
wordChosen = wordArray[x];
//public void processFile(String commonWords) {
// wordArray = commonWords.split(",");
//private String[] loadFileList() {
// try
// fileName = "C:\\Documents and Settings\\mfleming\\Desktop\\Wordlist";
// File file = new File("C:\\Documents and
// Settings\\mfleming\\Desktop\\Wordlist");
// if(file.exists());
// Scanner scan = new Scanner(file);
// while(scan.hasNext())
// String word = scan.next();
// processFile(word);
// } catch (Exception e)
// e.printStackTrace();
// return wordArray;
// public void add() {
// try {
// Scanner s = new Scanner(new File("Wordlist"));
// while (s.hasNext())
// } catch (Exception e) {
private String showWord() {
int k;
String temp = "";
for (k = 0; k < word.length; k++) {
temp +=word[k];
// System.out.print(word[k] + " ");
return temp;
// return showWord();
// System.out.println(" \nYou have exactly " + (GUESSES - Misses)
// + " guesses left! Time is running out! Cue Music LOL ");
private boolean wordGuessed() {
int a;
for (a = 0; a < word.length; a++) {
if (word[a] == NADA) {
return false;
return true;
// .setIcon --- Put image.
public String play() {
clear();
String temp = "";
while (true) {
// showWord();
a.setText(showWord());
//May not have to return string.
// System.out
// .print("Your guess shall be? 1234567890abcdefhijklmnopqrstuvqxyz hA! Guess... it's simply up to you!");
String s = Blah.readString();
if (s.length() > 0) {
guess(s.charAt(0));
if (Misses >= GUESSES) {
// System.out.println("You killed your hangman because....");
// System.out.println(storeWord);
break;
} else if (wordGuessed()) {
// System.out.println("You win. You suck. LOL. ><");
// System.out.println(word);
break;
index = (index + 1) / myWords.length;
return temp;
// public String storeWord() {
// return SW;
public static final void main(String args[]) {
hmg hmg = new hmg();
hmg.play();
private class MousePressedListener implements MouseListener {
public void mousePressed(MouseEvent e) {
if (e.getButton() == e.BUTTON1) {
((JButton) e.getSource()).setText("X");
if (e.getButton() == e.BUTTON3) {
((JButton) e.getSource()).setText("O");
* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
* (non-Javadoc)
* @see java.awt.Component#getAccessibleContext()
public AccessibleContext getAccessibleContext() {
// TODO Auto-generated method stub
return super.getAccessibleContext();
* (non-Javadoc)
* @see javax.swing.JPanel#getUI()
public PanelUI getUI() {
// TODO Auto-generated method stub
return super.getUI();
* (non-Javadoc)
* @see javax.swing.JComponent#getUIClassID()
public String getUIClassID() {
// TODO Auto-generated method stub
return super.getUIClassID();
* (non-Javadoc)
* @see java.awt.Component#paramString()
protected String paramString() {
// TODO Auto-generated method stub
return super.paramString();
* (non-Javadoc)
* @see javax.swing.JPanel#setUI(javax.swing.plaf.PanelUI)
public void setUI(PanelUI arg0) {
// TODO Auto-generated method stub
super.setUI(arg0);
* (non-Javadoc)
* @see javax.swing.JComponent#updateUI()
public void updateUI() {
// TODO Auto-generated method stub
super.updateUI();
private String myWords[] = { "analysis", "approach", "area", "assessment",
"assume", "authority ", "available", "benefit ", "concept ",
"consistent", "constitutional", "context", "contract", "create",
"data", "definition", "derived ", "distribution ", "economic",
"environment ", "established", "estimate ", "evidence", "export",
"factors", "financial", "formula", "function", "identified",
"income", "indicate ", "individual ", "interpretation",
"involved", "issues", "labour", "legal", "legislation", "major ",
"method", "occur", "percent ", "period", "policy", "principle",
"procedure", "process", "required", "research", "response", "role",
"section", "sector", "significant ", "similar", "source",
"specific", "structure", "theory", "variables", "achieve ",
"acquisition", "administration ", "affect", "appropriate ",
"aspects", "assistance ", "categories", "chapter", "commission",
"community", "complex ", "computer ", "conclusion", "conduct",
"consequences", "construction", "consumer ", "credit", "cultural ",
"design", "distinction", "elements ", "equation", "evaluation ",
"features ", "final", "focus", "impact", "injury", "institute ",
"investment", "items", "journal ", "maintenance", "normal",
"obtained ", "participation", "perceived ", "positive ",
"potential", "previous", "primary ", "purchase ", "range ",
"region", "regulations", "relevant ", "resident", "resources",
"restricted ", "security ", "sought", "select", "site",
"strategies", "survey", "text", "traditional", "transfer",
"alternative", "circumstances ", "comments", "compensation",
"components", "consent", "considerable", "constant ",
"constraints", "contribution", "convention ", "coordination",
"core", "corporate ", "corresponding", "criteria", "deduction",
"demonstrate ", "document", "dominant", "emphasis ", "ensure",
"excluded", "framework ", "funds", "illustrated ", "immigration",
"implies", "initial ", "instance ", "interaction", "justification",
"layer", "link", "location", "maximum ", "minorities", "negative ",
"outcomes", "partnership", "philosophy ", "physical ",
"proportion ", "published ", "reaction", "registered ", "reliance",
"removed", "scheme", "sequence", "sex", "shift", "specified ",
"sufficient", "task", "technical ", "techniques", "technology",
"validity", "volume", "access", "adequate", "annual", "apparent",
"approximated", "attitudes ", "attributed ", "civil", "code",
"commitment ", "communication", "concentration", "conference ",
"contrast ", "cycle", "debate", "despite ", "dimensions ",
"domestic ", "emerged ", "error", "ethnic", "goals", "granted",
"hence", "hypothesis ", "implementation", "implications",
"imposed", "integration", "internal ", "investigation", "job",
"label", "mechanism ", "obvious", "occupational ", "option",
"output", "overall ", "parallel", "parameters", "phase",
"predicted", "principal", "prior", "professional", "project",
"promote", "regime", "resolution ", "retained", "series",
"statistics ", "status", "stress", "subsequent", "sum", "summary",
"undertaken ", "academic ", "adjustment ", "alter ", "amendment ",
"aware ", "capacity ", "challenge ", "clause ", "compounds ",
"conflict ", "consultation ", "contact ", "decline ",
"discretion ", "draft ", "enable ", "energy ", "enforcement ",
"entities ", "equivalent ", "evolution ", "expansion ",
"exposure ", "external ", "facilitate ", "fundamental ",
"generated ", "generation ", "image ", "liberal", "licence ",
"logic ", "marginal ", "medical ", "mental ", "modified ",
"monitoring ", "network ", "notion ", "objective ", "orientation ",
"perspective ", "precise ", "prime ", "psychology ", "pursue ",
"ratio ", "rejected ", "revenue ", "stability ", "styles ",
"substitution ", "sustainable", "symbolic ", "target ",
"transition ", "trend ", "version ", "welfare ", "whereas ",
"abstract ", "accurate ", "acknowledged ", "aggregate ",
"allocation ", "assigned ", "attached ", "author ", "bond ",
"brief ", "capable ", "cited ", "cooperative ", "discrimination ",
"display ", "diversity ", "domain ", "edition ", "enhanced ",
"estate ", "exceed ", "expert ", "explicit ", "federal ", "fees ",
"flexibility ", "furthermore ", "gender ", "ignored ",
"incentive ", "incidence ", "incorporated ", "index ",
"inhibition ", "initiatives ", "input ", "instructions ",
"intelligence ", "interval ", "lecture ", "migration ", "minimum ",
"ministry ", "motivation ", "neutral ", "nevertheless ",
"overseas ", "preceding ", "presumption ", "rational ",
"recovery ", "revealed ", "scope ", "subsidiary ", "tapes ",
"trace ", "transformation ", "transport ", "underlying ",
"utility ", "adaptation ", "adults ", "advocate ", "aid ",
"channel ", "chemical", "classical ", "comprehensive ",
"comprise ", "confirmed ", "contrary ", "converted ", "couple ",
"decades ", "definite", "deny ", "differentiation ", "disposal ",
"dynamic ", "eliminate ", "empirical ", "equipment ", "extract ",
"file ", "finite ", "foundation ", "global ", "grade ",
"guarantee ", "hierarchical ", "identical ", "ideology ",
"inferred ", "innovation ", "insert ", "intervention ",
"isolated ", "media ", "mode ", "paradigm ", "phenomenon ",
"priority ", "prohibited ", "publication ", "quotation ",
"release ", "reverse ", "simulation ", "solely ", "somewhat ",
"submitted ", "successive ", "survive ", "thesis ", "topic ",
"transmission ", "ultimately ", "unique ", "visible ",
"voluntary ", "abandon ", "accompanied ", "accumulation ",
"ambiguous ", "appendix ", "appreciation ", "arbitrary ",
"automatically ", "bias ", "chart ", "clarity", "conformity ",
"commodity ", "complement ", "contemporary ", "contradiction ",
"crucial ", "currency ", "denote ", "detected ", "deviation ",
"displacement ", "dramatic ", "eventually ", "exhibit ",
"exploitation ", "fluctuations ", "guidelines ", "highlighted ",
"implicit ", "induced ", "inevitably ", "infrastructure ",
"inspection ", "intensity ", "manipulation ", "minimised ",
"nuclear ", "offset ", "paragraph ", "plus ", "practitioners ",
"predominantly ", "prospect ", "radical ", "random ",
"reinforced ", "restore ", "revision ", "schedule ", "tension ",
"termination ", "theme ", "thereby ", "uniform ", "vehicle ",
"via ", "virtually ", "widespread ", "visual ", "accommodation ",
"analogous ", "anticipated ", "assurance ", "attained ", "behalf ",
"bulk ", "ceases ", "coherence ", "coincide ", "commenced ",
"incompatible ", "concurrent ", "confined ", "controversy ",
"conversely ", "device ", "devoted ", "diminished ", "distorted",
"distortion", "equal", "figures", "duration ", "erosion ",
"ethical ", "format ", "founded ", "inherent ", "insights ",
"integral ", "intermediate ", "manual ", "mature ", "mediation ",
"medium ", "military ", "minimal ", "mutual ", "norms ",
"overlap ", "passive ", "portion ", "preliminary ", "protocol ",
"qualitative ", "refine ", "relaxed ", "restraints ",
"revolution ", "rigid ", "route ", "scenario ", "sphere ",
"subordinate ", "supplementary ", "suspended ", "team ",
"temporary ", "trigger ", "unified ", "violation ", "vision ",
"adjacent ", "albeit ", "assembly ", "collapse ", "colleagues ",
"compiled ", "conceived ", "convinced ", "depression ",
"encountered ", "enormous ", "forthcoming ", "inclination ",
"integrity ", "intrinsic ", "invoked ", "levy ", "likewise ",
"nonetheless ", "notwithstanding ", "odd ", "ongoing ", "panel ",
"persistent ", "posed ", "reluctant ", "straightforward ",
"undergo ", "whereby ", "noob", "frag", "punish", "lamer", "noobs",
"knife", "shank", "humvee", "sniper", "don't", "run", "you'll",
"only", "die", "tired", "LOL", "ROFL", "GG", "FTW", "indeed",
"sure", "yeah", "yea", "hi", "hello", };
DRIVER CLASS
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
public class HangManGuiTest {
public static void main(String[] args) {
// hangmangui hmg = new hangmangui();
hmg hmg = new hmg();
JFrame frame = new JFrame("Hangman! DJ Joker[8]Baller");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(hmg);
frame.pack();
frame.show();
// JFrame j = new JFrame();
// Listeners - Control everything - Call stuff from hmg.
// frame.getContentPane().add(hmg);
// j.setSize(500, 500);
// j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// j.setVisible(true);
hmg.play();
Message was edited by:
joker8ballerHey! Thanks for the tip...
Anyways, I fixed all of the errors (T hank god) and now all I have t o do is add the text to the gui. Help for adding the text into the gui. When I run it, it runs a gui, and it shows the spaces, but when I put in input.. nothing shows up and nothing plays.
So I'm going to use a.setText... for showWord and and play()... Is there anything else I woiuld need to do?
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.Random;
import java.util.Scanner;
import javax.accessibility.AccessibleContext;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.plaf.PanelUI;
public class hmg extends JPanel {
private char[] word;
private int Misses;
private int myWordIndex;
private int index;
private boolean[] used;
protected Image[] i = new Image[8];
protected Image[] s = new Image[3];
private final static char NADA = '_';
private final static int GUESSES = 8;
private String fileName;
i[0] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang1.jpg");
i[1] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang2.jpg");
i[2] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang3.jpg");
i[3] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hange4.jpg");
i[4] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang5.jpg");
i[5] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang6.jpg");
i[6] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang7.jpg");
i[7] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hang8.jpg");
s[0] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
s[1] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
s[2] = Toolkit.getDefaultToolkit().getImage(
"C:\\Documents and Settings\\mfleming\\Desktop\\hacks.jpg");
protected int x = 0;
protected ImageIcon icon = new ImageIcon(i[x++]);
protected ImageIcon icon2 = new ImageIcon(s[x++]);
private JLabel j = new JLabel(icon);
private JButton b = new JButton();
private JLabel a = new JLabel();
private String[] wordArray;
private String wordChosen;
public void paintComponent(Graphics g) {
super.paintComponents(g);
public hmg() {
this.add(j);
JButton guess = new JButton("The Click of Faith!");
this.add(guess, BorderLayout.WEST);
guess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!(x == i.length)) {
icon = new ImageIcon(i[x++]);
j.setIcon(icon);
JButton guess2 = new JButton("Click here if your almost dead! ");
this.add(guess2, BorderLayout.WEST);
guess2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
icon2 = new ImageIcon(s[x++]);
j.setIcon(icon);
// this.add(a, BorderLayout.SOUTH);
// a.setText(clear());
// a.setText(showWord());
// a.setText(play());
Misses = 0;
index = 0;
used = new boolean[Character.MAX_VALUE];
// public void actionPerformed(ActionEvent arg0) {
// if (!(x == i.length)) {
// icon = new ImageIcon(i[x++]);
// j.setIcon(icon);
private void clear() {
int k;
for (k = 0; k < Character.MAX_VALUE; k++) {
used[k] = false;
word = new char[myWords[myWordIndex].length()];
System.out.println(word.length);
for (k = 0; k < word.length; k++) {
word[k] = NADA;
private void guess(char ch) {
int b;
boolean charFound = false;
ch = Character.toLowerCase(ch);
for (b = 0; b < word.length; b++) {
if (!used[ch] && myWords[index].charAt(b) == ch) {
word[b] = ch;
charFound = true;
if (!used[ch] && !charFound) {
Misses++;
used[ch] = true;
private void chooseRandomWord()
// myWords[];
// loadFileList();
Random generator = new Random();
int x = generator.nextInt(wordArray.length);
wordChosen = wordArray[x];
//public void processFile(String commonWords) {
// wordArray = commonWords.split(",");
//private String[] loadFileList() {
// try
// fileName = "C:\\Documents and Settings\\mfleming\\Desktop\\Wordlist";
// File file = new File("C:\\Documents and
// Settings\\mfleming\\Desktop\\Wordlist");
// if(file.exists());
// Scanner scan = new Scanner(file);
// while(scan.hasNext())
// String word = scan.next();
// processFile(word);
// } catch (Exception e)
// e.printStackTrace();
// return wordArray;
// public void add() {
// try {
// Scanner s = new Scanner(new File("Wordlist"));
// while (s.hasNext())
// } catch (Exception e) {
private String showWord() {
int k;
String temp = "";
for (k = 0; k < word.length; k++) {
temp +=word[k];
// System.out.print(word[k] + " ");
return temp;
// return showWord();
// System.out.println(" \nYou have exactly " + (GUESSES - Misses)
// + " guesses left! Time is running out! Cue Music LOL ");
private boolean wordGuessed() {
int a;
for (a = 0; a < word.length; a++) {
if (word[a] == NADA) {
return false;
return true;
// .setIcon --- Put image.
public String play() {
clear();
String temp = "";
while (true) {
// showWord();
a.setText(showWord());
//May not have to return string.
JOptionPane.showInputDialog("Your guess shall be? 1234567890abcdefhijklmnopqrstuvqxyz hA! Guess... its simply up to you!");
// System.out
// .print("Your guess shall be? 1234567890abcdefhijklmnopqrstuvqxyz hA! Guess... it's simply up to you!");
String s = Blah.readString();
if (s.length() > 0) {
guess(s.charAt(0));
if (Misses >= GUESSES) {
JOptionPane.showMessageDialog(null,"You killed your hangman because....");
// System.out.println("You killed your hangman because....");
// System.out.println(storeWord);
break;
} else if (wordGuessed()) {
JOptionPane.showMessageDialog(null, "You win. You suck. LOL. ><");
// System.out.println("You win. You suck. LOL. ><");
// System.out.println(word);
break;
index = (index + 1) / myWords.length;
return temp;
// public String storeWord() {
// return SW;
public static final void main(String args[]) {
hmg hmg = new hmg();
hmg.play();
* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
* (non-Javadoc)
* @see java.awt.Component#getAccessibleContext()
public AccessibleContext getAccessibleContext() {
// TODO Auto-generated method stub
return super.getAccessibleContext();
* (non-Javadoc)
* @see javax.swing.JPanel#getUI()
public PanelUI getUI() {
// TODO Auto-generated method stub
return super.getUI();
* (non-Javadoc)
* @see javax.swing.JComponent#getUIClassID()
public String getUIClassID() {
// TODO Auto-generated method stub
return super.getUIClassID();
* (non-Javadoc)
* @see java.awt.Component#paramString()
protected String paramString() {
// TODO Auto-generated method stub
return super.paramString();
* (non-Javadoc)
* @see javax.swing.JPanel#setUI(javax.swing.plaf.PanelUI)
public void setUI(PanelUI arg0) {
// TODO Auto-generated method stub
super.setUI(arg0);
* (non-Javadoc)
* @see javax.swing.JComponent#updateUI()
public void updateUI() {
// TODO Auto-generated method stub
super.updateUI();
private String myWords[] = { "approach", "area", "assessment",
"assume", "authority ", "available", "benefit ", "concept ",
"consistent", "constitutional", "context", "contract", "create",
"data", "definition", "derived ", "distribution ", "economic",
"environment ", "established", "estimate ", "evidence", "export",
"factors", "financial", "formula", "function", "identified",
"income", "indicate ", "individual ", "interpretation",
"involved", "issues", "labour", "legal", "legislation", "major ",
"method", "occur", "percent ", "period", "policy", "principle",
"procedure", "process", "required", "research", "response", "role",
"section", "sector", "significant ", "similar", "source",
"specific", "structure", "theory", "variables", "achieve ",
"acquisition", "administration ", "affect", "appropriate ",
"aspects", "assistance ", "categories", "chapter", "commission",
"community", "complex ", "computer ", "conclusion", "conduct",
"consequences", "construction", "consumer ", "credit", "cultural ",
"design", "distinction", "elements ", "equation", "evaluation ",
"features ", "final", "focus", "impact", "injury", "institute ",
"investment", "items", "journal ", "maintenance", "normal",
"obtained ", "participation", "perceived ", "positive ",
"potential", "previous", "primary ", "purchase ", "range ",
"region", "regulations", "relevant ", "resident", "resources",
"restricted ", "security ", "sought", "select", "site",
"strategies", "survey", "text", "traditional", "transfer",
"alternative", "circumstances ", "comments", "compensation",
"components", "consent", "considerable", "constant ",
"constraints", "contribution", "convention ", "coordination",
"core", "corporate ", "corresponding", "criteria", "deduction",
"demonstrate ", "document", "dominant", "emphasis ", "ensure",
"excluded", "framework ", "funds", "illustrated ", "immigration",
"implies", "initial ", "instance ", "interaction", "justification",
"layer", "link", "location", "maximum ", "minorities", "negative ",
"outcomes", "partnership", "philosophy ", "physical ",
"proportion ", "published ", "reaction", "registered ", "reliance",
"removed", "scheme", "sequence", "sex", "shift", "specified ",
"sufficient", "task", "technical ", "techniques", "technology",
"validity", "volume", "access", "adequate", "annual", "apparent",
"approximated", "attitudes ", "attributed ", "civil", "code",
"commitment ", "communication", "concentration", "conference ",
"contrast ", "cycle", "debate", "despite ", "dimensions ",
"domestic ", "emerged ", "error", "ethnic", "goals", "granted",
"hence", "hypothesis ", "implementation", "implications",
"imposed", "integration", "internal ", "investigation", "job",
"label", "mechanism ", "obvious", "occupational ", "option",
"output", "overall ", "parallel", "parameters", "phase",
"predicted", "principal", "prior", "professional", "project",
"promote", "regime", "resolution ", "retained", "series",
"statistics ", "status", "stress", "subsequent", "sum", "summary",
"undertaken ", "academic ", "adjustment ", "alter ", "amendment ",
"aware ", "capacity ", "challenge ", "clause ", "compounds ",
"conflict ", "consultation ", "contact ", "decline ",
"discretion ", "draft ", "enable ", "energy ", "enforcement ",
"entities ", "equivalent ", "evolution ", "expansion ",
"exposure ", "external ", "facilitate ", "fundamental ",
"generated ", "generation ", "image ", "liberal", "licence ",
"logic ", "marginal ", "medical ", "mental ", "modified ",
"monitoring ", "network ", "notion ", "objective ", "orientation ",
"perspective ", "precise ", "prime ", "psychology ", "pursue ",
"ratio ", "rejected ", "revenue ", "stability ", "styles ",
"substitution ", "sustainable", "symbolic ", "target ",
"transition ", "trend ", "version ", "welfare ", "whereas ",
"abstract ", "accurate ", "acknowledged ", "aggregate ",
"allocation ", "assigned ", "attached ", "author ", "bond ",
"brief ", "capable ", "cited ", "cooperative ", "discrimination ",
"display ", "diversity ", "domain ", "edition ", "enhanced ",
"estate ", "exceed ", "expert ", "explicit ", "federal ", "fees ",
"flexibility ", "furthermore ", "gender ", "ignored ",
"incentive ", "incidence ", "incorporated ", "index ",
"inhibition ", "initiatives ", "input ", "instructions ",
"intelligence ", "interval ", "lecture ", "migration ", "minimum ",
"ministry ", "motivation ", "neutral ", "nevertheless ",
"overseas ", "preceding ", "presumption ", "rational ",
"recovery ", "revealed ", "scope ", "subsidiary ", "tapes ",
"trace ", "transformation ", "transport ", "underlying ",
"utility ", "adaptation ", "adults ", "advocate ", "aid ",
"channel ", "chemical", "classical ", "comprehensive ",
"comprise ", "confirmed ", "contrary ", "converted ", "couple ",
"decades ", "definite", "deny ", "differentiation ", "disposal ",
"dynamic ", "eliminate ", "empirical ", "equipment ", "extract ",
"file ", "finite ", "foundation ", "global ", "grade ",
"guarantee ", "hierarchical ", "identical ", "ideology ",
"inferred ", "innovation ", "insert ", "intervention ",
"isolated ", "media ", "mode ", "paradigm ", "phenomenon ",
"priority ", "prohibited ", "publication ", "quotation ",
"release ", "reverse ", "simulation ", "solely ", "somewhat ",
"submitted ", "successive ", "survive ", "thesis ", "topic ",
"transmission ", "ultimately ", "unique ", "visible ",
"voluntary ", "abandon ", "accompanied ", "accumulation ",
"ambiguous ", "appendix ", "appreciation ", "arbitrary ",
"automatically ", "bias ", "chart ", "clarity", "conformity ",
"commodity ", "complement ", "contemporary ", "contradiction ",
"crucial ", "currency ", "denote ", "detected ", "deviation ",
"displacement ", "dramatic ", "eventually ", "exhibit ",
"exploitation ", "fluctuations ", "guidelines ", "highlighted ",
"implicit ", "induced ", "inevitably ", "infrastructure ",
"inspection ", "intensity ", "manipulation ", "minimised ",
"nuclear ", "offset ", "paragraph ", "plus ", "practitioners ",
"predominantly ", "prospect ", "radical ", "random ",
"reinforced ", "restore ", "revision ", "schedule ", "tension ",
"termination ", "theme ", "thereby ", "uniform ", "vehicle ",
"via ", "virtually ", "widespread ", "visual ", "accommodation ",
"analogous ", "anticipated ", "assurance ", "attained ", "behalf ",
"bulk ", "ceases ", "coherence ", "coincide ", "commenced ",
"incompatible ", "concurrent ", "confined ", "controversy ",
"conversely ", "device ", "devoted ", "diminished ", "distorted",
"distortion", "equal", "figures", "duration ", "erosion ",
"ethical ", "format ", "founded ", "inherent ", "insights ",
"integral ", "intermediate ", "manual ", "mature ", "mediation ",
"medium ", "military ", "minimal ", "mutual ", "norms ",
"overlap ", "passive ", "portion ", "preliminary ", "protocol ",
"qualitative ", "refine ", "relaxed ", "restraints ",
"revolution ", "rigid ", "route ", "scenario ", "sphere ",
"subordinate ", "supplementary ", "suspended ", "team ",
"temporary ", "trigger ", "unified ", "violation ", "vision ",
"adjacent ", "albeit ", "assembly ", "collapse ", "colleagues ",
"compiled ", "conceived ", "convinced ", "depression ",
"encountered ", "enormous ", "forthcoming ", "inclination ",
"integrity ", "intrinsic ", "invoked ", "levy ", "likewise ",
"nonetheless ", "notwithstanding ", "odd ", "ongoing ", "panel ",
"persistent ", "posed ", "reluctant ", "straightforward ",
"undergo ", "whereby ", "noob", "frag", "punish", "lamer", "noobs",
"knife", "shank", "humvee", "sniper", "don't", "run", "you'll",
"only", "die", "tired", "LOL", "ROFL", "GG", "FTW", "indeed",
"sure", "yeah", "yea", "hi", "hello", };
}Message was edited by:
joker8baller -
I need help with my hangman project
I'm working on a project where we are developing a text based version of the game hangman. For every project we add a new piece to the game. Well for my project i have to test for a loser and winner for the game and take away a piece of the game when the user guesses incorrectly. these are the instrcutions given by my professor:
This semester we will develop a text based version of the Game Hangman. In each project we will add a new a piece to the game. In project 4 you will declare the 'figure', 'disp', and 'soln' arrays to be attributes of the class P4. However do not create the space for the arrays until main (declaration and creation on separate lines). If the user enters an incorrect guess, remove a piece of the figure, starting with the right leg (looking at the figure on the screen, the backslash is the right leg) and following this order: the left leg (forward slash), the right arm (the dash or minus sign), the left arm (the dash or minus sign), the body (vertical bar), and finally the head (capital O).
Not only will you need to check for a winner, but now you will also check to see if all the parts of the figure have been removed, checking to see if the user has lost. If the user has lost, print an error message and end the program. You are required to complete the following operations using for loops:
intializing appropriate (possible) variables, testing to see if the user has guessed the correct solution, testing to see if the user has guessed a correct letter in the solution, and determining / removing the next appropriate part of the figure. All other parts of the program will work as before.
Declare figure, disp, and soln arrays as attributes of the class
Creation of the arrays will remain inside of main
Delete figure parts
Check for loss (all parts removed)
Implement for loops
Init of appropriate arrays
Test for winner
Test if guess is part of the solution
Removal of correct position from figure
Output must be
C:\jdk1.3.1\bin>java P3
|
|
O
-|-
Enter a letter: t
|
|
O
-|-
t _ _ t
Enter a letter: a
|
|
O
-|-
t _ _ t
Enter a letter: e
|
|
O
-|-
t e _ t
Enter a letter: l
|
|
O
-|-
t e _ t
Enter a letter: s
|
|
O
-|-
t e s t
YOU WIN!
C:\jdk1.3.1\bin>java P3
Pete Dobbins
Period 5, 7, & 8
|
|
O
-|-
Enter a letter: a
|
|
O
-|-
Enter a letter: b
|
|
O
-|-
Enter a letter: c
|
|
O
-|
Enter a letter: d
|
|
O
|
Enter a letter: e
|
|
O
|
_ e _ _
Enter a letter: f
|
|
O
_ e _ _
Enter a letter: g
|
|
_ e _ _
YOU LOSE!
Well i have worked on this and come up with this so far and am having great dificulty as to i am struggling with this class. the beginning is just what i was suppose to comment out. We are suppose to jave for loops for anything that can be put into a for loop also.
/* Anita Desai
Period 5
P4 description:
1.Declare figure, disp, and soln arrays as attributes of the class
2.Creation of the arrays will remain inside of main
3.Delete figure parts
4.Check for loss (all parts removed)
5.Implement for loops
A.Init of appropriate arrays
B.Test for winner
C.Test if guess is part of the solution
D.Removal of correct position from figure
//bringing the java Input / Output package
import java.io.*;
//declaring the program's class name
class P4
//declaring arrays as attributes of the class
public static char figure[];
public static char disp[];
public static char soln[];
// declaring the main method within the class P4
public static void main(String[] args)
//print out name and period
System.out.println("Anita Desai");
System.out.println("Period 5");
//creating the arrays
figure = new char[6];
soln = new char[4];
disp = new char[4];
figure[0] = 'O';
figure[1] = '-';
figure[2] = '|';
figure[3] = '-';
figure[4] = '<';
figure[5] = '>';
soln[0] = 't';
soln[1] = 'e';
soln[2] = 's';
soln[3] = 't';
//for loop for disp variables
int i;
for(i=0;i<4;i++)
disp='_';
//Using a while loop to control program flow
while(true)
//drawing the board again!
System.out.println("-----------");
System.out.println(" |");
System.out.println(" |");
System.out.println(" " + figure[0]);
System.out.println(" " + figure[1] + figure[2] + figure[3]);
System.out.println(" " + figure[4] + " " + figure[5]);
System.out.println("\n " + disp[0] + " " + disp[1] + " " + disp[2] + " " + disp[3]);
//getting input
System.out.print("Enter a letter: ");
//declaring a string variable
String data = " ";
// call the readString method
data = readString();
//retrieves the character at position zero
char temp;
temp=data.charAt(0);
int h;
for(h=0;h<4;h++)
if(temp==soln[h])
disp[h]=soln[h];
return;
if(disp[h]==soln[h])
System.out.println("You Win");
else
for(h=0;h<6;h++)
if(temp!=soln[h])
figure[h] = ' ';
return;
if(disp[h]!=soln[h])
System.out.println("You Lose");
///Test if statements to replace user input with soln if correct
int j;
for(j=0;j<4;j++)
if(temp==soln[j])
disp[j]=soln[j];
//declared the readString method, we specified that it would
//be returning a string
public static String readString()
//make connection to the command line
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//declaring a string variable
String s = " ";
//try to do something that might cause an error
try
//reading in a line from the user
s = br.readLine();
catch(IOException ex)
//if the error occurs, we will handle it in a special way
//give back to the place that called us
//the string we read in
return s;
If anyone cann please help me i would greatly appreciate it. I have an exam coming up on wednesday also so i really need to understand this material and see where my mistakes are. If anyoone knows how to delete the parts of the hangman figure one by one each time user guessesincorrectly i would appreciate it greatly. Any other help in solving this program would be great help. thanks.Hi thanks for responding. Well to answer some of your questions. The professors instructions are the first 2 paragraphs of my post up until the ende of the output which is You lose!. I have to have the same output as the professor stated which is testing for a winner and loser. Yes the program under the output is what i have written so far. This is the 3rd project and in each we add a little piece to the game. I have no errors when i run the program my problem is when it runs it just prints the hangman figure, disp and then asks user ot enter a letter. Well once i enter a letter it just prints that letter to the screen and the prgram ends.
As far as the removal of the parts. the solution is TEST. When the user enters a letter lets say Tthen the figure should display again with the disp and filled in solution with T. Then ask for a letter again till user has won and TEST has been guessed correctly. Well then we have to test for a loser. So lets the user enters a R, well then the right leg of the hangman figure should be blank indicating a D the other leg will be blank until the parts are removed and then You lose will be printed to the screen.
For the program i am suppose to use a FOR LOOPto test for a winner, to remove the parts one at a time, and to see if the parts have been removed if the user guesses incorrectly.
so as u can see in what i have come up with so far i have done this to test for a winner and loser:
//declaring a string variable
String data = " ";
// call the readString method
data = readString();
//retrieves the character at position zero
char temp;
temp=data.charAt(0);
int h;
for(h=0;h<4;h++)
if(temp==soln[h])
disp[h]=soln[h];
return;
if(disp[h]==soln[h])
System.out.println("You Win");
else
for(h=0;h<6;h++)
if(temp!=soln[h])
figure[h] = ' ';
return;
if(disp[h]!=soln[h])
System.out.println("You Lose");
Obviously i have not writtern the for loops to do what is been asked to have the proper output. the first for loop i am trying to say if the user input is equal to the soln thencontinue till all 4 disp are guessed correctly and if all the disp=soln then the scrren prints you win.
then for the incorrect guesses i figured if the user input does not equal the soln then to leave a blank for the right leg and so on so i have a blank space for the figure as stated
:for(h=0;h<6;h++)
if(temp!=soln[h])
figure[h] = ' ';
well this doesnt work and im not getting the output i wanted and am very confused about what to do. I tried reading my book and have been trying to figure this out all night but i am unable to. I'm going to try for another hr then head to bed lol its 4am. thanks for your help. Sorry about posting in two different message boards. I wont' do it again. thanks again, anita -
Good evening all,
I have written the following code for a CS assignment. All seems well except for a few issues with the alignment of the ASCII art but I am still tweaking it a bit. The major problem is if the user presses the enter button instead of using the mouse several body parts are shown regardless if the letter entered is part of the hidden word or not. It doesn't do it with each word but only every other one. I'd appreciate being pointed in the right direction so I can get it to run either way (enter and/or mouse). Thanks in advance.
import java.util.*;
import javax.swing.*;
public class Hangman
public static void main (String [] args)
//declaration of variables
boolean playing = true; // true while playing game
boolean correct = false; // false when ending game
int i; // temp variable for index loop
int length; // length of secret word
int guessRemaining; // wrong guesses remaining
String c = ""; // temp variable for character
String word; // secret word
String hiddenLetters = ""; // use to hide letters of word
String wrongLetters = ""; // letters not in secret word
String temp = ""; // temp variable for Strings
guessRemaining = 6; // start w/ no wrong guesses
word = JOptionPane.showInputDialog(null, "Enter the secret word.");
length = word.length(); // Player 1 enters a word.
for (i=0; i < length; i++)
hiddenLetters = hiddenLetters + "-"; // Letters of hidden word replaced with -
while (playing == true){ // Player 2 begins game
correct = false;
if (guessRemaining==6){
c = JOptionPane.showInputDialog(null,"\t---------- \n\t | | \n\t | \n\t | \n\t | \n\t | \n\t=======\n"+
wrongLetters + "\n"+ hiddenLetters);
if (guessRemaining==5)
c = JOptionPane.showInputDialog(null,"\t---------- \n\t | | \n\t | () \n\t | \n\t | \n\t | \n\t=======\n"+
wrongLetters + "\n"+ hiddenLetters);
if (guessRemaining==4)
c = JOptionPane.showInputDialog(null,"\t---------- \n\t | | \n\t | () \n\t | | \n\t | \n\t | \n\t=======\n"+
wrongLetters + "\n"+ hiddenLetters);
if (guessRemaining==3)
c = JOptionPane.showInputDialog(null,"\t---------- \n\t | | \n\t | () \n\t | |--\n\t | \n\t | \n\t=======\n"+
wrongLetters + "\n"+ hiddenLetters);
if (guessRemaining==2)
c = JOptionPane.showInputDialog(null,"\t---------- \n\t | | \n\t | () \n\t | --|-- \n\t | \n\t | \n\t | \n\t=======\n"+
wrongLetters + "\n"+ hiddenLetters);
if (guessRemaining==1)
c = JOptionPane.showInputDialog(null,"\t---------- \n\t | | \n\t | () \n\t | --|-- \n\t | \n\t | \n\t | \n\t=======\n"+
wrongLetters + "\n"+ hiddenLetters);
if (guessRemaining==0){
JOptionPane.showMessageDialog(null,"\t---------- \n\t | | \n\t | () \n\t | --|-- \n\t | | \n\t | \n=======\n\n+YOU'VE BEEN\n HANGED!!!\n"+ wrongLetters + "\n"+ hiddenLetters);
playing = false;
for (i = 0; i < length; i++)
if (hiddenLetters.charAt(i)!= '-'){ // '-' replaced w/ correct letter
temp = temp + hiddenLetters.charAt(i);}
else if (word.charAt(i)==c.charAt(0)){
temp = temp + c.charAt(0);
correct = true;
else {
temp = temp + "-";
hiddenLetters = temp;
temp = "";
if (correct == false){
wrongLetters = wrongLetters + c;
guessRemaining = guessRemaining - 1;
if (hiddenLetters.equals(word)){
JOptionPane.showMessageDialog(null, "Awesome Job! You Won The Game!");
playing = false;
}// End programFlounder,
I guess I should have been more explicit in my question. I certainly wasn't looking for someone to fix the code for me or spoonfeed me the answer. I was only wanting to be pointed in the right direction about how to deal with this. I haven't encountered this type of error before and after testing it over 50 times and trying everything I've learned in the past few months and doing a search on here and reviewing the tutorials I was still stuck. Sorry about that. Thanks for the info and the advice regarding the other line of code. I really do appreciate the help. -
Plz help me on the hangman code
Consider the venerable "hangman" game, in which a player attempts to guess a word one letter at a time. If you are unfamiliar with hangman, simply google it; you'll be playing in no time.
Consider the following abstract view of hangman. The input is an unknown word and a sequence of character guesses. There is also an implicit parameter, which is the number of incorrect guesses that may be made before losing the game. Even though you wouldn't implement an interactive hangman game this way, let's model this as:
static public int hangman (String puzzle, String guesses, int limit)
Requires: puzzle != null, guesses != null, limit >=0
Effects: returns the number of the guess that solves the
puzzle within the given limit on incorrect guesses.
If the puzzle is not solved within the limit, returns -1.
e.g.
hangman ("cat", "abct", 1) is 4 (solved)
hangman ("cat", "abct", 0) is -1 (hit the limit)
hangman ("cat", "abcd", 5) is -1 (gave up)
I wrote the following code but it gives me an error of array index out of bounds exception though it compiles correctly. If someone can help me in correcting the code or point out my mistake.
public class hangman
public static int hang(String puz,String gue,int lim)
int i,j,flag=0,ret=0;
char p[],g[];
p=puz.toCharArray();
g=gue.toCharArray();
one:
for(i=0;i<g.length;i++)
two:
for(j=0;j<p.length;j++)
if(g==p[j])
//take the element off the p array and resize p
if(p.length==1)
break one;
else
char b[]=new char[p.length];
for(int k=j+1;k<p.length;k++)
p[k-1]=p[k];
b=p;
p=new char[p.length-1];
for(int l=0;i<p.length;l++)
p[l]=b[l];
continue one;
else
if(j==p.length-1)
flag++;
else
continue two;
if(flag>lim)
return -1;
else
return 0;
public static void main(String args[])
int ret;
ret=hang("cat","abct",1);
System.out.println(ret);I wrote the following code but it gives me an error
of array index out of bounds exception though it
compiles correctly.I just want to point out a fundamental misunderstanding that this statement suggests you have.
Compiling just converts your source code into equivalent bytecode. The only errors you'll get during compilation are if the syntax is bad (like you forgot a semicolon, misspelled a method name, have an extra closing brace, etc.) or if you're trying to ues a vairialbe that the copmiler can't be sure will have been initialized, etc.
Compilation does NOT execute your code, and it has no way to determine the logical problem with, for instance, int[] arr = new int[0];
int x = arr[999]; The fact that x has zero elements and you're trying to access element 999 only comes to light at execution time.
So "I get an error at runtime even though it compiles fine" is kind of meaningless.
Note that I'm not trying to pick on you here. I just want to shift your thinking away from this fundamental misconception you seem to have. -
Is there anyway to change the font for the letters in the hangman widget? I love the game, but the font is really hard to read. I am working with low level literacy learners, and this would be a fantastic game, but the font has to be cleaner so it is more accessible. For that matter - is there a way to change fonts in ANY of the widgets? Again, it goes to the accessibility factor, and some fonts are just so tiny (or in some cases too big) for our resources. Would be nice to see Adobe work in customizations for this into the widgets.
Magritte,
First of all save any important notes that you may have using a word processing program.
Then find the widget-com.apple.widget.stickies.plist file in your Macintosh HD/Users/yourusername/Library/Preferences folder, drag it to the Desktop and log out/in or restart and let us know what happens.
;~) -
I have been working on this program for more than a week. It is a Hangman program that is supposed to get input from a dialog box when the Guess button is clicked. Then the frame should display the word like so -a--- if the word is "magic." It does not work. If it runs at all it displays some weird output like random letters and numbers. Any help would be greatly appreciated. import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
import java.lang.String;
import java.io.*;
public class HangmanGUI extends JFrame implements ActionListener
char[] word = {'m','a','g','i','c'};
String strword = "magic";
int guesses;
String guess;
char chguess;
JTextField Word = new JTextField(10);
JButton Guess = new JButton("Guess");
char[] GuessedSoFar= {'-','-','-','-','-'};
String ToDisplay;
public HangmanGUI()
setTitle( "-Hangman-" );
Word.setEditable( false );
getContentPane().setLayout(new FlowLayout());
getContentPane().add(Word);
getContentPane().add(Guess);
Guess.addActionListener( this );
public void actionPerformed( ActionEvent evt) //throws IOException
// The application
// try{
guess=JOptionPane.showInputDialog ("Enter a guess: ");
chguess=guess.charAt(0);
// catch(IOException ex ){
// Word.setText("Sorry");
int e=0;
for(int i = 0; i<=strword.length(); i++);{
if(chguess==strword.charAt(e)){
GuessedSoFar[e]=chguess;}
e++;
ToDisplay="";
for (int q=0; q<=strword.length();q++){
ToDisplay+=GuessedSoFar[q] ;
Word.setText(" "+ToDisplay);
public static void main ( String[] args ) throws IOException
HangmanGUI HangmanApp = new HangmanGUI() ;
WindowQuitter wquit = new WindowQuitter();
HangmanApp.addWindowListener( wquit );
HangmanApp.setSize( 200, 100 );
HangmanApp.setVisible( true );
class WindowQuitter extends WindowAdapter
public void windowClosing( WindowEvent e )
System.exit( 0 );
}well, try to change your code, so that the for things don't go up to the length of the String
import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
import java.lang.String;
import java.io.*;
public class HangmanGUI extends JFrame implements ActionListener {
char[] word = {'m','a','g','i','c'};
String strword = "magic";
int guesses;
String guess;
char chguess;
JTextField Word = new JTextField(10);
JButton Guess = new JButton("Guess");
char[] GuessedSoFar= {'-','-','-','-','-'};
String ToDisplay;
public HangmanGUI() {
setTitle( "-Hangman-" );
Word.setEditable( false );
getContentPane().setLayout(new FlowLayout());
getContentPane().add(Word);
getContentPane().add(Guess);
Guess.addActionListener( this );
public void actionPerformed( ActionEvent evt) {
guess=JOptionPane.showInputDialog ("Enter a guess: ");
chguess=guess.charAt(0);
int e=0;
for(int i = 0; i<strword.length(); i++) {
if(chguess==strword.charAt(e)){
GuessedSoFar[e]=chguess;}
e++;
ToDisplay="";
for (int q=0; q<strword.length();q++){
ToDisplay+=GuessedSoFar[q] ;
Word.setText(" "+ToDisplay);
public static void main ( String[] args ) throws IOException {
HangmanGUI HangmanApp = new HangmanGUI() ;
WindowQuitter wquit = new WindowQuitter();
HangmanApp.addWindowListener( wquit );
HangmanApp.setSize( 200, 100 );
HangmanApp.setVisible( true );
class WindowQuitter extends WindowAdapter {
public void windowClosing( WindowEvent e ){
System.exit( 0 );
} -
Issues with hangman activity in captivate 7
Hi,
I am using the hangman activity in some of my projects. There are two issues being faced:
When I test the published file in scormcloud, it works fine. The screen automatically progresses to the next slide once the learner completes the activity (I am using IE or firefox browser). However, when my client tests it, they get stuck after this activity, because the slide doesn't progress (they're testing on Chrome browser). Is this a browser issue?
Secondly, for the learner to move from one question to another after completing it, the button label reads 'Retry', which is not correct because you want them to continue and not retry a word. Is there a way to customize the button labels for these new interactions?
Your advise would be highly appreciated!
DivyaDivya, I have had similar problems with the puzzle widget. In the end we cannot make learner tools that only work on certain browsers. Users use different browsers. And that is that.
Adobe did not round off these widget tools properly. I actually wonder how they passed any form of QA.
I have not specifically used the hangman widget yet, However, when a learner does not complete the puzzle widget in time, it just hangs (freezes) right there! So I added a "continue" button that actually runs the slide again (so widget runs again) and allows the learner to try again. In the same way you could just add a continue button when and where your require it. You might have to use some advanced action to co-ordinate the lot.
If you have not worked with advanced actions before, now is the time to learn. Drink a Red Bull (It is not really bad for you) and watch the series of videos that explain advanced actions on YouTube. You will need the Red Bull to maintain focus . Just make enough time available and be patient. You will get it right. It will help you overcome many of the Captivate problems. -
import java.awt.*;
import java.awt.event.*;
public class Hangman
/* Extracts letters from the current woriginalCharArray and puts them in a character array */
private static char[] wordChange (String originalCharArray)
char[] temp;
temp = new char[originalCharArray.length ()];
for (int i = 0; i < originalCharArray.length (); i++)
temp[i] = originalCharArray.charAt (i);
return temp;
/* Handles the 'Guess' button */
private static class ActionHandler implements ActionListener
public void actionPerformed (ActionEvent event)
boolean changeWord; // If true, change to next word
boolean correctCheck; // If false, decrease maxGuessCounter
char guessedChar; // Character entered by user
// Check to see if it's the last word, and quit if it is
if (index > 4)
outputLabel.setText ("Game over");
outputGuess.setText ("Your score is: " + points);
guessedChar = (textField.getText ()).charAt (0); // Reads character
/* Resets boolean variables */
changeWord = false;
correctCheck = false;
/* Checks if the guessed character exists in the Word, adds to points counter */
for (int i = 0; i < originalCharArray.length; i++)
if (guessedChar == originalCharArray)
guessedCharArray[i] = guessedChar;
correctCheck = true;
points++;
/* If false, decrease maxGuessCounter */
if (correctCheck != true)
maxGuessCounter--;
/* Reset the values, to avoid concatenation */
outputLabelWord = "";
spacelessOutputWord = "";
/* Go through array, and set the outputLabelWord to the guessedCharArray (e.g. set all the correctly guessed chars in a String, so you can display it */
for (int i = 0; i < guessedCharArray.length; i++)
outputLabelWord = outputLabelWord + " " + guessedCharArray[i];
spacelessOutputWord = spacelessOutputWord + guessedCharArray[i];
/* If the word is correctly guessed, or the maximum amount of guesses have been exhausted, change the word */
if (spacelessOutputWord.equals (wordList[index]) || maxGuessCounter < 1)
maxGuessCounter = 5;
index++;
originalCharArray = new char[wordList[index].length ()];
originalCharArray = wordChange (wordList[index]); // Extract characters from the word, enter them in a character array
guessedCharArray = new char[originalCharArray.length];
/* Reset the guessed character array */
for (int i = 0; i < originalCharArray.length; i++)
guessedCharArray[i] = '_';
for (int i = 0; i < guessedCharArray.length; i++)
guessCharString = guessCharString + " " + guessedCharArray[i];
outputLabel.setText (guessCharString);
changeWord = true;
if (changeWord == false)
outputLabel.setText (outputLabelWord);
outputGuess.setText ("" + maxGuessCounter);
/* Declare variables */
private static int points = 0;
private static int index;
private static int maxGuessCounter;
private static String spacelessOutputWord = "";
private static String outputLabelWord = "";
private static String word = " ";
private static String guessCharString = "";
private static Label outputLabel;
private static Label outputGuess;
private static TextField textField;
private static Frame display;
/* Declare arrays */
private static char[] originalCharArray;
private static char[] guessedCharArray;
private static String[] wordList = { "h", "he", "hel", "hell", "hello" };
public static void main (String[]args)
textField = new TextField ("", 10);
maxGuessCounter = 5;
//Frame
display = new Frame ();
display.setLayout (new GridLayout (3, 2));
index = 0;
//Button stuff
Button guess;
ActionHandler action;
guess = new Button ("Guess");
outputGuess = new Label ("5");
outputLabel = new Label (word);
originalCharArray = new char[wordList[index].length ()];
originalCharArray = wordChange (wordList[index]);
guessedCharArray = new char[originalCharArray.length];
// Initializes the outputLabel
for (int i = 0; i < guessedCharArray.length; i++)
guessedCharArray[i] = '_';
for (int i = 0; i < guessedCharArray.length; i++)
guessCharString = guessCharString + " " + guessedCharArray[i];
outputLabel.setText (guessCharString);
guess.setActionCommand ("guess"); // Name the button event
action = new ActionHandler (); // Instantiate listener
guess.addActionListener (action); // Register the listener
//What to display on screen
display.add (outputLabel);
display.add (new Label (""));
display.add (textField);
display.add (guess);
display.add (outputGuess);
display.pack ();
display.show ();
display.addWindowListener (new WindowAdapter ()
public void windowClosing (WindowEvent event)
display.dispose ();
System.exit (0);}
Problems:
1) Doesn't work well, when it comes to the last word. It requires an additional click, after the wrong guess, in order to show the game over thing.
2) Gives an error message:
java.lang.ArrayIndexOutOfBoundsException
at Hangman$ActionHandler.actionPerformed(Hangman.java:85)
at java.awt.Button.processActionEvent(Button.java:381)
at java.awt.Button.processEvent(Button.java:350)
at java.awt.Component.dispatchEventImpl(Component.java:3526)
at java.awt.Component.dispatchEvent(Component.java:3367)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
when there.
3) Doesn't set to correct number of "_"'s (i.e equal to the word) when you guess the right word; only after you have entered the first number does it set the number of "_"'s correctly, namely the same amount as characters in the word.Also another weird thing I noticed. Check this part of the code:
private static char[] wordChange (String originalCharArray) { char[] temp; temp = new char[originalCharArray.length ()]; for (int i = 0; i < originalCharArray.length (); i++) { temp<i> = originalCharArray.charAt (i); } return temp; }When I change the length() to length, it doesnt work, although it shouldnt be length(). How come? I thought length() is for strings, and length is for arrays. -
hi everyone, im trying to make a hangman program but i have a few iissues first, whenever i ttry to run it, i get an "Exception in thread "main" java.lang.NoSuchMethodError: main" error and i dont know why. secondly,i dont know how to finish the metho replaceLetter. Please help!!!
--Confused Student
import java.util.*;
import java.io.*;
import java.lang.Math;
public class Hangman
private ArrayList<String> wordList;
private String word;
private String guess;
private boolean done = false;
private int numGuess = 0;
public final int MAX_GUESSES = 6;
public final String fileName = "words.txt";
public static void main(String[] args)
* Creates the Hangman object.
* Initializes wordList by getting the words from fileName.
* Initializes word by choosing a word from wordList.
* Initializes guess as an empty string.
public Hangman() throws FileNotFoundException
wordList = getWords(fileName);
word = chooseWord(wordList);
guess = setEmptyString(word.length());
* Determines if the game is done or still playing.
* Returns true if it is won or lost.
* Returns false otherwise.
public boolean done()
if (numGuess >=6)
return true;
return false;
* Determines if the game has been won by guessing the word.
* One way of determining this is if guess no longer has any "-" .
public boolean won()
/** Add code here **/
return false;
* Determines if the game has been lost.
* The game is lost if numGuess is MAX_GUESSES
public boolean lost()
if (numGuess>=MAX_GUESS)
return true;
return false;
* Determines whether the s contains letter.
public boolean has(String s, String letter)
if (s.indexOf(letter) != -1)
return true;
return false;
* Replaces the letter at index i in s with letter.
* Does not change s.
* Returns the new String.
public String replaceLetter(String s, int i, String letter)
return "";
* Replaces letter in word with "-"
* Replaces the corresponding letter in guess with letter.
* It must account for every instance of letter.
public void addToGuess(String letter)
Scanner sc = new Scanner(System.in);
String s = "";
for(int i = 0; i < word.length(); i++)
s += "-";
for(int i = 0; i < word.length(); i++)
* Prompts the user for a letter.
* Determines if the word has the letter.
* If it does, it must add that letter to the guess.
* Otherwise, it must update the number of incorrect guesses.
* It then displays the number of guess taken and the number remaining.
public void getGuess()
System.out.println(guess + "\n");
System.out.println("Guess a letter");
Scanner sc = new Scanner(System.in);
String letter = sc.next().substring(0,1);
/** Add code here **/
System.out.println(numGuess + " guesses.");
System.out.println(MAX_GUESSES - numGuess + " guesses remaining.\n");
* Returns a string of length size.
* The string will contain only "-" characters.
public String setEmptyString(int size)
String empty = "";
for(int i = 0; i < size; i++)
empty += "-";
return empty;
* Chooses a word from the ArrayList.
* Returns the chosen word as a String.
* The word is chosen at random.
public String chooseWord(ArrayList<String> list)
int index = (int)
(Math.random()*list.size());
return list.get(index);
* Gets a list of words from the given file.
* Returns the list as an ArrayList of Strings.
public ArrayList<String> getWords(String fileName) throws
FileNotFoundException
Scanner file = new Scanner(new File(fileName));
ArrayList<String> words = new ArrayList<String>();
while(file.hasNextLine())
words.add(file.nextLine());
return words;
* Repeatedly calls getGuess until the game is done.
* When the game is done, it displays an appropriate message.
public void playGame()
while(!done())
getGuess();
if (won())
System.out.println("You won!");
else
System.out.println("Sorry, you lose.");
/**Ralph Jones Jr**/In your main() method, first create an object of your class Hangman and invoke methods on it. Something link this...
try{
new Hangman().getGuess();
}catch(FileNotFoundException f){System.out.println(f);}Since Hangman() constructor throws FileNotFoundException, you need try-catch for creating your Hangman object. -
Hello, im trying to make it so that when an incorrect letter is chosen (arrayToPass does not contain string) the picture of the hangman is drawn.
I want count to go up to the number of incorrect attempts so that the appropriate picture is shown - not sure where I would put this though (count).
Generaly having trouble understanding the logic for this.
Please give some hints
Commented out code is various stuff ive tried already and i did not see a forum for logic therefore i think this is right.
public void actionPerformed(ActionEvent e)
boolean b = false;
int count = 0;
ImageIcon icon = null;
String s = e.getActionCommand();
String string = s.toLowerCase();
b = arrayToPass.indexOf(string) > -1; //Sees if array word has letter in radiobutton in it
//Split the word into an array
char[] chr = arrayToPass.toCharArray();
if(b == true) //If the word holds that letter
//String tempString = new Character(chr[1]).toString();
//jtp.setText("Correct");
for(int k = 0; k < chr.length; k++)
String ss = new Character(chr[k]).toString();
jl.setText(ss); //Set label to correct letter found
else
count++;
if(count == l)
icon = new ImageIcon("E:\\HangMan1.jpg");
jtp.insertIcon(icon);
else if(count == 2)
icon = new ImageIcon("E:\\HangMan2.jpg");
jtp.insertIcon(icon);
else if(count == 3)
icon = new ImageIcon("E:\\HangMan3.jpg");
jtp.insertIcon(icon);
else if(count == 4)
icon = new ImageIcon("E:\\HangMan4.jpg");
jtp.insertIcon(icon);
else if(count == 5)
icon = new ImageIcon("E:\\HangMan5.jpg");
jtp.insertIcon(icon);
}Although this is still very simple code, it always pays off to bring structure into your code.
You have a couple of tasks which you have to fulfill here.
1) Analyze the game situation.
2) change your game state accordingly.
3) display your current game state.
You can handle these three tasks completely seperate. First, you have to check for your words' validity. Depending on this, you have to change your count. Then, you have to repaint.
So, what you need is at least a game state object. This one must live as long as the game lives, so fields like your "count" are defintely wrong inside the "actionPerformed" method. Don't misuse the Action Command to carry information. Allow access to your game state object, and store the hangman word there.
Your word validity check is quite complicated. Maybe it would be a good idea to move it into its own method.
Your painting method will contain more than just changing your hangman pics. For example, you also have to uncover letters that were hidden before, so maybe you should put this into this method, as well.
This might look like overkill, but seperating helps you to distinguish between good code and wrong code. It also helps you to mentally concentrate on one specific topic, instead of handling everything as one mesh. -
Hi,
As the title suggest im putting together a simple hangman program. Ive been learning java for about a month now and I'm 90% done with the homework. The problem im having is actually outputting the correct slected letters to the screen. Im not trying to get game made for me, its just annoying that ive got all the core components worked out, i just cant output correct guesses to the screen :). For example.
I have created an array of 26 buttons, A-Z with this loop.
StringBuffer buffer;
letters = new Button[26];
for (i = 0; i <26; i++)
buffer = new StringBuffer();
buffer.append((char) (i+65));
letters[i] = new Button (buffer.toString());
letters.addActionListener( this );
add(letters[i]);
}The below segment is what im using to distinguish between correct and incorrect guesses.
{code:java} public void actionPerformed( ActionEvent ev)
for (i = 0; i < 26; i++)
if (ev.getSource() == letters)
letters[i].setVisible(false);
if (Words[rnd].indexOf(ev.getActionCommand()) == -1)
++badguesses;
System.out.print("Incorrectguesses is: ");
System.out.println(badguesses);
repaint();
if(Words[rnd].indexOf(ev.getActionCommand()) >= 0)
++correctguesses;
letterbuffer.insert(Words[rnd].indexOf(ev.getActionCommand()),ev.getActionCommand());
repaint();
}As you can see, im trying to add the letter pressed (button) to a stringbuffer, so i can send it down to the paint method. This compiles. However. From what i understand, (and i want to understand) java is adding the letters into a single string so, "f""i""r""e" would become "fire". Is this correct? My problem is outputting the individual characters. I had got to:
{code:java}public void paint(Graphics graf)
if (correctguesses > 0){
for (i = 1; i <=length; i++)
graf.drawString(letterbuffer.charAt(i),85,85+30*i);
//repaint();
} When i realised that this wasnt going to work. Basically i have no idea how to outprint the individual characters to their respective slots(check measurements in drawstring). Could somone explain what is going on, and suggest a possible fix please :)
Regards, D4rky
Here are my variables:String[] Words = {lots of words in here :) };
Random rand = new Random();
int rnd =(int)Math.floor(Math.random()*Words.length);
int length = Words[rnd].length(); //Length of chosen Array
int badguesses = 0;
int correctguesses = 0;
int x;
int i;
Button letters[];
StringBuffer letterbuffer = new StringBuffer(length);{code}Edited by: D4rky on Nov 1, 2009 11:20 AM
Edited by: D4rky on Nov 1, 2009 11:22 AM[Be Forthright When Cross Posting To Other Sites|http://faq.javaranch.com/java/BeForthrightWhenCrossPostingToOtherSites]:
[http://forums.devshed.com/java-help-9/hangman-650502.html]
~ -
i need help creating a hangman game with a predefined array of words for a java assignment here is my code so far
input Textfield 1 "for inputing word letters"
int alltrys = 6; "allow 6 incorrect"
int nowrong =0;
char guess;
int guessnumbers;
boolean badGuess;
String[] words;
public void init (){
word = newString(20); "this is going to be my array of predefined words"
word(0) = "cardiff";
word(1) = "bluebirds";
word(2) = "ccfc";
word(3) = "goal";
word(4) = "alexander";
word(5) = "jones";
word(6) = "hamman";
word(7) = "ridsdale";
word(8) = "ninianpark";
word(9) = "bluearmy";
word(10) = "grandstand";
word(11) = "cantonstand";
word(12) = "grangeend";
word(13) = "bobbank";
word(14) = "wales";
word(15) = "city";
word(16) = "penalty";
word(17) = "shoots";
word(18) = "chopra";
word(19) = "ayatollah";
int w = rand.nextInt(20);
int randomNumber I = Math.random()*word.length);
for (int stringIndex = 0; stringIndex < word(i),length();stringIndex ++)
char.currrentCharacter
dont know if some is even right but am reccomended to also use
drawString()
drawOval()
drawLine()
TextField()
Button()
i am only new to java so really need help also using textpad to do javawell id like to see how good you are after just four
weeks after being taught by some ****** who dont know
how to do his job properlyYeah, blame your teacher. It couldn't possibly be your own fault. -
Console Hangman game HELP!!!
I have to construct a hangman game, and am having some trouble with showing the letters of the word that is guess. Also, I cannot figure out where to put
public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
in my code to make it case insensitive. And my other big problem is that I cannot get the game to exit once the player guesses then enitre word correctly. Any suggestions will help.
import java.util.*;
import java.io.*;
public class hangman
public static void main(String [] args) throws IOException
// public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
int maxTries = 7;
int wordLength;
boolean solved;
StringBuffer guessedLetters = new StringBuffer();
//the fileScan gets the first word for the game
Scanner fileScan = new Scanner(new FileInputStream("words.txt"));
String secretWord = fileScan.next();
//Creates a StringBuffer for the viewing of the letters guessed
StringBuffer word = new StringBuffer();
for(int i = 0; i <= secretWord.length(); i++)
word.append("_");
System.out.println("Welcome to the game of HANGMAN!!!!");
System.out.println("You will have 7 chances to guess what the word is.");
// System.out.println("Your word is " + wordLength + " letters long.");
String letter;
while(maxTries > 0 && (word.equals(secretWord)) == false)
System.out.println(word.equals(secretWord));
System.out.println("The letters that you have guessed are: " + guessedLetters);
System.out.println("The word so far is: " + word);
System.out.print("Please enter a letter to guess: ");
Scanner inScan = new Scanner(System.in);
letter = inScan.next();
guessedLetters.append(letter + " ");
if(secretWord.indexOf(letter) != (-1))
int addedLetter = secretWord.indexOf(letter);
word.replace(addedLetter, addedLetter, letter);
word.setLength(secretWord.length());
else
maxTries--;
System.out.println("You have " + maxTries + " wrong guesses left.");
}THANKSI have to construct a hangman game, and am having some trouble with showing the letters of the word that is guess. Also, I cannot figure out where to put
public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
in my code to make it case insensitive. And my other big problem is that I cannot get the game to exit once the player guesses then enitre word correctly. Any suggestions will help.
import java.util.*;
import java.io.*;
public class hangman
public static void main(String [] args) throws IOException
// public static final Comparator<secretWord> CASE_INSENSITIVE_ORDER;
int maxTries = 7;
int wordLength;
boolean solved;
StringBuffer guessedLetters = new StringBuffer();
//the fileScan gets the first word for the game
Scanner fileScan = new Scanner(new FileInputStream("words.txt"));
String secretWord = fileScan.next();
//Creates a StringBuffer for the viewing of the letters guessed
StringBuffer word = new StringBuffer();
for(int i = 0; i <= secretWord.length(); i++)
word.append("_");
System.out.println("Welcome to the game of HANGMAN!!!!");
System.out.println("You will have 7 chances to guess what the word is.");
// System.out.println("Your word is " + wordLength + " letters long.");
String letter;
while(maxTries > 0 && (word.equals(secretWord)) == false)
System.out.println(word.equals(secretWord));
System.out.println("The letters that you have guessed are: " + guessedLetters);
System.out.println("The word so far is: " + word);
System.out.print("Please enter a letter to guess: ");
Scanner inScan = new Scanner(System.in);
letter = inScan.next();
guessedLetters.append(letter + " ");
if(secretWord.indexOf(letter) != (-1))
int addedLetter = secretWord.indexOf(letter);
word.replace(addedLetter, addedLetter, letter);
word.setLength(secretWord.length());
else
maxTries--;
System.out.println("You have " + maxTries + " wrong guesses left.");
}THANKS -
Hi all experts,
I'm wanting to create a simple hangman game for the Nokia 3650 for a Thesis due in September.
Can you tell me what emulator and/or development kit I need to download from Nokia or Java in order to get started.
My first task is to write HelloWorld! on a Nokia Emulator for the 3650!!!
I'm fairly new to Java programming so I want to keep it as simple as possible for now and then hopefully build up to maybe some sounds and a bit of animation.
I want look into the possibility of using bluetooth for a 2-player game eventually too.
Any help/advice/warnings/sympathy/luck would be all gratefully received!!
Much appreciated
Natalie.Grab the J2ME toolkit version 1 from http://java.sun.com/products/j2mewtoolkit/
Install & Read Docs
Maybe you are looking for
-
What is the best way to filter an IP from being blocked?
What is the best way to filter an IP from being blocked by a false positive? Event Action Filter?
-
Adobe only prints first page of multi-page PDF documents.
On a military network, ever since users have been upgraded to Adobe Pro 9, only the first page of their multi-page documents will print from a particular network printer. The OS is Windows XP. Adobe Pro version is 9.1.2 Network printer is a Xerox P
-
Problem on Multi based queries
Hi,gurus, I have two DSO(BI 7.0), ZDSO1 and ZDSO2, in ZDSO1, there are three characteristics ZCH01, ZCH02, ZCH03 and one key figure ZKF01, the key is ZCH01, while in ZDSO2, there are three characteristics ZCH01, ZCH04, ZCH05 and one key figure ZKF
-
Application that allows to paste images copied from the web..
hey guys. im looking for an application that allows to paste images copied from the web.. ive tried a few but they only paste the next... anyone help? cheers.
-
This should be possible, but how??? I read in their forum that I should startup rox instead of xfdesktop in xinitrc, but it didn't work. I tried to do it in at least two different xinitrc since it didn't say which one... And I started thinking, the "