Android, where to put my UI updates and my game loop - java

So I'm new to Android, and have been having some difficulties with understanding threading/Android UI updating and such. I have some code for a simple game engine I made for an AP computer science final project and I have been trying to make it into an Android app. Coming from the java world I'm not used to threading or worrying about how much time or where a calculation is taking place so I've been having some difficulties getting my game playable. After a splash screen and a main menu, I have it set up so an activity named "Play" starts. In this activity I have found that I can initialize my game engine object(which gets passed from class to class), create an object I created to make an AsyncTask("GuiThreader" in the code linked below) but as soon as I throw in some code in "Play" to do anything more than that (like initialize a button, or start the threader helper class) I get an "Activity has Stopped Unexpectedly" error meaning I'm doing something wrong. I've been looking at a lot of the Android example code but its making little sense to me. So I guess with all that background my bigger question is how can I get this code working? More specifically where should I have my loop that checks when the game is over, and how can I update my button colors outside of the "main" threader to keep it from crashing.
Here is my code:
"Play" Activity (with lines of code commented that I was testing with):
http://pastebin.com/K5kFsMvG
"GuiThreader" used to make the game calculations an AsyncTask: http://pastebin.com/306eUYfq
"GUIdriver" used to call a class that updates the button colors: http://pastebin.com/RANZBH38
"ButtonColorUpdate" saves a value for buttons and updates their colors: http://pastebin.com/qN2fw1RC
If you need anything else just comment and I'll put it up. Thanks in advance for any help!

Start by reading this. Then I'd recommend looking at the code from Replica Island. There's a ton you can learn from studying the code of this project. If you want to interact with GUI "stuff" from a separate thread, a Handler (see the API) can be useful for sending messages between the two.

Related

How do I get the program to wait for a click on another part of the GUI? [duplicate]

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.

Problems separating GUI from logic

I am currently learning java and wanted to give myself a project that was both challenging and fun. I decided to build a game that I remember playing when I was a kid called dopewars.
This is my second attempt at this game. When I began my first attempt, all went well. After a short while my source code began to fill wildly out of control until I could continue no more as I kept getting lost within mountains of code.
I then decided to begin again, only this time I wanted to seperate the gui from the logic (2 different .java files). This is where my problem lies. Previously this would work fine. Since seperating my java files the functionality has stopped.
When I press jbutton b1, my program is supposed to take the price value of cocaine and the units value entered into the jtextfield by the user, perform a calculation by accessing a method within Buy.java, and then update the appropriate JLabels within the s jpanel of GUI.java.
For example, user x wants to buy cocaine at the price indicated, so he enters a value representing the quantity he would like. He then presses the buy button which ultimately deducts the money from his pocket which is shown on the left side of the program window by using a method within the Buy class.
I hope you can understand my explanation and I hope to hear from you soon. Thanks.in advance. My Source code is below.
Maybe you should make a main.java (with GUI, etc.) and a logic.java (or whatever you want to call it) and make the main class Extend the logic class. to solve your jbutton problem, you should probably make the Main class extend the JFrame class, and implement the ActionListener interface, and then in the ActionPreformed method, call a method to do the logic from the logic class. I hope this helped.

Java: GUI to controller thread communication

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.

Android board game implementation design

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)
}});

is multiple activities and surface views the correct way to go?

I'm currently in the process of making one of my first android games and have come into some difficulty understanding how to make the transitions between screens.. for example:
My game starts its main activity, which then loads TitleScreen surface view which initializes its own thread
on tap I start a new intent which loads a new activity which loads GameView surface view which initializes its own thread
This all works fine when testing on my device (Evo 3d) but crashes on tap on my test bed, I'm using android x86 in virtual box for quick testing. Is this likely to be a problem in my code or a problem with the simulator?
Also I'm wanting to add a level select screen in between the title screen and the game screen and figured i could do this by creating another activity/surface view/thread combo, Is this acceptable coding practice or is this a wasteful/process heavy method?
You could create a variety of methods that you call from your onDraw method. Each method would draw one screen (game, level, score). To start simple a switch case in the onDraw checks the screen and then calls the right thing to draw.
If you want to have different layers, you should use different acitvities so that the background (game) is being paused while the scoreboard is active. This only makes sense if you want the background to be still visible or need the acitivites for other reasons.
But you should never have more than one surface view active at the same time, android doesnt like that.
I think its not good to use more activities for single application. Try to use ViewFlipper with number of xml layout files. Here you can apply transition effects very easily.
I am suggesting you it for transition effects, but you also check it once. I am also thinking which one is good.

Categories

Resources