Hangman game - logic problem

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.

Similar Messages

  • 2 player turn based game logic in c# for snake and ladder

    Hello programmers,
    I am developing a snake and ladder game in xaml and C#.(windows 8.1 app)
    my question is:
    1) I am unable to think about the solution for player turn, I have build the game logic for single player and its working fine. please provide some solutions or the concept.
    2) I have build the same game logic with two different ways, one with nested if else and the next with array which one would be good for performance.
    and I also want to know about windows Azure for online score and multi player game service.

    Hi,
    I am not very familiar with the multiplayer Game development. For multiplayer games, you'll need to set up a matchmaking server and have the clients connect to it. It can then pair them off and facilitate communications. If the clients have publicly available
    network addresses then it can introduce them and they can talk directly to each other.There isn't anything built in for this so you'll need to either build your own or find a third party implementation. If you are using Unity3d then check out
    http://docs.unity3d.com/Documentation/Components/net-MasterServer.html
    Also, you can use Xbox services, and I find an article below:
    https://msdn.microsoft.com/en-us/library/bb975801.aspx
    For windows Azure problem, you should go to windows Azure forum.
    Best Wishes!
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. <br/> Click <a
    href="http://support.microsoft.com/common/survey.aspx?showpage=1&scid=sw%3Ben%3B3559&theme=tech"> HERE</a> to participate the survey.

  • 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.");
    }THANKS

    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.");
    }THANKS

  • The logical problem in turnover in  for ?

    Welcome
    wrote this code, everything is true but there is a logical problem to be solved first idea of this program is a moving train to the contrary, it can stop and operated once again and that can add cars and locomotives and can delete it but there is a problem when adding that the train carriages have remained stable cart after the first turnover Thus ...
    THAT shows us the error ..
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Train extends JFrame implements ActionListener{
        private boolean check = false;
        private boolean stopped = true;
        private boolean add = false;
        private int trainPlace = 0;
        private int INDEX_START = 0;
        public int speed = 300;
        private ImageIcon CurrentImage ;
        private boolean front=true, back=false ;
        private int carrNum = 0 ;
        private JPanel screen, area , controlroom;
        private JButton[][] street;
        public JButton[] keybord;
        private String s[] = {"Start","Back","Fast","Slow","Add Carriage","Delete Carriage","Rest","Check","Desiners"};
        private ImageIcon images[][] ={{
                        new ImageIcon("images/UpRight.jpg"),
                        new ImageIcon("images/RightDown.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        {new ImageIcon("images/Vert.jpg"),
                        new ImageIcon("images/DownRight.jpg"),
                        new ImageIcon("images/Horiz.jpg"),
                        new ImageIcon("images/RightDown.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/Vert.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/Vert.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/Vert.jpg"),
                        new ImageIcon("images/UpRight.jpg"),
                        new ImageIcon("images/Horiz.jpg"),
                        new ImageIcon("images/RightUp.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/DownRight.jpg"),
                        new ImageIcon("images/RightUp.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg"),
                        new ImageIcon("images/NoTrack.jpg")}};
        private ImageIcon frontImagesTrain[]={
                        new ImageIcon("images/TrainDown.jpg"),
                        new ImageIcon("images/TrainDown.jpg"),
                        new ImageIcon("images/TrainLeft.jpg"),
                        new ImageIcon("images/TrainLeft.jpg"),
                        new ImageIcon("images/TrainDown.jpg"),
                        new ImageIcon("images/TrainLeft.jpg"),
                        new ImageIcon("images/TrainUp.jpg"),
                        new ImageIcon("images/TrainUp.jpg"),
                        new ImageIcon("images/TrainUp.jpg"),
                        new ImageIcon("images/TrainUp.jpg"),
                        new ImageIcon("images/TrainRight.jpg"),
                        new ImageIcon("images/TrainDown.jpg"),
                        new ImageIcon("images/TrainRight.jpg"),
                        new ImageIcon("images/TrainDown.jpg")};
            private ImageIcon trackImagesTrain[]={
                    new ImageIcon("images/Vert.jpg"),
                    new ImageIcon("images/RightUp.jpg"),
                    new ImageIcon("images/Horiz.jpg"),
                    new ImageIcon("images/UpRight.jpg"),
                    new ImageIcon("images/RightUp.jpg"),
                    new ImageIcon("images/DownRight.jpg"),
                    new ImageIcon("images/Vert.jpg"),
                    new ImageIcon("images/Vert.jpg"),
                    new ImageIcon("images/Vert.jpg"),
                    new ImageIcon("images/UpRight.jpg"),
                    new ImageIcon("images/RightDown.jpg"),
                    new ImageIcon("images/DownRight.jpg"),
                    new ImageIcon("images/Horiz.jpg"),
                    new ImageIcon("images/RightDown.jpg")};
              private ImageIcon carrinImagesTrain[]={
                        new ImageIcon("images/Carriage1Down.jpg"),
                        new ImageIcon("images/Carriage1Down.jpg"),
                        new ImageIcon("images/Carriage1Left.jpg"),
                        new ImageIcon("images/Carriage1Left.jpg"),
                        new ImageIcon("images/Carriage1Down.jpg"),
                        new ImageIcon("images/Carriage1Left.jpg"),
                        new ImageIcon("images/Carriage1Up.jpg"),
                        new ImageIcon("images/Carriage1Up.jpg"),
                        new ImageIcon("images/Carriage1Up.jpg"),
                        new ImageIcon("images/Carriage1Up.jpg"),
                        new ImageIcon("images/Carriage1Right.jpg"),
                        new ImageIcon("images/Carriage1Down.jpg"),
                        new ImageIcon("images/Carriage1Right.jpg"),
                        new ImageIcon("images/Carriage1Down.jpg")};
        private int[]frontPath={13, 18,17,16,21,20,15,10,5,0,1,6,7,8};
      private int[]frontPath2={8, 13,18,17,16,21,20,15,10,5,0,1,6,7};  
        private ImageIcon icon;
        private JLabel labelInfo;
        public Train () {  
           screen = new JPanel(new GridLayout(1,1));
           Font f =new Font ("Sanserif",Font.BOLD,18);
           labelInfo = new JLabel("WELCOM" ,JLabel.CENTER);
           labelInfo.setFont(f);
           screen.setBackground(Color.red);
           screen.add(labelInfo);
           getContentPane().add(BorderLayout.NORTH,screen );
            street = new JButton[5][5];
            area = new JPanel (new GridLayout(5,5));
            for(int r=0; r<5; r++) 
                for (int c=0; c<5; c++){
                    street[r][c] = new JButton("", images[r][c]);
                    area.add(street[r][c]);
            getContentPane().add(BorderLayout.CENTER,area );   
            keybord = new JButton[9];
            controlroom = new JPanel(new GridLayout(5,2));   
    //        ActionHandler handler = new ActionHandler();
            for (int i=0; i <9; i++)
                keybord[i] = new JButton(s);
    keybord[i].addActionListener(this);
    controlroom.add(keybord[i]);
              keybord[i].setEnabled(false);
              keybord[7].setEnabled(true);
    getContentPane().add(BorderLayout.SOUTH,controlroom );
    public void moveTrainFront(){
    int trainPlace1 = trainPlace;
    try{
    if (trainPlace == frontPath.length-1) trainPlace = 0;
    else trainPlace ++;
                   if (carrNum == 0 )
         int i = frontPath[trainPlace]/5;
         int j = frontPath[trainPlace] - i * 5;
         int r = frontPath[trainPlace1]/5;
         int c = frontPath[trainPlace1] - r * 5;
         street[i][j].setIcon(frontImagesTrain[trainPlace]);
         street[r][c].setIcon(trackImagesTrain[trainPlace1]);
                   else
                        int i1 = frontPath[trainPlace]/5;
                        int j1 = frontPath[trainPlace] - i1 * 5;
                        street[i1][j1].setIcon(frontImagesTrain[trainPlace]);     
                        int trainPlace2 = trainPlace;
                        for (int z = 1; z <= carrNum; z++)
    if (trainPlace2 - z < 0) trainPlace2 = 13;
                                  int i2 = frontPath[trainPlace2 - z]/5;
                                  int j2 = frontPath[trainPlace2 - z] - i2 * 5;
                                  street[i2][j2].setIcon(carrinImagesTrain[trainPlace2 - z]);
              int r1 = frontPath[trainPlace1 - carrNum]/5;
                        int c1 = frontPath[trainPlace1 - carrNum] - r1 * 5;
                        street[r1][c1].setIcon(trackImagesTrain[trainPlace1 - carrNum]);
    }catch(ArrayIndexOutOfBoundsException aiex){System.out.println("the array out of index");}
    // Move train Back
    public void moveTrainBack(){
    int trainPlace1 = trainPlace;
    try{
    if (trainPlace == 0) trainPlace = 13;
    else trainPlace--;
    int i = frontPath[trainPlace]/5;
    int j = frontPath[trainPlace] - i * 5;
    int r = frontPath[trainPlace1]/5;
    int c = frontPath[trainPlace1] - r * 5;
    street[i][j].setIcon(frontImagesTrain[trainPlace]);
    street[r][c].setIcon(trackImagesTrain[trainPlace1]);
    }catch(ArrayIndexOutOfBoundsException aiex){System.out.println("the array out of index");}
    public void setRest(){
    setStop(true);
              setSpeed(300);
    int i = frontPath[trainPlace]/5;
    int j = frontPath[trainPlace] - i * 5;
    street[i][j].setIcon(trackImagesTrain[trainPlace]);
    trainPlace = 0;
    i = frontPath[trainPlace]/5;
    j = frontPath[trainPlace] - i * 5;
    street[i][j].setIcon(frontImagesTrain[0]);
    public void setCheck (boolean c)
    int i = frontPath[trainPlace]/5;
    int j = frontPath[trainPlace] - i * 5;
    street[i][j].setIcon(frontImagesTrain[0]);
    check = c ;
    public boolean getCheck (){ return  check ;}
    public void setSpeed (int s){speed = s ;}
    public int getSpeed(){return  speed;}
    public void setStop(boolean s){stopped = s ;}
    public boolean getStop(){return  stopped ;}
    public void setBack(boolean s){back = s ;}
    public boolean getBack(){return  back;}
         public void setAdd(){carrNum++ ;}
    public boolean getAdd(){return  add;}
    // Action
         public void actionPerformed(ActionEvent e){
              if(e.getSource()==keybord[0])//Start
              if (stopped)
              keybord[0].setText("Stop");
                   setStop(false);
                   labelInfo.setText("Running");
    else      
                   {    setStop(true);
                   keybord[0].setText("Start");
                        labelInfo.setText("Stop");
              if(e.getSource()==keybord[1])//Front And Back
              if (!back)
                   setBack(true);
              keybord[1].setText("Front");
                   labelInfo.setText("Back");
              else      
                   setBack(false);
              keybord[1].setText("Back");
                   labelInfo.setText("Front");
              }     else if (e.getSource()==keybord[2])//Fast
              if (speed <= 0)
              labelInfo.setText("You've arrived the maximum speed : " + getSpeed());
              else {      setSpeed(speed  - 10);
                   labelInfo.setText("The Train speed is slow down to : " + getSpeed());
         else if(e.getSource()==keybord[3])//Slow
              {setSpeed(speed + 10);
                    labelInfo.setText("The Train speed is pulled up to : "+getSpeed());
    else if(e.getSource()==keybord[4]) //ADD carrin
                        setAdd();
                        labelInfo.setText("Add Carriage");
              //setStop(false);
    else if(e.getSource()==keybord[5]) //Delete carrin
                   labelInfo.setText("Delete Carrin");
         else if(e.getSource()==keybord[6]) //Rest
                   setRest();     
              labelInfo.setText("Rest");
         else if (e.getSource()==keybord[7]) //Check
         setCheck(true);
         keybord[7].setEnabled(false);
         keybord[0].setEnabled(true);
         keybord[1].setEnabled(true);
         keybord[2].setEnabled(true);
         keybord[3].setEnabled(true);
         keybord[4].setEnabled(true);
         keybord[5].setEnabled(true);
         keybord[6].setEnabled(true);
         keybord[8].setEnabled(true);
         labelInfo.setText("The Train is Checked");
    else if(e.getSource()==keybord[8]) //desiners
         String x = "";
                   labelInfo.setText("Desiners About");
                   JOptionPane.showMessageDialog(null,"The Progect is Under The Auspices of:"
                   + "\n??" + "\n" + "\n ??" +
                   "\n ??" + "\n??" + "\n ??" + "\n" + "\n" + "\n?? " + "\n C 2007");     }     
    This main ..
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.lang.Thread;
    public class TestTrain{     
        public static void main(String[]args){
            Train train = new Train ();
              MoveTrain mt = new MoveTrain(train);
            train.setTitle("Train");
            train.setSize(421,550);
            train.setVisible(true);
            train.addWindowListener (
            new WindowAdapter (){
                 public void windowClosing(WindowEvent e ){
                      System.exit(0);
              mt.start();
    }This Threads
    import java.lang.Thread;
    public class MoveTrain extends Thread {
         Train train ;
        public MoveTrain (Train train){
               this.train= train;
         public void run(){
               while(!train.getCheck());
               while (train.getCheck()){
                    try {sleep (train.getSpeed()); }
                    catch (InterruptedException e ){System.out.println("unknown error");}
                     if (!train.getStop())
                        if(!train.getBack())
                                {train.moveTrainFront();
                          else  train.moveTrainBack();
    }This Link image icon ..
    http://www.geocities.com/alhairan_2003/as/777/UpRight.jpg
    http://www.geocities.com/alhairan_2003/as/777/Vert.jpg
    http://www.geocities.com/alhairan_2003/as/777/TrainUp.jpg
    http://www.geocities.com/alhairan_2003/as/777/TrainRight.jpg
    http://www.geocities.com/alhairan_2003/as/777/TrainLeft.jpg
    http://www.geocities.com/alhairan_2003/as/777/TrainDown.jpg
    http://www.geocities.com/alhairan_2003/as/777/Train.jpg
    http://www.geocities.com/alhairan_2003/as/777/RightUp.jpg
    http://www.geocities.com/alhairan_2003/as/777/RightDown.jpg
    http://www.geocities.com/alhairan_2003/as/777/NoTrack.jpg
    http://www.geocities.com/alhairan_2003/as/777/Horiz.jpg
    http://www.geocities.com/alhairan_2003/as/777/DownRight.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage3Up.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage3Right.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage3Left.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage3Down.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage2Up.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage2Right.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage2Left.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage2Down.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage1Right.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage1Left.jpg
    http://www.geocities.com/alhairan_2003/as/777/Carriage1Down.jpg
    thanks :)

            String[] car1Names = {
                "Carriage1Down", "Carriage1Left", "Carriage1Down", "Carriage1Right"
            };The first image name should be "Carriage1Up" but it is missing in your directory.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class MC6 implements Runnable, ActionListener {
        JLabel[] grid;
        BufferedImage[] trackImages;
        BufferedImage[] trainImages;
        BufferedImage[][] carImages;
        int[] imageKeys;
        int[] trackKeys;
        int[] forwardKeys;
        int[] reverseKeys;
        int keyIndex = 0;
        int carCount = 0;           // [0 - 3]
        boolean goingAhead = true;
        boolean changeDirections = false;
        Thread thread = null;
        boolean moving = false;
        final int DELAY = 1000;
        public MC6() {
            loadImages();
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            if(ac.equals("START"))
                changeDirections = false;
                start();
            if(ac.equals("STOP"))
                stop();
            if(ac.equals("FORWARD") || ac.equals("REVERSE"))
                changeDirections = true;
            if(ac.equals("ADD CARRIAGE"))
                carCount += (carCount+1 <= 3) ? 1 : 0;
            if(ac.equals("REMOVE CARRIAGE")) {
                int carIndex = getCarIndex(carCount);
                int trackIndex = trackKeys[carIndex];
                int imageIndex = imageKeys[carIndex];
                grid[trackIndex].setIcon(new ImageIcon(trackImages[imageIndex]));           
                carCount -= (carCount-1 >=0 ) ? 1 : 0;
        public void run() {
            while(moving) {
                // Clear track in preparation for next advance.
                if(changeDirections) {
                    clearTrack();
                    // Adjust keyIndex by one increment in the direction of travel
                    // to allow it to return it to its current position after the
                    // next advance in position (further below).
                    advance();
                    goingAhead = !goingAhead;
                    changeDirections = false;
                } else {
                    // Replace last car with track image before train advances.
                    int carIndex = getCarIndex(carCount);
                    int trackIndex = trackKeys[carIndex];
                    int imageIndex = imageKeys[carIndex];
                    grid[trackIndex].setIcon(new ImageIcon(trackImages[imageIndex]));
                // Move to next position on the track.
                advance();
                // Set locomotive.
                setLocomotive();
                // Set the cars following the locomotive.
                setCars();
                try {
                    Thread.sleep(DELAY);
                } catch(InterruptedException e) {
                    System.out.println("interrupted");
                    stop();
        private int getCarIndex(int carNumber) {
            int n = carNumber;
            int index;
            if(goingAhead) {
                index = keyIndex-n;
                if(index < 0)
                    index += trackKeys.length;
            } else {
                index = (keyIndex+n) % trackKeys.length;
            return index;
        private void advance() {
            keyIndex = goingAhead ?
                           (keyIndex+1 > trackKeys.length-1) ? 0 : keyIndex+1
                           (keyIndex-1 < 0) ? trackKeys.length-1 : keyIndex-1;
        private void clearTrack() {
            // Remove all cars from track before direction change.
            for(int j = 0; j < carCount; j++) {
                int carIndex = getCarIndex(j+1);
                int trackIndex = trackKeys[carIndex];
                int imageIndex = imageKeys[carIndex];
                grid[trackIndex].setIcon(new ImageIcon(trackImages[imageIndex]));
        private void setLocomotive() {
            int trackIndex = trackKeys[keyIndex];
            int imageIndex = goingAhead ? forwardKeys[keyIndex]
                                        : reverseKeys[keyIndex];
            grid[trackIndex].setIcon(new ImageIcon(trainImages[imageIndex]));
        private void setCars() {
            for(int j = 0; j < carCount; j++) {
                int carIndex = getCarIndex(j+1);
                int trackIndex = trackKeys[carIndex];
                int imageIndex = goingAhead ? forwardKeys[carIndex]
                                            : reverseKeys[carIndex];
                grid[trackIndex].setIcon(new ImageIcon(carImages[j][imageIndex]));
        private void start() {
            if(!moving) {
                moving = true;
                thread = new Thread(this);
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.start();
        public void stop() {
            moving = false;
            if(thread != null)
                thread.interrupt();
            thread = null;
        private void loadImages() {
            String[] trackNames = {
                "UpRight", "RightDown", "Vert", "DownRight", "Horiz", "RightUp", "NoTrack"
            String[] trainNames = { "TrainUp", "TrainLeft", "TrainDown", "TrainRight" };
            String[] car1Names = {
                "Carriage1Down", "Carriage1Left", "Carriage1Down", "Carriage1Right"
            String[] car2Names = {
                "Carriage2Up", "Carriage2Left", "Carriage2Down", "Carriage2Right"
            String[] car3Names = {
                "Carriage3Up", "Carriage3Left", "Carriage3Down", "Carriage3Right"
            trackImages = getImages(trackNames);
            trainImages = getImages(trainNames);
            BufferedImage[] car1Images = getImages(car1Names);
            BufferedImage[] car2Images = getImages(car2Names);
            BufferedImage[] car3Images = getImages(car3Names);
            carImages = new BufferedImage[][]{ car1Images, car2Images, car3Images };
        private BufferedImage[] getImages(String[] ids) {
            BufferedImage[] images = new BufferedImage[ids.length];
            for(int j = 0; j < ids.length; j++) {
                String path = "images/" + ids[j] + ".jpg";
                try {
                    images[j] = ImageIO.read(new File(path));
                } catch(IOException e) {
                    System.out.println("Read error for " + path +
                                       ": " + e.getMessage());
                    images[j] = null;
            return images;
        private JPanel getCenterComponent() {
            imageKeys = new int[] {
                0, 1, 3, 4, 1,  2,  5,  4,  0,  5,  3,  2,  2, 2
            trackKeys = new int[] {
                0, 1, 6, 7, 8, 13, 18, 17, 16, 21, 20, 15, 10, 5
            forwardKeys = new int[] {
                0, 3, 2, 3, 3,  2,  2,  1,  1,  2,  1,  0,  0, 0
            reverseKeys = new int[] {
                1, 0, 1, 1, 0,  0,  3,  3,  0,  3,  2,  2,  2, 2
            grid = new JLabel[25];
            JPanel panel = new JPanel(new GridLayout(5,0));
            for(int j = 0; j < grid.length; j++) {
                ImageIcon icon;
                int index = getIndexForValue(j);
                if(index != -1) {
                    icon = new ImageIcon(trackImages[imageKeys[index]]);
                } else {
                    icon = new ImageIcon(trackImages[6]);
                grid[j] = new JLabel(icon);
                panel.add(grid[j]);
            return panel;
        private int getIndexForValue(int value) {
            for(int j = 0; j < trackKeys.length; j++) {
                if(value == trackKeys[j])
                    return j;
            return -1;
        private JPanel getControls() {
            String[] ids = {
                "Start", "Stop", "Forward", "Reverse", "Add Carriage", "Remove Carriage"
            JPanel panel = new JPanel(new GridLayout(0,2));
             for(int j = 0; j < ids.length; j++) {
                JButton button = new JButton(ids[j]);
                button.setActionCommand(ids[j].toUpperCase());
                button.addActionListener(this);
                panel.add(button);
            return panel;
        public static void main(String[] args) {
            MC6 test = new MC6();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getCenterComponent());
            f.getContentPane().add(test.getControls(), "Last");
            f.pack();
            f.setLocation(200,100);
            f.setVisible(true);
    }

  • I purchased gems from the game legends at war and the game has problems and I've lost the things I've paid good money for how do I get a refund

    I purchased gems from the game legends at war and the game has problems and I've lost the things I've paid good money for how do I get a refund gree offer no support it takes days to get a reply then they offer no help, if Ive paid for something I expect to get it and being a paying customer I expect support when there is problems

    Simon ~ Welcome to the Support Communities. See the iTunes Store option here:
    http://www.apple.com/support/itunes/contact/

  • Logical problem using vectors

    Hi and Happy New Year,
    I have a vector in my java application which contains a number of elements that is not fix which means each time the number of elements might change.
    I want to retrieve the elements of the vector 3 by 3 its like table records paging in jsp , asp or php
    - lets say this time i've got 10 elements in my vector , I have to JButtons previous_3 and next_3
    - The first time the program runs I want to get the first three elements of the vector (0 to 2)
    - By clicking on the next_3 button I want to get the next 3 ( 3 to 5) and so on... providing that the exist
    - By clicking on the privious_3 button I want to get the previous 3 ( 0 to 2) in this instance and so on... providing that the exist
    Can anyone give me a hint as how to solve this problem at least give me some ideas cause i am lacking of ideas my brain is frozen, I know that is it more a logical problem that a programming one
    I 've done this kind of thing in Asp and PHP but as I am new to Java
    I just can not figure out how to tackle this issue

    You may want to use the modulus function.
    lets look at an example.
    pseudo code
    vector v = new vector()
    v.size = 10; //lets say there are 10 elements in the vector
    int n = 3; // you want to jump maximum 3 elements each time
    // you can jump 3.3 times before running outide the scope
    // of the vector, well after the third time you must check
    // how many elements that is left in the vector, this is
    // done by modulus n%10 = 1, this means that the last time
    // you can not jump more than 1 element.
    I have to go now so I cant give you any code to cope with the problem, Ill be back in 3 hours, maybe I can give a good axample, but this outline is the way to go.
    TheLaw

  • Poker game logic(again)

    i think that this will be the last thread that i will start on the subject of poker.
    if you have not looked at the other poker game logic threads, it might help.
    if figured out ways to check for repeaded cards(2,3,4,2&2,2&3) and how to do the flush. I am only having trouble figuring out if ther is one of the straights(cards in ascending order).
    you can check the suit and the rank of each card and there are 5. how do you figure if they are in a particular order?
    THANX!

    Sort the card array by face value of card. then
    boolean straight()
    if( ((a[0]+1) == a[1]) && ((a[1]+1) == a[2]) && ... etc. )
    return true;
    You will have to account for ace-2-3-4-5 too though. or 10-j-q-k-ace depending on the value you assign an ace.

  • Hangman game

    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 java

    well 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.

  • Lenovo 3000 n200 Type: 0769 game graphics problem

    Hi,
    I have a Lenovo 3000 n200 Type 0769 laptop which served me well at university with my 3D modelling in SolidWorks for my projects. However, when I tried to run games on it, the games always crash, even on a very low setting graphics setting which is extremely frustrating. The only game I have managed to run successfully with no problems is Football Manager (providing I dont use the 3d game play as when I do, like all other games I have tried, it crashes.). What do I need to upgrade to successfully run games on my laptop and also, (if it is only a new graphics card that is required) where can I find out which cards are compatible with my laptop?
    Running games is the only problem I am finding with the laptop and any help anyone can give me will be very much appreciated as I see a few other people who have posted in the forum have had the same problem with no luck with help on here.
    Cheers.
    - Pete
    PS. The games I have tried running with no success include; The Sims 2, Lord Of The Rings - Battle For Middle Earth 1 & 2, Command & Conquer Generals, Command & Conquer 3 and Warhammer Dawn Of War

    I don't know about the desktops, but Lenovo laptops are the worst I have ever used. I have had mine nearly a year and the amount of problems I have had with it is rediculous, along with this problem, the hard drive has broken and needed to be replaced, the finger print scanner is broken and does not recognise the only finger prints that have been registered on the laptop, and now it has broken again and i cannot get passed the rescue and recovery screen. NO ONE should buy this laptop or any lenovo laptops like it, they are unbelievably unreliable!

  • Flash as2 game animation, problem.

    hello i am making a flash animation game but i have a problem, i have my guy running and everything its all gifs, so when he stops its a gif its not one picture its 4 of em (gif) which i made them all compressed into a gif and added to my library then added that to my flash made it work blah blah blah-
    well my problem is when my guy runs left he turn right after i let go of the key i no whats it is doing it using my 1 animation i have in their for standing  i to add my other animation which he standing left basically he runs left after i press left then i let go he turns right, i need to know how to make it so either when i let go of the (LEFT) key it uses my animation ('still2') which is him facing left which i need i have him running right and he stays right after so thats good, or if u know if theres a way i can make the code say like after i let go of like left it uses gotoAndStop('still2') then for running right it uses gotoAndStop('still') so he dosent turn around after i let go of left! well i hope u can find out, and its all animated, so dont just make it so it dosent stop using the animation of left or right, cause then hes running in place for enternity thanks heres my code.
          var rollSpeed = Number=14;
         ichigo_mc.onEnterFrame = function() {
          if (Key.isDown(Key.RIGHT)) {
           this._x += rollSpeed;
           this.gotoAndStop("right");
          } else if (Key.isDown(Key.LEFT)) {
           this._x -= rollSpeed;
           this.gotoAndStop("left");
          } else {
           this.gotoAndStop("still");

    no its actually not a school project just i want to know how to make a game, and i dont know really anything about flash, but i have in my picture of my guy another layer so theres each indivudual layer like i have in my pic of my guy the still still2 running animation 1 n 2 and both my attack things, if you would to see my project so far ask me and i send the file and it should show my guy and his animations...
    heres my code so far.. idk y but i like putting at the end
       var rollSpeed = Number=14;
         var facingRight = true;
         ichigo_mc.onEnterFrame = function() {
          if (Key.isDown(Key.RIGHT)) {
           this._x += rollSpeed;
           this.gotoAndStop("right");
           facingRight = true;
          } else if (Key.isDown(Key.LEFT)) {
           this._x -= rollSpeed;
           this.gotoAndStop("left");
           facingRight = false;
       } else if (Key.isDown(Key.SPACE)) {
        this.gotoAndStop("atack2");
          } else {
           if (facingRight) {
             this.gotoAndStop("still");
           } else {
             this.gotoAndStop("still2");

  • Multiple Game Center Problems

    I dont expect to get a lot of solutions but I wanted to know if I was the only one having the following issues:
    1) Someone sends me a friend request..I accept it...on the "Me" page it shows I have a friend but when I click on "Friends" none show up.
    2)A friend sends me a game invite I click accept and all it says is waiting for my friend to start the game.
    3) I cant seem to send an invite out...all it says is waiting and nothing happens.
    Again if there are solutions...great!...if not I want to know if its my 4 generation ipod touch thats not right or the game center app.
    Thanks in advance!

    That problem happened to me, also. Then, I fixed it.
    Instructions:
    1. Open multitasking bar and close everything. (Hold down and press the X's.
    2. Then, power off.
    3. Turn back on.
    4. This is where the problem lies: TURN ON ALL THE NOTIFICATIONS FOR GAMECENTER.
    It should work now.

  • Game Center Problems

    Hey guys,
    Ok so recently i have been having problems with my iphone 4's game center, i am running 4.2.1
    So today for some reason there seems to be 2 different accounts under the same email because i sign in to my game center and I see my account which has 1 friend, 37 games played, and 87 achievements but then I go into a game called overkill and it tells me to sign in. Use Exisiting Account, Create account or cancel, I go into use existing account and put in the pass word and I play it.
    When i exit the game and go back to springboard then to game center again it says I have 0 friends, 9 games played and 30 achievements.
    Then again I sign out of game center and sign in again and it goes back to the first account records, 1 friend, 37 games, and 87 achievements and there is no record of my previous games!
    WHAT SHOULD I DOOOO!?!??
    Thanks

    I had the same problem  , Finally i  solve the problem.
    1- Delete the game which  has the problem
    2- go ifile  /var/stash/libexec.ykDhbq
    see  installd  and instald.backup
    3-change the installd   to intald.new
    4-change the name instald.backup  to  ınstald
    5- respring
    6- download same game again and login gamecenter . it will be ok.
    dont forget to rename instad and instald.backup files .. change again make them like the old time
    and respring

  • Game Center problems only on ipad not iphone

    So I never bothered to check game center on my ipad and i dont think i ever launched it. I have it working and running fine on my iphone and also rarely use it. I started playing Clash of Clans now and I want to sync it with game center on my ipad. Problem is I cant get it to load the games. It logs me in and i can see "ME" but if i click on games or friends it says "not Available" Unable to load data due to network connectivity issues or errors. I want it get it working in order to save my Clash of Clans data and or play it on my iphone.
    I have tried many ways and methods as i have searched on google to make it work, and nothing works. Reseting settings, hard reset, logging off resetting and restarting and nothing. I even went to apple store and tech couldnt get it to work. Said id have to do a reset as a new ipad. I dont mind, but im worried because i dont know where Clash of clans saves its info and im too much in and bought in game gems to just lose the progress. I just synced my ipad and tempted to do a restore from back up and see if that works, but im scared again of CoC being lost and having to start from scratch.. What can i do? The tech said Game center isnt reading the wifi in the ipad and there is an internal conflict. Now i had my friend log into his gamecenter account in my ipad and voila, his games show up, friends, and progress. Log him out, i log in and it doesnt show crap. I go to my iphone, game center is up and running perfect. Any ideas??

    BBump. Help pls

  • HT4314 Game Center Problem

    There isn't a catagory for this, but... Game Center games don't show up for me. None of them, not my friend's or mine. (Yes, I have used these games multiple times before) Help? (I wasn't sure where to ask this ^^)

    I am having the same problem and I also have an iPod 2nd Gen.  When I sign into Game Center it shows my profile, how many friends I have on game center, the number of games I have and my achievements.  When I tap on the games app all it says is "Find Game Center Games" it doesn't list any of my games yet when I am playing the games the little icon on top of the screen always says "Welcome back, geew66" whenever I open a game.  I finally got around to calling Apple to find out why this is happening.  They informed me it is a glitch on their end and I needed to plug my iPod into my computer and give them remote access to my iPod to fix it.  After doing this, the guy on the phone then informed me that in order to continue I needed to purchase extended warranty (or whatever it was that he called it) for $99 for 1 year and then he would be able to fix the glitch.  Needless to say, I didn't pay them the $99 and my Game Center doesn't work.  I just figure that if it is their glitch to begin with, why should we have to pay that kind of money to get it fixed.  Any suggestions on how to fix this problem without the huge expense would be greatly appreciated.  I am not at all impressed with the money hungry customer service I received from Apple. 

  • Flash games, serious problem with windows 7 bootcamp

    when you open a webpage that has a flash game, windows 7 bootcamp stucks from time to time, with no reason! why is this happening? using firefox. tried safari the same thing, and tried latest flash player on both. try facebook games or google random flash games most of them cause windows 7 to stuck or go slow! suggestions please, does anyone else have the same problem?

    sorry the whole win 7 freezee on mbp 13", wait for apple update (i hope they notice)! now running XP SP3 and runs great!!! "laptop 2 go drivers" and runs games perfect!

Maybe you are looking for