I'm building a game using Java for a university project. The game had to use a textual interface at first, and only later we had to add a GUI.
I have a thread running the game logic and updating the game model, and a separate thread, the one with the main function, having the JFrame instantiated on, where I then switch panels according to the game state (the controller tells the gui which frame to display with a setPage method).
Getting the user input, however, is what is driving me crazy now.
With the textual interface, all I had to do to get the user input was to call a method, something like getPlayerNum, and after the user put in the number and pressed enter I would have the input back to the controller.
All the game logic is implemented in a game loop, asking for input when it needs it and notifying the output to the view.
How can I emulate a similar behavior now that I'm forced to use a event-based gui?
How can I block the method call until the user clicks a button, and then have the method return the correct value?
Kudos for developing an independent game model. As a prelude to designing your GUI, start with this very simple game. Add a TextView that listens to the model and reports on game progress. This will help you see how the GUI works, and it may help you decide what additional features you may need in your model.
Related
This question already has an answer here:
How to stop Java from running the entire code with out waiting for Gui input from The user
(1 answer)
Closed 5 years ago.
I'm a rather basic programmer who has been assigned to make a GUI program without any prior experience with creating a GUI. Using NetBeans, I managed to design what I feel the GUI should look like, and what some of the buttons should do when pressed, but the main program doesn't wait for the user's input before continuing. My question is, how do I make this program wait for input?
public class UnoMain {
public static void main(String args[]) {
UnoGUI form = new UnoGUI(); // GUI class instance
// NetBeans allowed me to design some dialog boxes alongside the main JFrame, so
form.gameSetupDialog.setVisible(true); // This is how I'm trying to use a dialog box
/* Right around here is the first part of the problem.
* I don't know how to make the program wait for the dialog to complete.
* It should wait for a submission by a button named playerCountButton.
* After the dialog is complete it's supposed to hide too but it doesn't do that either. */
Uno Game = new Uno(form.Players); // Game instance is started
form.setVisible(true); // Main GUI made visible
boolean beingPlayed = true; // Variable dictating if player still wishes to play.
form.playerCountLabel.setText("Players: " + Game.Players.size()); // A GUI label reflects the number of players input by the user in the dialog box.
while (beingPlayed) {
if (!Game.getCompleted()) // While the game runs, two general functions are repeatedly called.
{
Player activePlayer = Game.Players.get(Game.getWhoseTurn());
// There are CPU players, which do their thing automatically...
Game.Turn(activePlayer);
// And human players which require input before continuing.
/* Second part of the problem:
* if activePlayer's strategy == manual/human
* wait for GUI input from either a button named
* playButton or a button named passButton */
Game.advanceTurn();
// GUI updating code //
}
}
}
}
I've spent about three days trying to figure out how to integrate my code and GUI, so I would be grateful if someone could show me how to make this one thing work. If you need any other information to help me, please ask.
EDIT: Basically, the professor assigned us to make a game of Uno with a GUI. There can be computer and human players, the numbers of which are determined by the user at the beginning of the game. I coded the entire thing console-based at first to get the core of the game to work, and have since tried to design a GUI; currently this GUI only displays information about the game while it's running, but I'm not sure how to allow the code to wait for and receive input from the GUI without the program charging on ahead. I've investigated other StackOverflow questions like this, this, this, or this, but I cannot comprehend how to apply the answers to my own code. If possible, I'd like an answer similar to the answers in the links (an answer with code I can examine and/or use). I apologize if I sound demanding or uneducated and confusing; I've been working diligently on this project for a couple weeks and it's now due tomorrow, and I've been stressing because I can't advance until I figure this out.
TL;DR - How do I get my main program to wait and listen for a button click event? Should I use modal dialog boxes, or is there some other way to do it? In either case, what code needs to be changed to do it?
Unlike console based programming, that typically has a well defined execution path, GUI apps operate within a event driven environment. Events come in from the outside and you react to them. There are many types of events that might occur, but typically, we're interested in those generate by the user, via mouse clicks and keyboard input.
This changes the way an GUI application works.
For example, you will need to get rid of your while loop, as this is a very dangerous thing to do in a GUI environment, as it will typically "freeze" the application, making it look like your application has hung (in essence it has).
Instead, you would provide a serious of listeners on your UI controls that respond to user input and update some kind of model, that may effect other controls on your UI.
So, to try and answer your question, you kind of don't (wait for user input), the application already is, but you capture that input via listeners and act upon them as required.
My game is going to have multiple screens and right now I have one class which is an InputProcessor and a GestureListener. Should I create seperate input classes for each screen and set the screen on show and hide methods or should I just check which screen is active with if branches within the Input class and make one InputProcessor class that handles all the input of every screen?
When you program games you think on the high level design as the engine, and you separate heavily the engine-logic from the game-logic. If you know MVC for example, then you know how this separating roles of code tends to go.
Have a component that takes input keyboard for instance, but doesn't give it "meaning", just take the data and store it somewhere, this includes analyzing gestures, record the gesture, identify it and store "gesture 'x' received", just liek you stored "key A pressed" or "key A released". That will be the input for the current pass of the game/ui logic.
You should probably have every screen be an object of the game engine, and have the game logic modify them all, but you can separate ui from game logic if you like. In that case, the input will travel to one of them depending on which one is active at the moment (which one has focus).
Each class should have their own way to decode the pre-processed input into specific commands. Because the ui should have common ui components you can have a single library for them all, and then you just inherit from them. If you aren't using common ui objects (butons, scroll panels, panels, text areas, etc), then every screen will have to have its own function for processing input. The ui component receives the input and sends it to the appropriate form object for further work. The game logic will decode and apply stuff on its game logic pass.
As such have different input processors and assign them to the correct screens, give them useful names like MainMenuInputProcessor.
Once you are done you call paint on everything.
I've been working on a console based program that acts as an inventory of Plant objects.
I have a parent class "Plant" that has child classes of "Flower", "Weed", etc... These objects are added, removed, displayed, searched through another class containing the main method and methods for the actions above.
The methods/actions are chosen by the user via console input processed with a switch statement.
My question is this: We are adding a GUI to this console based program using a JFrame, JPanels, etc... Would the proper way to go about this be to create a new class for the interface and a new main method in that class to run the program? I would of course change the former main method to a method called by the new main.
Moving from a console program requires a lot more than just changing main methods. GUI programs are event driven. So you're not going to be running endless loops like you would in a console program.
What I mean by event driven is, for example, a button get pressed, an event is fired. You as the programmer are responsible for coding what happens when that event is fired.
So some advice.
You should go through the tutorials and learn some of the basic components and how they work. Some of the basic ones are JLabel, JTextField, JButton
You will definitely need to focus on how to write event listeners. Some of the basic ones you may want to focus on are ActionListener for button presses MouseListener for mouse events.
Should learn to layout out components correctly. Some of the basic layouts you may want to focus on are GridLayout, BorderLayout, and FlowLayout
You want to learn about the basic containers like JFrame and JPanel and learn their capabilities
The Swing tutorials are always a good place to start. Once you pick up on the basics, then move on to some more complex material.
My question is more about general design and code flow, rather than a specific issue like syntax. How can I take an existing game (a fighting game, kind of like Pokemon) and add a GUI to it? I've done very simple GUIs before, so I understand the concepts of adding a frame, selecting a layout, and adding panels, buttons, images, etc. I'm not stuck on the details. Rather, I don't know where to implement the GUI.
Is it best to create a class or classes for the GUI, and then create instances of those classes within my existing code? Or do I go the other way around, and have the code within the GUI drive the game forward?
I also haven't used event driven programming before. How does this fit into the structure?
You might want to read up on the Model-View-Controller pattern.
Take your existing game and turn it into a library of objects that maintain the game state through the various actions the players can make. This will be your "Model".
Then create some graphical elements that will display the game state to the user. This will be your "View".
Finally, you will need some user interface elements that allow the user to update the game state (buttons and such). These will have callback or events in which you will put the code that calls the methods in your "Model" object to update the game state, and to update the "View" objects as necessary. That's the Controller.
I'm working on implementing an android version of the board game Cloud 9. I have never designed games, android apps (except 1-2 hello world apps) or even programs with GUI before (did a lot of CLI), and I have some questions regarding the design.
The game is turn-based, so there's no real-time considerations here, and I was wondering what was best to do. The game consists of pretty simple 2-3-options selections for each decision the player has to make, and for starters I want to make it "text-based", i.e., have a TextView with the game "log" on it and whenever the human player has to make a decision, he is given 2-3 buttons with the options he can play. The game consists of several rounds and levels.
I started out implementing the game "core" without a GUI altogether and with AI players. I then tried to figure out how to allow for human players, GUI, etc. My current design idea is a GameEventListener class which will be informed of different events in the game (round begins, round ends, a certain player did a certain action, etc.), and have the activity implement it and thus it can draw/write to the screen what happens, etc.
However, I'm not sure if this is the best approach, and how the Android part should be implemented (for example, I would like that after some events, the player will have a "continue" button, so he can see what was done before the game continues - how do I wait for the button to be pressed? If I return from the listener function, the game will continue). Any suggestion on how to proceed?
You can take a look at my Tetrads Drop game here for GUI and some of my approach
http://code.google.com/p/tetrads-drop-lite/
It is a tetris clone and can play with another player over the internet. If you need help with some GUI code, Ed Burnette's "Hello, Android" is a good book to start.
Updated
It is quite similar to what you are designing.
There are these package hierarchies
-com.aunndroid.Engine (handling game logic)
-com.aunndroid.View (managing 2D Views)
-com.aunndroid.Tolk (communication between deivces)
Since your game is turn-based, then I think design such as GameEventListener is OK.
Basically,this kind of GUI can be implemented by replying to the events. You can assign each UI component your listener.
For example, button.setOnClickListener(Your listener class);
For different buttons, you can create different listener classes for them respectively, and you can collect them in one GameEventListener as well. If the operation reacted to the events is not complicated, we can even use anonymous class:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//do your operations here(e.g. get input, update UI)
}});