vendredi 23 mars 2018

KeyListener with switch on loop for coin toss game in Java

I'm having a problem with a coin toss simulation. I've been working with java for just a few hours so bear with me. What I want the program to do is show the title once, give the menu (press T....) run the random simulation and loop back to the menu unless player presses Q. Everything worked as I was testing every addition individually. The random generator, the printing but as you can probably tell, I have no idea how to implement a KeyListener. How do I make make it work?

import java.util.Random;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class CoinToss
{

    public void menu implements KeyListener
    {
        addKeyListener(this);
        System.out.println("*******************************************************");
        System.out.println("**********************WELCOME**************************");
        System.out.println("*******************TO COIN TOSS************************");
        System.out.println("*******************************************************");
    }
    @Override
    public void keyPressed(KeyEvent e) 
    {
        boolean gameOn = true;
        while (gameOn == true)
        {
            Random rand = new Random();
            System.out.println("PRESS T TO TOSS A COIN \nPRESS Q TO QUIT");
            switch(e.getKeyCode())
            {
                case KeyEvent.VK_T:
                int n = rand.nextInt(2);
                if(n == 0)
                {
                    System.out.println("HEADS");
                }
                if(n == 1)
                {
                    System.out.println("TAILS");
                }
                if(n == 2)
                {
                    gameOn = true;
                }
                break;
                case KeyEvent.VK_Q:
                System.out.println("GOOD BYE! \nSEE YOU NEXT TIME!");
                gameOn = false;
                break;
            }    
        }
    }
    @Override
        public void keyReleased(KeyEvent e) 
        {

        }
     @Override
        public void keyTyped(KeyEvent e) 
        {

        }

}




Aucun commentaire:

Enregistrer un commentaire