0

I am trying to get a function where, when you press enter, you start the game, but it isn't working. There is no error. I have followed a tutorial.

here is my code:

import greenfoot.*;

/**
 * Write a description of class Menu here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Menu extends World
{

    /**
     * Constructor for objects of class Menu.
     * 
     */
    public Menu()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(800, 500, 1); 

        prepare();
    }

     public void start()
    {
        {
            if(Greenfoot.isKeyDown("ENTER"))
            {
                MinionWorld MinionWorld= new MinionWorld();
                Greenfoot.setWorld(MinionWorld);
            }
        }
    }

    /**
     * Prepare the world for the start of the program. That is: create the initial
     * objects and add them to the world.
     */
    private void prepare()
    {
        Controls controls = new Controls();
        addObject(controls, 300, 100);
        controls.setLocation(175, 50);
    }
}
user902383
  • 8,420
  • 8
  • 43
  • 63

3 Answers3

0

Your code check if the Enter button is pressed at the moment it is run. You should use a KeyListener to catch the 'Enter' pressed event. If you are not using a GUI you can just use a Scanner and wait for the user to press Enter:

Scanner scanner = new Scanner(System.in);
scanner.nextLine();

This will wait until the user press Enter.

0
if(Greenfoot.isKeyDown("ENTER"))

Change this line to

if(Greenfoot.isKeyDown("enter"))

Key name for Enter is "enter" all small-caps.

mirmdasif
  • 6,014
  • 2
  • 22
  • 28
0

With your actual code now, what's happening is that when you call start(), it's checking ONCE, at the time you called start() if the user pressed enter.

One thing you can do is to put the code of your start method in a while loop, which will make it checking if the user pressed enter all the time, and when the condition is met, you can break the while loop to end the start method.

Here is an example of code:

public void start()
{
    while(true){
        if(Greenfoot.isKeyDown("ENTER"))
        {
            MinionWorld MinionWorld= new MinionWorld();
            Greenfoot.setWorld(MinionWorld);
            break; // Ends the loop
        }
    }
}
Kevyn Meganck
  • 609
  • 6
  • 15