While loops and...threads? - java

Ive created a network game. I am having issues with (seemingly) unexplainable errors. Note that the cards are added by to the ArrayList upon mouse clicks, and this class is run on its own thread.
private void waitForAction(){
tb.report("Waiting for user to make a move...");
selectedCards = new ArrayList<Card>();
while(selectedCards.size() < 2){
if(selectedCards.size() == 2)//Wtf is going on here...?
tb.report("This loop is (not) broken.");
else
tb.report("Looping..");
};
tb.report("This player has selected 2 cards.");
}
When I remove the else statement, the loop never exits, which is proven to me by the print(report()) methods. I had the same issue in earlier development, but it was corrected by adding the if part of the if-else statement. I am honestly baffled, logical reasoning tells me that JVM is not checking the condition because the thread is not running, however throughout the program I only ever call Thread's start() once, otherwise its untouched by my code. Any wiser sole's opinion would be much appreciated.

Without more information it's hard to tell you exactly what is going wrong. However, I would strongly advise that you write your server in more of an event-based model. Especially given that it's a card game, so I'm guessing it's turn based and not real-time.
Instead of doing your loop based approach, try this:
The server keeps a model of the current state of the game.
The client sends a message to the server. One such message could be "play card XYZ"
The server processes the message and updates the model accordingly. If a user played a card, it might remove that card from the person's hand. It might change some other state based on the effect of the card. All the logic is handled when the message is received.
State changes are sent out to all the clients so that they are seeing a view consistent to the state of the server.

You have multithreading environment. ArrayList is not a threadSafe collection -- it does not guarantee visibility on other threads. This means your waiting thread never sees changes in the collection.
Try to use some collection of java.util.concurrency.

Related

Can I do Swing operations at shutdown time?

This relates to this Java question.
Here's my problem. I've written an app that allows people to do a lot of data entry, typing into a lot of separate fields. To confirm the change in each field they can often hit Return (for a single line field) or control-S (for multi-line fields where Return would be valid input), but that's cumbersome, so I also allowed fields to save their content when they lose focus. So users can type-tab-type and it all goes smoothly.
Except if they change a field and then click on the application window exit X in the corner. They expect that this counts as losing focus and will save that last change. But the lost focus event doesn't happen and the change is lost.
I could add a Done button, which would have the side effect of moving focus and saving the last field, and then exiting. But I shouldn't have to. There's a X in the corner and it should do the right thing.
My first thought was
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(.....
because I thought from there I could publish() something to my SwingWorker to tell it call loseFocus on everything. No such luck; publish() is protected.
Basically I need to do one last operation on my various widgets when X is clicked. How do I?
Edit: I should note that each editable widget (dropdown, JTextPane, etc) has been extended to hold the actual relevant data. All the data for that widget, e.g. whether the value the user typed is valid, what it was before he edited it, etc. is in those extended class instances. There's no other place values are held; this isn't model-view-controller.
The reason for this is that widgets can get changed either by user actions or network messages; a message can come in that throws out an existing widget entirely and replaces it with one with new content. In other words, doInBackground is in a permanent read-loop, reading network update messages and publish()ing those update requests to process(). User action happens as usual, between calls to process().
Bottom line,there's no global data structure to go to at exit time to get values. They're all in dozens to hundreds of data structures managed by the swing worker thread.The app itself, outside that swing worker thread, doesn't even know what sort of values and widgets exist - all widgets are created, placed and destroyed by network messages from the server. The rest of the app (what little there is) couldn't safely get to the data if it wanted to, unless I implemented a whole lot of shared data and locking.
It all works flawlessly, and I'd rather not redesign it all for this one tiny shutdown case. It just never occurred to me that I couldn't publish an extra "shut down" message into the work queue for process() from outside that thread. (I mean thread safe queues are trivial to implement; why didn't they?)
If the answer is "you can't talk to swing at shut down", I'll live with it. I do have a potentially evil workaround - I could have x do nothing but send a message to the server, which could write back a "you should shut down message" which could do the rest. But that seems ungainly.
The short answer is, there isn't a good solution. I tried installing a shutdown hook and publishing a message to the swing thread to tell it to finish up, and then gave the shutdown thread a 500ms sleep to give process() time to happen. process() wasn't called. publish() alone apparently isn't enough, once shutdown starts.
Bottom line, don't put data you need to get at in swing threads. Global data and synchronized functions is the only way to go.

How to make a thread that is getting a simultaneous requests by other threads and it needs to flush them out one by one

So, I am using a midi controller to move the mouse for controlling a program purposes.
My problem right now is that I hit the mouse with multiple instances of robot class (maybe a very bad idea) for example if I move 2 faders together in my current code I'm generating 254 instances of robot and the mouse is getting half way at both on - screen faders.
My question is: is there a way to keep a list of the requests and flush them out one by one. Also the list/queue must be able to fill it's back side while flushing
EDIT: the list/queue must also flush the requests as soon as it receives one
If you can just point me to the right direction that would be great!
Thanks 😊
You can use one of the queues from java.util.concurrent package, ArrayBlockingQueue for example.
Also to mention. You say: "the list/queue must also flush the requests as soon as it receives one". A list or a queue itself does not flush anything. It's up to threads to decide when they are ready to get another request from a queue.

How to connect UI and functionality?

I am only a beginner in Java and until now I just put the functionality into the addActionListener() method of the buttons, it was enough for little games and stuff.
But now I am trying to make it seriously and I am wondering how to connect those 2.
As an example I am making a Fuchimi game, so I have my classes for the actual game and then a class that builds the frame with everything needed.
But my actual problem right now is, that after the frame is created, it doesn't do the following code since the code pauses at the window, like here:
FuchimiUI ui = new FuchimiUI();
//The following is not executed
Hand playerHand = null;
while (playerHand == null) {
playerHand = ui.getPlayerHand();
}
Hand enemyHand = generateHand();
ui.changeEnemyText("Enemy picked " + enemyHand.toString());
if (enemyHand.beats(playerHand)) {
ui.changeGenText("Computer wins!");
} else
ui.changeGenText("You win!");
The buttons I have just change the hand of the player.
So how can I do that properly, having the game code being compiled while the frame is already open?
I thought about threads, but I have too little knowledge about them, thus I don't know if that would be a good way.
Edit:
The ui.getPlayerHand() method returns the chosen hand(rock, paper or scissors) that the player has chosen through the buttons.
Of course I could have written the whole code in each of the button's addActionListener()methods, but I doubt that's the proper way of doing that.
So in general, all I wanted to do is let the player choose his hand and then let the game generate a random hand, then compare those two and change the text of one of the labels, depending on wether the player won or not.
The problem you are having results from the fact that your while loop is blocking the UI thread. You need to offload it to a different thread and then enqueue the UI updates back on the UI thread. The same situation is encountered here, please have a look.
There are several ways to fix this. One of them is the SwingWorker.
The steps are:
Override doInBackground for your while loop.
In it, call publish to store intermediate results (like the messages you want to display).
Override process to display the intermediate results in your UI.
The third page of above mentioned tutorial covers this.
As much as I agree with Domi's answer, that long-running code should go into a background thread, I strongly suspect that this is not what you need in this situation, that instead you should re-think the structure of your program. Likely what you need instead of that while loop is a modal dialog.
For more and better advice, consider telling us more details of the game logic and your program set up. For instance, tell us exactly what ui.getPlayerHand() does, as a start.
What you want to do is to change the structure of your program so that it is event-driven and state based where its behavior changes depending on its state. For instance if your program is in "choose hand" mode, then those buttons or other user interfaces are all that respond to the user.

Modal-style programming within a Java server

For my game, I have it running on two servers (one for the game, one for the login system). They both need to interact with each other, and sometimes, ask questions about the state of something else in the other server.
For this example, the game server will be asking the login server if a player is trying to log in:
public boolean isLoggingIn(int accountId) {
//Form a packet to send.
int retVal = sendData();
return retVal > 0;
}
Obviously I'd use an int so information other than booleans can be returned.
My question is, how do I get this modal-style programming working? It'd work just like JFileChooser's getOpenDialog() function.
Also, I should mention that more than one thread can call this method at once.
I assume by modal, you mean trying to block all actions except one. I strongly suspect that this style will lead you into trouble. Modal interaction is a form of locking and therefore not very tolerant to hangups and disconnects and such. To make it tolerant, you need timeouts and cleanup code for cases when someone entered a mode and then nothing further happened. (i.e they closed their laptop, or the game crashed, they unplugged the network cable etc).
If I were you I would instead try to think of things in terms of authentication and authorization.
The quick answer - you need to expose methods on both servers as RMI-capable, and simply invoke methods like you described.
You might find it useful to review the official Oracle RMI tutorial: http://docs.oracle.com/javase/tutorial/rmi/index.html
Althought your design might be wrong - it's your design, and why not letting you shoot your head? ;)
Also, it's worth looking at Spring Security: http://static.springsource.org/spring-security/site/
If you use something like this on a thread that is supposed to handle other requests after it, it would hang up all those requests while it is blocking for a return value if the latency between the game and login servers is high. Certainly what you want instead is a callback so that your thread could handle other requests while it waits for a response.
I see no reason to halt execution of a thread until a value is received. If you need the value for an operation after it, then just copy all the code you have after the call you want to be "modal" in the callback. If you expect to send multiple requests while still waiting for a response, then send a unique "responseId" from the requester's side that the responder can include in its response. Use the "responseId" as a key for a Map with Runnables as values. When you receive a response, call remove on the Map with the responseId key and call run() on the Runnable value that is returned. MINA is supposed to asynchronous and should not block for a response packet.
If you have a really good reason for why you want to handle it all on the same thread, you can look into the java.util.concurrent package. I would implement it using a CountDownLatch of count 1, call await() after sending a request message, and call countDown() when you receive a response by MINA. You have to use an AtomicReference or an array of length 1 to hold the value you received in the response that you can read back into the waiting thread.
PS, you still doing MapleStory work?

Gameloop for j2me "turn-based" game

Edit: This makes alot more sense to me now that i've taken a step away from the code, thanks for the help.
Just found stack overflow the other day through Coding Horror and it looks awesome. Figure that i'd ask the community about a problem i'm currently trying to work out.
I'm developing a roguelike sortof game using j2me for midp 2.0 phones. The project is still in the basic stages of development as I figure out how it's going to work. The part i'm currently stuck on has to do with threading.
The game has a custom HaxCanvas class which extends GameCanvas and Implements runnable. It's run method calls repaint() and then sleeps for 50 ms, resulting in a frame rate of 20 FPS. This allows me to write the rest of the game without having to put repaint everywhere and should make animations and effects easier to do later on. (at least in theory).
The flow of the game is controlled by a GameManager class, which loops through all the NPC's on the map, taking their turns, until it's the player's turn. At this point I need to get input to allow the player to move around and/or attack things. I originally was calling gameManager.runUntilHeroTurn() in the keyPressed method of my HaxCanvas. However after reading up on j2me system threads I realized that putting a method with the potential to run for a while in a callback is a bad idea. However I must used keyPressed to do input handeling, since i need access to the number keys, and getKeyStates() does not support this.
Sofar my attempts to put my gameloop in it's own thread have resulted in disaster. A strange "uncaught ArrayIndexOutOfBoundsException" with no stack trace shows up after the game has run for several turns .
So i suppose my question is this:
For a "turn based" game in j2me, what's the best way to implement the game loop, allowing for input handeling only when it's the player's turn?
Although not j2me specifically you should capture user input, the general strategy is to queue the input it until its time to process the input.
input ---> queue <---> Manager(loop)
This way you can even script input for debug purposes.
So you don't need a new thread. Each time the user presses key you store them in a buffer, and then process the contents of the buffer when necessary. If the player buffer has no input, the manager should skip all gameplay, do animations and then start over (since the game is not an action game).
I would avoid threading for the game logic as J2ME threading, depending on manufacturer of course, does not do a great job of sharing the limited resources. You will often see pauses while a thread does heavy processing. I would only recommend threads for loading or network connectivity features as in this case you will just be giving the user basic "Loading..." feedback.
To handle this, I would not have sub-loops to update each of the AI in one frame. I would do something like following in the run function:
public void run() {
while(true) {
// Update the Game
if(gameManager.isUsersTurn()) {
// Collect User Input
// Process User Input
// Update User's State
}
else {
// Update the active NPC based on their current state
gameManager.updateCurrentNPC();
}
// Do your drawing
}
}
You want to avoid having everything updated in one frame as 1) the updating might be slow, resulting in no immediate visual feedback for the user 2) you can't animate each individual NPC as they make their action. With this setup you could have NPC states, NPC_DECIDE_MOVE and NPC_ANIMATING, that would allow you further control of what the NPC is doing. NPC_ANIMATING would basically put the game in a waiting state for the animation to take place, avoiding any further processing until the animation is complete. Then it could move on to the next NPC's turn.
Also, I would just have a gameManager.update() and gameManager.paint(g) (paint would be called from paint) that would handle everything and keep the run method thin.
Finally, did you look into flushGraphics()? With the GameCanvas you usually create a Graphics object, draw everything to that and then call flushGraphics(), then wait. The method you mention is the way of tackling it for the Canvas class. Just thought I would mention this and post a link:
Game Canvas Basics

Categories

Resources