Java Lejos autonomous NXJ-robot threads causing trouble - java

I'm writing an java code to control a fairly simple robot, which should execute the following actions; PID-linefollower, ultrasonic detection and color detection.
As this is my first program in java, I obviously have lots to learn in regards to OOP.
The robot runs on a track where the line is accompanied by colors on the road, which the robot should periodically check for and if found, act differently based on which color it reads.
So the process should run somewhat alike this following pseudo(java)-code:
Initialize and calibrate sensors.
while (! Button.ENTER.isDown)
Run PID-controller
If (ColorSensorColor = 0 || ColorSensorColor = 2)
if (color = 0)
turn left
if (color = 2)
turn right
while (UltraSonicDistance < 30cm)
free-roll motors
My question therefore is; how do I construct two threads that can run the ColorSensor and UltraSonicSensor in parallel with a main thread?
The latest actual code is situated here
Lastly, thanks for all your input - I've scoured the interwebz for good tutorials, but it seems that I have too few braincells to comprehend the mother of all OOP.

/u/evil_burrito on /r/javahelp kindle answered with the following, working suggestion:
First, you might want to consider a real time JVM, if you're not already. If your controller has to run uninterrupted, that might be something to consider. FWIW, RT is not my area of expertise at all.
However, your basic question about threads is easier to answer.
Create an inner class for each of the ultrasonic sensor and the color sensor. Have those classes implement Runnable. In the run method, check the appropriate sensor and update a volatile variable in the outer class.
Use a ScheduledExecutorService to execute a sensor check for each of these classes (create an instance of the inner class and submit it to the executor to be run at intervals of 1ms or 100 microseconds, or whatever).
The main class can just monitor the values of the volatile variables and decide what to do w/o interruption.

Related

Multiprocessing in Java with Killable thread

I have a scenario in which I am running unreliable code in java (the scenario is not unlike this). I am providing the framework classes, and the intent is for the third party to overwrite a base class method called doWork(). However, if the client doWork() enters a funked state (such as an infinite loop), I need to be able to terminate the worker.
Most of the solutions (I've found this example and this example) revolve around a loop check for a volatile boolean:
while (keepRunning) {
//some code
}
or checking the interrupted status:
while (isInterrupted()) {
//some code
}
However, neither of these solutions deal with the the following in the '//some code' section:
for (int i = 0; i < 10; i++) {
i = i - 1;
}
I understand the reasons thread.stop() was depreciated, and obviously, running faulty code isn't desirable, though my situation forces me to run code I can't verify myself. But I find it hard to believe Java doesn't have some mechanism for handling threads which get into an unacceptable state. So, I have two questions:
Is it possible to launch a Thread or Runnable in Java which can be reliably killed? Or does Java require cooperative multithreading to the point where a thread can effectively hose the system?
If not, what steps can be taken to pass live objects such that the code can be run in a Process instead (such as passing active network connections) where I can actually kill it.?
If you really don't want to (or probably cannot due to requirement of passing network connections) spawn new processes, you can try to instrument code of this 'plugin' when you load it's class. I mean change it's bytecode so it will include static calls to some utility method (eg ClientMentalHealthChecker.isInterrupted()). It's actually not that hard to do. Here you can find some tools that might help: https://java-source.net/open-source/bytecode-libraries. It won't be bullet proof because there are other ways of blocking execution. Also keep in mind that clients code can catch InterruptedExceptions.

Is it good to separate game thread and display thread?

It is the first time I want to write a java game, and I chose to do a Snake Line.
I learnt from a piece of source code from online. It updates the game states and displays in one thread. I changed around that code, and when I changed the FPS (from 60 to 30), animation slows down. More to this, the game behavior changes too. It is duck shooting game, and the space between ducks get narrower.
So I decided to separate the game thread and the display thread to avoid the above problem. But then I realize it brings out the concurrency problem which will be all over the place.
So as the title indicates, is it good to separate game thread and display thread? What is the common practice and why?
From the changes you experience, it sounds like you are using frame as a unit of time measurement. Or, more precisely, you use pixel/frame(or something like that) for velocity and second for time.
This might be OK for a simple game like yours, ones that are light enough on the system resources so that the delay between frames you specify in the code is practically the same as the real delay, meaning you are in complete control over the FPS. When the game get heavier and modern systems can no longer guarantee that property, you have a problem.
The solution is usually not to separate the game and display loops to separate threads, but to not use frames as unit of measurement for game mechanics calculations. Instead, each frame measure the time from the previous frame and use that value for the calculations, eg. multiply it by the speed to know how much to move a game object in this frame.
Not that separating those loops is such a bad idea. You don't get concurrency problems "all over the place", since the interaction between the game logic and the display shouldn't be "all over the place". The interaction should be one-way: the game loop writes data and the display loop reads it. That means you shouldn't have race conditions, but you can still get other multithreading hazards, which you can solve with volatile variables.

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.

Python - Threading, Timing, or function use?

I am having an issue formulating an idea on how to work this problem. Please help.
My project consists of an N x N grid with a series of blocks that are supposed to move in a random direction and random velocity within this grid (every .1 seconds, the location of the block is updated with the velocity). I have three "special" blocks that are expected to have individual movement functions. I will have other blocks (many of them) doing nothing but updating their location, and making sure they remain in the grid.
Now these three blocks have functions beyond movement, but each of these runs individually, waiting for the other block's special function to finish (block 2 will wait on block 1, Block 3 will wait on 2 and set it back to block 1, etc.) This queue of sorts will be running while the motion is happening. I want the motion to never stop. After each block's non-movement function runs n times, the code finishes.
My question is this: should I use threads to start and stop the non-movement functions, or is there a way to just set a time and set booleans that could use a class function after .1 seconds to continuously move the objects (and obviously loop over and over), and then use counts to end the program all together? If so, how would you write main function for this in Python? For all of this happening, does anyone think that Java would be significantly faster than Python in running this, especially if writing the data to a .txt file?
Your best bet is probably to handle all of them at once in a single update function rather than attempting to use Threads. This is primarily because the Global Interpreter Lock will prevent multiple threads from processing concurrently anyway. What you're after then is something like this:
def tick():
for box in randomBoxes:
box.relocate()
specialBlock1.relocate()
specialBlock2.relocate()
specialBlock3.relocate()
Then we define a second function that will run our first function indefinitely:
def worker():
while True:
tick()
sleep(0.1)
Now that we have an interval or sorts, we'll launch a Thread that runs in the background and handles our display updates.
from threading import Thread
t = Thread(target = worker, name = "Grid Worker")
t.daemon = True # Useful when this thread is not the main thread.
t.start()
In our tick() function we've worked in the requirements that specialBlocks 1, 2, and 3 are working in a set order. The other boxes each take their actions regardless of what the others do.
If you put the calls to the special functions together in a single function, you get coordination (2) for free.
def run(n, blocks):
for i in range(n):
for b in blocks:
b.special()
As for the speed of Python versus Java, it depends on many things, such as the exact implementation. There is too little information to say.

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