Guessing Game Problem

I'm having a problem thinking of a way to think of a solution to this. Basically, what I am trying to do is have a guessing game with the computer. What happens is I think of a number from 1000 to 9999, let's say 3741. Then the computer randomnly guesses from an ArrayList of 1000-9999, and asks if its the right number, or not. Let's say the computer guesses 5312. I would respond by saying how many matches there are 0-4, in this case 4. Then my idea is to update the arrayList, by deleting all the necessary values. I would do this continuously until one number is left, which would be the correct answer. I am trying to think of an algorithm that would do this in 15 guesses or less (aiming for 10ish).
My code so far:
// fill in your information in the line below, and comment it out in order to compile
// Name: ???   Student ID: ???;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class Assignment2 {
private int totalGuesses;
private ArrayList<Integer> guess;
private int myGuess;
public Assignment2 ( ){
totalGuesses = 0;
myGuess = 0;
guess = new ArrayList<Integer>();
for(int i = 1000; i <= 9999 ; i++) // Adds numbers 1000 to 9999 initially.
   guess.add(i);
public int myGuessIs() {
  return myGuess;
public int totalNumGuesses() {
  return totalGuesses;
public void updateMyGuess(int nmatches) {
  // fill in code here
  // update the guess based on the number of matches claimed by the user
if(guess.size() == 0)
  myGuess = -1;
// you shouldn't need to change the main function
public static void main(String[] args) {
  Assignment2 gamer = new Assignment2( );
  JOptionPane.showMessageDialog(null, "Think of a number between 1000 and 9999.\n Click OK when you are ready...", "Let's play a game", JOptionPane.INFORMATION_MESSAGE);
  int numMatches = 0;
  int myguess = 0;
  do {
   myguess = gamer.myGuessIs();
   if (myguess == -1) {
    JOptionPane.showMessageDialog(null, "I don't think your number exists.\n I could be wrong though...", "Mistake", JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
   String userInput = JOptionPane.showInputDialog("I guess your number is " + myguess + ". How many digits did I guess correctly?");
   // quit if the user input nothing (such as pressed ESC)
   if (userInput == null)
    System.exit(0);
   // parse user input, pop up a warning message if the input is invalid
   try {
    numMatches = Integer.parseInt(userInput.trim());
   catch(Exception exception) {
    JOptionPane.showMessageDialog(null, "Your input is invalid. Please enter a number between 0 and 4", "Warning", JOptionPane.WARNING_MESSAGE);
    numMatches = 0;
   // the number of matches must be between 0 and 4
   if (numMatches < 0 || numMatches > 4) {
    JOptionPane.showMessageDialog(null, "Your input is invalid. Please enter a number between 0 and 4", "Warning", JOptionPane.WARNING_MESSAGE);
    numMatches = 0;
   if (numMatches == 4)
    break;
   // update based on user input
   gamer.updateMyGuess(numMatches);
  } while (true);
  // the game ends when the user says all 4 digits are correct
  System.out.println("Aha, I got it, your number is " + myguess + ".");
  System.out.println("I did it in " + gamer.totalNumGuesses() + " turns.");
Obviously, I'm having trouble thinking of a solution to updateMyGuess...I don't know why but I'm most likely making this way harder than it actually is.. Can anyone help?

borisan wrote:
What happens is I think of a number from 1000 to 9999, let's say 3741. Then the computer randomnly guesses from an ArrayList of 1000-9999, and asks if its the right number, or not. Let's say the computer guesses 5312. I would respond by saying how many matches there are 0-4, in this case 4. Don't you mean 0?
What if computer's guess is 2795. I assume number of matches then would be 1 (the 7). How exactly is your code going to know that 7 is the lone match and not the 2 or the 9 or the 5?

Similar Messages

  • Need help with a guessing game

    Hi. hopefully, this is a really easy issue to resolve. I had to write a program that administers a guessing game, where the computer chooses a random number, and the user has to guess the number. If the user doesn't get it within 5 guesses, they lose and start all over with a new number. I have this all in a while loop (as per my instructions). My issue is that whenever the user enters 0, the program should quit with the users final score and so on. My program will not quit unless the 0 is entered on the last (fifth) guess. please help, it would be very appreciated. Here is my code:
    import java.util.Scanner;
      public class guessgame {
        public static void main(String[] args) {
          Scanner scanner = new Scanner (System.in);
            int randnum;        //random number generated by computer
            int userguess = 1;      //number the user guesses
            int userscore = 0;      //number of correct guesses by user
            int compscore = 0;      //number of times not guessed
            int guessnum = 0;       //number of guesses for one number
            int gamenum = 0;        //number of games played
        System.out.println ("I will choose a number between 1 and 10");
        System.out.println ("Try to find the number using as few guesses as possible");
        System.out.println ("After each guess i will tell you if you are high or low");
        System.out.println ("Guess a number (or 0 to quit)");
        while (userguess != 0) {
          randnum = 1 + (int)(Math.random() * 10); //generates random number
          gamenum ++;
          userguess = userguess;
            for (guessnum = 1; guessnum < 6 && userguess != randnum; guessnum ++) {
                userguess = scanner.nextInt();
                userguess = userguess;
               if (guessnum >= 5) {
                  System.out.println ("You did not guess my number!");
                                  } //closes if statement
               if (userguess == randnum) {
                 userscore ++;
                 System.out.println ("You guessed it! It took you " + guessnum + " tries.");
                 System.out.println ("If you want to play again, enter a guess");
                 System.out.println ("If you do not want to play again, enter 0");
                                        } //closes if statement
               else if (userguess < randnum)
                 System.out.println ("Your guess is too low");
               else if (userguess > randnum)
                 System.out.println ("Your guess is too high");
                                                          }//closes for loop
                              } //closes while loop
    compscore = gamenum - userscore;
            System.out.println ("Thanks for playing! You played " + gamenum + " games");
            System.out.println ("Out of those " + gamenum + " games, you won " + userscore + " times");
            System.out.println ("That means that I won " + compscore + " times"); 
    } //closes main
    } //ends guessgame class

    The problem with your program is that the while loop doesn't get checked. The condition of the while loop will only get checked each iteration, and not during one iteration. The time you are in your for-loop is still one iteration so it won't check if userguess is 0. see it liek this
    While: is userguess 0, no, do 1 iteration
    while-iteration-forloop: check 5 guesses, userguess can be anything even 0 while loop won't stop.
    end of for loop
    end of while-iteration
    new while iteration, is userguess 0?
    and so on.
    HTH,
    Lima

  • AC3 help (number guessing game)

    Hello I have a problem, im fairly new to action script and flash in general but heres my code:
    //These are the variables.
    var beginMessage:String;
    var randomNumber:uint;
    var guess:uint;
    //It disables the play again button so only the guess button is usable.
    playagain_btn.enabled =false;
    guess_btn.enabled = true;
    //shows a message in the message_txt box.
    beginMessage="Choose a number between 1 - 100.";
    message_txt.text=beginMessage;
    //Basically only allows numbers between 0-9...
    input_txt.restrict="0-9";
    input_txt.text="";
    //This stores a random number between 100 and 1.
    randomNumber = Math.floor(Math.random() * 100 + 1);
    //Adds an event listener to the guess button.
    guess_btn.addEventListener(MouseEvent.CLICK, yourGuess);
    function yourGuess(event:MouseEvent):void {
    guess=uint(input_txt.text);
    //This checks if the guessed number is greater than the random number.
    if (guess > randomNumber) {
    message_txt.text = "Your guess, " +  guess + " is too damn high.";
    //This checks if the guessed number is lower than the random number.
    else if (guess < randomNumber) {                       
    message_txt.text = "Your guess, " +  guess + " is too low.";         
    //This displays a message when the correct number is guessed.  
    else{        
    message_txt.text = "congratulations ,the number is " + randomNumber + ".";
    winGame();        
    function winGame():void{       
    //Disables the guess button and enables the play again button.         
    guess_btn.enabled = false;         
    playagain_btn.enabled = true;          
    //This removes a listener from the yourguess button and adds a
    //listener to playagain
    guess_btn.removeEventListener(MouseEvent.CLICK, yourGuess);         
    playagain_btn.addEventListener(MouseEvent.CLICK, guessAgain);
    function guessAgain(event:MouseEvent):void{         
    //Runs the init() method.         
    init();
    //Runs the init() method.
    init();
    //this part of the script is for the number
    //Declare variables
    var numOfGuesses:uint ;
    var numOfGuessesMessage:String;
    function init():void {
        //Displays a message showing the total number of guessing remaining
        numOfGuesses = 6;
        numOfGuessesMessage = " Guesses remaining";
        guess_txt.text = numOfGuesses + numOfGuessesMessage;
    if(numOfGuesses == 0){
            message_txt.text = "The number was " + randomNumber + "."; 
            guess_txt.text = "you lose!!!!!! D:!!.";
            winGame();
    function yourGuess(event:MouseEvent):void {
        guessMessage();
    function guessMessage():void{
        //Only decrement the numOfGuesses if the text field contains characters.
        if(input_txt.length > 1 && numOfGuesses != 0){
            numOfGuesses--;
            guess_txt.text = numOfGuesses + numOfGuessesMessage;
    And my errors are duplicate function definition. theres the code its crying about.
    function yourGuess(event:MouseEvent):void {
        guessMessage();
    what Im doing here is making a number guessing game, everything works but the number of guesses wont go down.

    Put a trace in the function where you try to decrease the number of guesses and see if the logic is letting you get in to change it...
      function guessMessage():void {
       //Only decrement numofGuess if the input field has characters.
    trace(input_txt.length, numOfGuesses)
       if(input_txt.length > 1 && numOfGuesses != 0){
        numOfGuesses--;
        guess_txt.text = numOfGuesses + numOfGuessesMessage;
      //When guesses have ran out, A message will appear saying you can reset.
      if(numOfGuesses == 0){
       message_txt.text = "The number I was thinking was " + randomNumber + ".";
       guess_txt.text = "Press play again to try again";
      winGame(event:MouseEvent);
    If you happen to be changing frames where you leave the frame with this code and then come back to it, then you are likely running into this line again....
    numOfGuesses = 6;
    which resets the number of guesses.

  • My ipod nano 4th generation will plug into itunes and if i push buttons i can hear music, however the whole time the screen is black so its a guessing game. how do i fix this?

    my 4th generation ipod nano works but its a guessing game. the screen is totally black even when plugged into my computer. itunes still recognizes it. is the screen broke is it the backlight, any suggestions how to find out or to fix this? oh and ive completely restored the ipod several times. i let someone borrow it and this is how i got it back so i dont know what caused the problem.
    Message was edited by: robynd369

    I checked for anything either bent or broken, and as far as I know everything looks fine, though I could probably clean out the dust and dirt collected in there after a year. I could take a picture if that would help. Would being dirty inside there cause this to happen? It's one thing I guess I never thought of and probably should do.

  • I guess the problem come from me or I really need those contacts before he calls me for it. I'll try some method that I got from some responders on your support website. Do you have or can you recommand any software that can solve this problem?

    I guess the problem come from me but I really need those contacts before he calls me for it. I'll try some method that I got from some responders on your support website. Do you have or can you recommand any software that can solve this problem?
    One more thing. I just update my iphone that my boss gave to me but it seems to be like it giving me some trouble. My iphone was updated not too long and was successful. I try to lock into it and it telling me emergency call. I plug it to my itune and it telling me that the sim card is not valid or supported. So I inserted my sim card that I usually use to call and it still saying the same. Please help me get into it.

    And as far as paying for phone support, here are a few tips:
    If you call your carrier first and then they route you to Apple, you usually don't have to pay for phone support.
    If you are talking to Apple and they ask you to pay a support fee, ask if you can get an exception this time.  That usually works once, but they keep track of the times you've been granted such an exception.
    If you still end up paying the support fee, that fee only applies if it's not a hardware related issue.  In other words, if it can be fixed by just talking over the phone and following Apple's instructions, then the fee applies.  But if your device is deemed to have a hardware failure that caused the issue, then the fee should not apply, and you can ask for it to be waived after the fact.
    This forum is free, and almost all of the technical support articles the Apple tech advisors use are available on this website.  Literally 99% of what they can do over the phone is just walking you through the publicly available support articles.  In other words, you're paying the fee to have them do your research for you.  It's like hiring a research consultant to go look stuff up in the public library so you don't have to.  You're capable of doing it; you'd just rather pay someone to do it for you.
    It's like Starbucks.  You know how to make coffee.  Everyone knows how to make coffee.  And Starbucks coffee isn't any better than what you could make at home for far less.  But you want the convenience.  So you're really paying a convenience fee.  Milk is more expensive at 7-Eleven than it is at the grocery store... because it's a convenience store.

  • Titanium Fatal1ty Pro SPDIF game problem

    (Titanium Fatalty Pro SPDIF game problem hi all,
    sorry if this issue reported in the past i but i could not get any answer on any relati've posts, the terminology was so complicated
    i buy?a new pc with a Titanium Fatalty Pro sound card, i use Vista sp2 x64, the sound card is connected to my external amplifier with SPDIF out in order to get surround sound for my movies and my games and here is my problem
    any movies format with surround sound play perfect with out any problem any kind of movie DVD, dvix, mkv?files?etc
    but non of the games i play?use the surround system, why is that? is any?kind of special settings needed to be done? how is possible to get surround to movies and not to the games?
    thanks you all for your time ?

    ,Re: Titanium Fatalty Pro SPDIF game problem? this is really coincidence - I just posted on the very same topic 5 minutes ago.
    for games just go to the Console Entertainment mode > Encoder > Dolby Digital. Although this is not documented I believe what happens is that the sound card encodes the 6 digital channels onto Dolby Digital mode and transfers this over SPDIF. Kok-Choy actually recommend using the standard analogue cables (and he has a point as you are actually upcoding an existing game signal onto Dolby so that your digital receiver can then decode this down to 6 channels - seems a pretty useless overhead)
    for video - I am curious to know what you do - I can either get 96/24 bits on the display of my z5500 with a direct signal but the z5500 receiver then tells me that this signal is only in dolby ProLogic II (and not DD or DTS). As alternati've I use again the encoder and have to select for EACH FILM WHAT IS BEST DOLBY DIGITAL OR DTS. Pls explain what settings you use.
    thanks

  • Need help with " Number guessing game " please?

    This is what teacher requires us to do for this assignment:
    Write a program that plays a simple number guessing game. In this game the user will think of a number and the program will do the guessing. After each guess from the program, the user will either indicate that the guess is correct (by typing �c�), or that the next guess should be higher (by typing �h�), or that it should be lower (by typing �l�). Here is a sample output for a game. In this particular game the user thinks of the number 30:
    $java GuessingGameProgram
    Guess a number between 0 and 100
    Is it 50? (h/l/c): l
    Is it 25? (h/l/c): h
    Is it 37? (h/l/c): l
    Is it 31? (h/l/c): l
    Is it 28? (h/l/c): h
    Is it 29? (h/l/c): h
    Is it 30? (h/l/c): c
    Thank you for playing.
    $
    This program is implementing a binary search algorithm, dividing the range of possible values in half with each guess. You can implement any algorithm that you want, but, all things being equal, binary search is the best algorithm.
    Write the program so that the functionality is split between two classes: GuessingGameProgram, and NumberGuesser.
    GuessingGameProgram will only be used for its main function. It should instantiate a NumberGuesser, and it will be responsible for the loop that notifies the user of the next guess, reads the �h�, �l�, or �c� from the user, and sends an appropriate message to the number guesser accordingly.
    The guesses themselves should all be generated by the NumberGuesser class. Here is a diagram of the members and methods for the class. Notice that the members are unspecified. Feel free to give your NumberGuesser class any members (which we have also been calling fields, or instance variables) that you find useful. Make them all private.
    NumberGuesser
    NumberGuesser(int upperLimit, int lowerLimit)
    int guess()
    void higher()
    void lower()
    The constructor should take two integer arguments, a lower and upper bound for the guesses. In your program the constructor will be called with bounds of 0 and 100.
    The guess method should return the same value if it is called more than once without intervening calls to the lower or higher methods. The class should only change its guess when it receives a message indicating that its next guess should be higher or lower.
    Enjoy. Focus your attention on the NumberGuesser class. It is more interesting than the GuessingGameProgram class because it is a general-purpose class, potentially useful to anybody who is writing a number guessing game. Imagine, for instance, that a few weeks from now you are asked to write a number guessing game with a graphical Java Applet front end. If you NumberGuesser class is well written, you may be able to reuse it without any modifications.
    I'm new to JAVA and I'm set with my 2nd homework where I'm so confused. I know how to do something of this source in C language, but I'm a bit confused with Java. This is the code me and my classmate worked on, I know it's not 100% of what teacher asked, but is there any way possibly you guys could help me? I wrote this program if the game is played less then 10 times, thought I would then re-create a program without it, but now I'm confused, and my class book has nothing about this :( and I'm so confused and lost, can you please help? And out teacher told us that it's due the end of this week :( wish I knew what to do. Thank you so so much.
    Here's the code:
    import java.text.*;
    import java.io.*;
    class GuessingGame
    public static void main( String[] args ) throws IOException
    BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ) );
    int guess = 0, limit = 9, x = 0, n, a = 0 ;
    double val = 0 ;
    String inputData;
    for ( x = 1; x <= 10; x++)      //number of games played
    System.out.println("round " + x + ":");
    System.out.println(" ");
    System.out.println("I am thinking of a number from 1 to 10. ");
    System.out.println("You must guess what it is in three tries. ");
    System.out.println("Enter a guess: ");
    inputData = stdin.readLine();
    guess = Integer.parseInt( inputData );
    val = Math.random() * 10 % limit + 1;     //max limit is set to 9
    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(0);               //format number of decimal places
    String s = nf.format(val);
    val = Integer.parseInt( s );
         for ( n = 1; n <= 3; n++ )      //number of guess's made
                   if ( guess == val)
                        System.out.println("RIGHT!!");                    //if guess is right
                        a = a + 1;
                        System.out.println("You have won " + a + " out of " + x + " rounds");
    System.out.println(" ");
    n = 3;
    continue;
              if (n == 3 && guess != val)                         //3 guesses and guess is wromg
                        System.out.println("wrong");
    System.out.println("The correct number was " + val);
                        System.out.println("You have won " + a + " out of " + x + " rounds");
    System.out.println(" ");
    continue;
                   //how close guess is to value
                   if ( guess == val - 1 || val + 1 == guess) //Within 1
                   System.out.println("hot");
         else if ( guess == val - 2 || val + 2 == guess) // Within 2
                   System.out.println("warm");
              else
                   System.out.println("cold");                         // Greater than 3
         inputData = stdin.readLine();
         guess = Integer.parseInt( inputData );
    //ratings
    if ( a <= 7)
         System.out.println("Your rating is: imbecile.");
    else if ( a <= 8)
         System.out.println("Your rating is: getting better but, dumb.");
    else if (a <= 9)
         System.out.println("Your rating is: high school grad.");
    else if ( a == 10)
         System.out.println("Your rating is: College Grad.!!!");

    Try this.
    By saying that, I expect you ,and your classmate(s), to study this example and then write your own. Hand it in as-is and you'll be rumbled as a homework-cheat in about 20ms ;)
    When you have an attempt where you can explain, without refering to notes, every single line, you've cracked it.
    Also (hint) comment your version well so your tutor is left with the impression you know what you're doing.
    In addition (huge hint) do not leave the static inner class 'NumberGuesser' where it is. Read your course notes and find out where distinct classes should go.
    BTW - Ever wonder if course tutors scan this forum for students looking for help and/or cheating?
    It's a double edged sword for you newbies. If you ask a sensible, well researched question, get helpful answers and apply them to your coursework, IMHO you should get credit for doing that.
    On the other hand, if you simply post your assignment and sit there hoping some sucker like me will do it for you, you should be taken aside and given a good kicking - or whatever modern educational establishments consider appropriate abmonishment ;)
    I'd say this posting is, currently, slap bang between the two extreemes, so impress us. Post your solution in the form you intend to hand it in, and have us comment on it.
    Good luck!
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    public class GuessingGame
         public static void main(String[] args)
              throws Exception
              BufferedReader reader= new BufferedReader(
                   new InputStreamReader(System.in));
              NumberGuesser guesser= new NumberGuesser(0, 100);
              System.out.println(
                   "\nThink of a number between 0 and 100, oh wise one...");
              int guess= 0;
              while (true) {
                   guess= guesser.guess();
                   System.out.print("\nIs it " +guesser.guess() +"? (h/l/c) ");
                   String line= reader.readLine();
                   if (line == null) {
                        System.out.println(
                             "\n\nLeaving? So soon? But we didn't finish the game!");
                        break;
                   if (line.length() < 1) {
                        System.out.println("\nPress a key, you muppet!");
                        continue;
                   switch (line.toLowerCase().charAt(0)) {
                        case 'h':  
                             guesser.higher();
                             break;
                        case 'l':     
                             guesser.lower();
                             break;
                        case 'c':
                             System.out.println("\nThank you for playing.");
                             System.exit(0);
                        default:
                             System.out.println(
                                  "\nHow hard can it be? Just press 'h' 'l' or 'c', ok?");
                             continue;
                   if (guess == guesser.guess()) {
                        System.out.println(
                             "\nIf you're going to cheat, I'm not playing!");
                        break;
         private static class NumberGuesser
              private int mLower;
              private int mUpper;
              private int mGuess;
              NumberGuesser(int lowerLimit, int upperLimit)
                   mLower= lowerLimit;
                   mUpper= upperLimit;
                   makeGuess();
              private void makeGuess() {
                   mGuess= mLower + ((mUpper - mLower) / 2);
              int guess() {
                   return mGuess;
              void higher()
                   mLower= mGuess;
                   makeGuess();
              void lower()
                   mUpper= mGuess;
                   makeGuess();
    }                  

  • Help with action script number guessing game

    can someone help me in flash cs6 to make a simple guessing game, i just need help with the coding. making a guessing game from 1-100
    The constructor is coded to assign a random number for
    the user to guess
    • In the section of code indicated by the comments
    (within the handler function doGuess()), write condition
    statements that guide the user to guessing the number
    using text written to the output
    • Trace out the users' guess, plus a message
    • Messages for the user depending how close they are from the
    guess, condition each of the following:
    • Guesses correctly, +/-1 from the guess, +/-10 from the guess,
    +/-20 from the guess, +/-40 from the guess, all other guesses

    close, it's actually an in class practice lab. After doing this we have to do another one that needs to be submitted. I just need help with the coding for this because i dont know how to start at all. let alone the actual lab.

  • Sound blaster Audigy 2 zs gamer problem!

    (Sound blaster Audigy 2 zs gamer problem!? I had a recent problem recently that caused Windows not to load at all. After getting that fixed and the computer back home I have run into a sound issue. None of the Creative's Media Source programs would work properlly. When clicked on I would get the error that the program has encountered an error and needs to close. Finally un-installed all creative programs and related software and went through the re-install process. Encountered an error that program could not load because plxcore.plx cannot be found. I went through the solution listed on?Creative's web site to fix the?issue and none of fixes worked. Recently deleted everything Creative again by uninstalling all drivers and going through the installshield folder and deletd all creative related items. Went through the install process again. Had the plx error, fixed it and had sound but had the same problems with the Media SOurce as before. Went to Creative's web site through auto updater for a new driver and other essential items needed for my sound. Back to no sound again. Under Windows control panel under sounds and audio devices under volume tab, it will not even let me select the speaker setting or place the volume control on the task bar. @99.3.9.75

    Brettpopp
    Try updating your BIOS to the latest and have the sound card tested on another machine to see if it is still functioning.
    Jason

  • IPod Touch playng games problems , after download not start games

    iPod Touch playng games problems , after download not start games

    When touch the game icon just "blink" (tremor)for one momentend not start games, a lot of games,aleator ,never apps sistem to the factory.After restore to the factory seting and redownload is posible to run once or twice corectly and after that the trouble begin again.

  • Word guessing game Flash Develop as3

    I am coding a word guessing game for primary level age 5/6. They have to guess a five letter word by looking at the image. I want to provide a clue button, which when clicked will give the user one correct letter. There are five words contained in an array. I want to give one letter as a clue. Here is my current code (not completed). If anyone has any ideas, they would be greatly appreciated as havn't done this before!!
                        public function clue(event:MouseEvent):void {
                                  for (var  i : uint = 0; i < 5; i++)
                                  if (this["text" + i].text != currentWord.charAt(i))
                                                                //changing colour to red
                                                                trace ("checking if equal");
                                                                this ["button" + i] = setImage("../images/red2.png", 405 + (40 * i), 600);
                                                                this["button" + i].visible = true;
                                                                //need to give the user one correct letter
                                                                ["Text"+i] == currentWord.charAt(i)

    Hi Ned,
         Mt current Word is the current word in my Array which could be any out of 5. The current letter was i was trying to get a letter out of the current Word in the array and provide one correct letter as a clue to the user. The text+i is the letter/word at position i in the array. I basically took my method for search for char and tried to change it for searching for letters instead of words but not really sure what i am doing. Here is search for char code i was basing the other one on. This method checks the letters inputed into the 5 textfields against the current word in the array and changes coloured cirlces underneath each letter to yellow if correct and red if incorrect.
    public function searchForChar(evt:MouseEvent):void {
                                  trace ("coming in here");
                                  //make sure all text fields have been entered
                                  for (var  i : uint = 0; i < 5; i++)
                                            trace ("looping");
                                            //if letter is right
                                            if (this["text" + i].text == currentWord.charAt(i))
                                                      //changing colour to yellow
                                                      trace ("checking if equal");
                                                      this ["button" + i] = setImage("../images/yellow2.png", 405 + (40 * i), 600);
                                                      this["button"+i].visible = true;
                                                      else
                                                                if (this["text" + i].text != currentWord.charAt(i))
                                                                //changing colour to red
                                                                trace ("checking if equal");
                                                                this ["button" + i] = setImage("../images/red2.png", 405 + (40 * i), 600);
                                                                this["button" + i].visible = true;

  • Creating a word-based guessing game

    Hi...
    I'm currently producing a experimental flash project, which
    involves both comic-book style imagery, animation and
    puzzle-solving whereby the user must solve a riddle in order to
    progress through the story. Of course, the whole project involves
    one bit of Actionscript 2 on each page in order to get it to work
    but so far I've only been able to find code for a guessing game
    with numbers.
    The following code is how I've tried to handle this: I'm
    fairly new to Actionscript so please forgive me! I've attached this
    code to my "answer_btn" button. "Input" refers to the input textbox
    in which the correct answer must be typed.
    Thanks for your help!

    Input is not the same as input.
    if input is the instance name of your textfield, you need to
    use its text property. if input is the variable associated with
    your textfield, you're ok.
    you have a paranthesis mismatch on your 2nd line of code.
    remove one right paranthesis.
    if your button is a true button (not a movieclip button),
    you're directing the parent timeline of the timeline that contains
    your button to play "riddle_story".

  • ATI and TVout plus games problems

    Hi,
    So I really hate ATI by now but since switching to nvidia ain't and option atm I might as well ask for user input on couple of problems:
    1st: Tvout, I guess to get working tvout i must use fglrx? Tvout works as clone atm but is it possible to get same extended desktop and videos playing in fullscreen tv-overlay as in windows? or atleast how to change the clone-tv-out resolution? any working configs would be appreciated.
    2nd: While fglrx seems to have better fps than opensource ones, why the hell do games (nexuiz, true-combat, flightgear for one) go from 60+ fps to a crawl as soon as some otherplayer/cpu moves at screen?
    Atleast tremulous works just fine.
    Using amd3000 and radeon9600pro with ck kernel and usually resolution off 1680x1050 (although lowering res. doesn't seem to help at all)
    Anyone else experiencing these?
    PS. I could just switch to opensource ati drivers and get compiz and play in windows but then I'd still loose tvout rite? (big minus and ATI really sucks)

    Mikko777 wrote:
    1st: Tvout, I guess to get working tvout i must use fglrx? Tvout works as clone atm but is it possible to get same extended desktop and videos playing in fullscreen tv-overlay as in windows? or atleast how to change the clone-tv-out resolution? any working configs would be appreciated.
    2nd: While fglrx seems to have better fps than opensource ones, why the hell do games (nexuiz, true-combat, flightgear for one) go from 60+ fps to a crawl as soon as some otherplayer/cpu moves at screen?
    Atleast tremulous works just fine.
    Well nevermind my ranting, The more i use linux the more angry i get that things ain't up to windows level
    Answering myself:
    1st: for tvout must use fglrx or opensource drivers with crappy apps like atitvout or gatos. so basically its fglrx only and even that ain't too shabby.
    2nd: No idea, just a crappy driver I think.
    3rd: No compiz without xgl and xgl just plain sux (xfreezes, kernel panicks with opengl apps, not possible to spawn another x screen?)
    So in short buy nvidia / intel.

  • Number Guessing Game Help

    this is my current code it works ok, but i need a bit of help with when they get it right, and I have to start converting it to graphical in Borland Jbuilder.
    import java.io.*;
         import java.util.*;
    public class Numb{
         public static void main (String [] args){
              //Game State     
              int magicNumb = Math.abs(new Random().nextInt() % 100) + 1;
              //Output instructions
              System.out.println("I Feel Numb!");
              System.out.print("Do you feel Loved? Y/N");
              //Read from input
              InputStreamReader inStream = new InputStreamReader(System.in);
              BufferedReader keyboard = new BufferedReader(inStream);
              String line = null;
              try{
                   line=keyboard.readLine();
              }catch(IOException ioe){}
              boolean acrobat = true;
              //If they pressed y let them play
              if(line.equalsIgnoreCase("y")){
                   //Game stuff goes here
                   System.out.println("Don't Expect Suggest a NUMBer between 1 and 100");
                   System.out.print("Enter a guess:");               
                   //LOOP
                   while (acrobat=true){
                   //Read user input
                   {try{
                        line=keyboard.readLine();
                   }catch(IOException ioe){}
                   //Convert the inpt to an int value
                   int guess = (int)Integer.parseInt(line);
                   //If Right
                   if (guess==magicNumb)
                        System.out.println("Green Light Seven Eleven You stop in for a pack of cigaretes");
                        acrobat=false;               
                   //If too High
                   if (guess>magicNumb)
                        System.out.println("Too Much is Not Enough");
                   //If too Low
                   if (guess<magicNumb)     
                        System.out.println("Gimme Some more, Gimme some more");}
    }

    Ok what i need help with is when they get the
    integer, i need to either state another message and
    quit, or give them the option to play again?Okay, so, your overall code structure will look something like this: do {
        play();
        again = askIfPlayAgain();
    } while again;
    void play() {
        do {
            ask for a guess
            give answer
        } while (incorrect);
    } You don't have to use do/while. Plain old while will work.
    The main points are:
    1) You need two loops. The inner one keeps going within one round until they guess correctly, and the outer one keeps starting new rounds until they quit.
    2) You should break the problem down into smaller, more elemental pieces, rather than stuffing everything into one big blob in main.
    #1 will help you solve this problem, but #2 is an absolutely essential skill to learn.

  • Puzzle Game and new Game Problem

    Hello Java Programmers,
    Once again I have encountered a problem with my ongoing puzzle game. I have completed it all. Now I want my user to be able to start a new game in after they win. I tried repaint and update method with JFrame but it deosn't reshuffle the buttons. How can I do that. The code geos below.
    [/b]
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JOptionPane;
    public class PuzzleGame{
       String[] btn_Labels = {"1","2","3","4","5","6","7","8","9",
                            "10","11","12","13","14","15"," "};
       String[] labels = {"1","2","3","4","5","6","7","8","9",
                            "10","11","12","13","14","15"};
       private final int ONE = 1, TWO = 2, THREE = 3, FIVE = 5;
       private boolean WIN_STATE = false; 
       private JButton b[];
       public String clicked_btn_label = "";
       //Constructor method.
       public PuzzleGame(){
          showSplashScreen();
          initGame();
       public static void main(String args[]){
          PuzzleGame game = new PuzzleGame();
       //When a new Game started labels of buttons are shuffled using this method.
       public void shuffleNumbers(){
          String temp = null;   
          for(int j=0; j<16; j++){
          int k = (int)(Math.random()*16);
          temp = btn_Labels[j];
          btn_Labels[j] = btn_Labels[k];
          btn_Labels[k] = temp;           
       //Game initialization method.
       public void initGame(){
          b = new JButton[16];
          JPanel p = new JPanel();
          JFrame frame = new JFrame();
          shuffleNumbers();
          for(int i=0; i<16; i++){
             b[i] = new JButton();
             b.setText(btn_Labels[i]);
    b[i].setActionCommand(""+(i+1));
    for(int i=0; i<16; i++){
    b[i].addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent e){
    clicked_btn_label =(String)e.getActionCommand();
    doSwapping();
    checkWin();
    p.add(b[i]);
    p.setLayout(new GridLayout(4,4));
    frame.getContentPane().add(p);
    frame.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    Dimension dm = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (dm.width - 230)/2;
    int y = (dm.height - 240)/2;
    frame.setBounds(x,y,320,240);
    frame.setSize(340,240);
    frame.setVisible(true);
    //This method swaps the clicked button with the empty button if it doesn't violate rule.
    public void doSwapping(){
    int num = Integer.parseInt(clicked_btn_label);
    String temp;
    if( (num + ONE <= 16) && b[num].getText() == " " && num % 4 != 0){
    temp = b[num].getText();
    b[num].setText(b[num-ONE].getText());
    b[num-ONE].setText(temp);
    else if((num - TWO >= 0) && b[num-TWO].getText() == " " && ((num - ONE) % 4 != 0)){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num-TWO].getText());
    b[num-TWO].setText(temp);
    else if( (num + THREE < 16) && b[num+THREE].getText() == " "){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num+THREE].getText());
    b[num+THREE].setText(temp);
    else if( (num - FIVE >= 0) && b[num-FIVE].getText() == " "){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num-FIVE].getText());
    b[num-FIVE].setText(temp);
    // else{}
    public void checkWin(){
    WIN_STATE = true;
    for(int i=0; i<15; i++){
    if( b[i].getText() != labels[i])
    WIN_STATE = false;
    if(WIN_STATE == true){
    JOptionPane.showMessageDialog(null,"Congratulations You Have won the Game!","You Win",JOptionPane.INFORMATION_MESSAGE);
         initGame();
    public void showSplashScreen(){
    JWindow w = new JWindow();
    JPanel p = (JPanel)w.getContentPane();
    JLabel l = new JLabel(new ImageIcon("splash.jpg"));
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (d.width - 230)/2;
    int y = (d.height - 240)/2;
    p.add(l);
    w.setBounds(x,y,320,240);
    w.setVisible(true);
    try{
    Thread.sleep(10000);
    catch(Exception e){
    w.setVisible(false);
    [/b]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Sorry for violation. I would like to add a menubar to the application containing a single menu button for new game. adding a menubar is simple but how can i reshuffle the buttons using methods like update etc. or any other way.

Maybe you are looking for

  • Inbound Delivery Index Table

    Hi,   I tried to retrieve the delivery number with vendor code(LIFNR) in VLKPA-KUNDE.  But, nothing is returned.  Is there any other index table that provide the same information. Regards, Kit

  • UnmarshalException - Method not found

    I am using weblogic 7. The server and client are separate machines. When I ran the client, the following error appeared: Start server side stack trace: java.rmi.UnmarshalException: Could not unmarshal method ID; nested exception is: java.rmi.Unmarsha

  • .MOV files not opening - please help

    Can anyone help please: After having all sorts of problems with my iMac, I wiped my HD, reinstalled OSX (snow leopard) and restored my system using Time Machine. Now some, but not all, of my .MOV movies filmed on iPhone will not open.  I just get the

  • Whether SAP WAS supports Adobe interactive form implementation done in J2EE

    Hello, we are develoing a J2EE application, where we will develop Adobe interactibe forms. We need to know if the Adobe document services will support this implementation. The main confusion is around documentation, which discusses Web Dynpro only. P

  • SAP HANA Coud Portal is showing "HTTP Status 401 - Unauthorized"

    Hi ,   After clicking SAP HANA Cloud Portal From Cloud Cockpit its showing "HTTP Status 401-Unauthorized". Previously it was working fine for me and i have created and tested some widget also.But now i am getting this error.Please help me on that. Th