Java - Subtract 32 from a number in a specific amount of time - java

I was wondering... Is there a way that I could subtract 32 from a number in a specific amount of time? Such as 500 mils?
If you could help out, it would be great!
Thanks!
public void update() {
x += dx;
if(this.y % 32 == 0) {
this.tileY = this.y / 32;
}
if(this.x % 32 == 0) {
this.tileX = this.x / 32;
}
System.out.println(tileX);
}
public void moveLeft () {
// subtract 32 dx in 500 ms
}

Well, here is a lovely code I've developed for you. I've added the keyword static to be able to call it from main without creating any objects, but it does not use anything from a static context.
As my comments through the code try to explain, this isn't the perfect solution, it's just a start, you may face issues such as multi-threading errors (if you decide to use a separate Thread to update the position) or slight timing issues if the body of the method takes a while to execute.
If you feel the nanosecond precision is a bit too much for your purposes, remember there is also Thread.sleep(int milis).
Here is the code (try changing the values calling moveLeft(int, int) to see the results):
public class Slider {
public static void main(String[] args) {
Thread thread = new Thread() {
#Override
public void run() {
/*
* If you are going to use something like this, beware you are multi-threading
* Make sure what you do is thread-safe
*/
moveLeft(32, 500);
}
};
thread.start();
}
public static void moveLeft(int distance, int milis) {
//time_px is how many nanoseconds the Thread can sleep until it has to move 1 dx
double time_px = (100000*milis)/distance;
if (time_px >= 1) {
//Get the milis and nanos, rounding for Thread.sleep
long time_round = (long) Math.floor(time_px);
long milis_sleep = time_round/100000;
System.out.print("Waiting " + milis_sleep + "ms ");
int nano_sleep = (int) (time_round%100000);
System.out.println(nano_sleep + "ns per dx");
for (int i=0; i<distance; i++) {
try {
Thread.sleep(milis_sleep, nano_sleep);
/*
* Your code here
* A long code here might not get you the desired result since the sleeping does
* not account for the time spent processing the code. But this is a good start
*/
System.out.println("moving 1 dx");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
else {
System.out.println("Cannot go that fast");
//If you are moving that fast (more than 1 dx per nanosecond) then you need to change this up a little.
}
}
}

Related

GameLoop, What To Put For Delta?

I was just wondering for a quick question, what do you put in for delta exactly. The parameter double delta is (as the developer stated, in seconds of logic updates). If I wanted the loop to run 20 times a second, would I have it set to .2 or something like that? I am a bit confused on the logic updates (in seconds) part.
Anyways if you want to check any more of the game loops provided then check out the page here http://entropyinteractive.com/2011/02/game-engine-design-the-game-loop/
public abstract class GameLoop
{
private boolean runFlag = false;
/**
* Begin the game loop
* #param delta time between logic updates (in seconds)
*/
public void run(double delta)
{
runFlag = true;
startup();
// convert the time to seconds
double nextTime = (double)System.nanoTime() / 1000000000.0;
while(runFlag)
{
// convert the time to seconds
double currTime = (double)System.nanoTime() / 1000000000.0;
if(currTime >= nextTime)
{
// assign the time for the next update
nextTime += delta;
update();
draw();
}
else
{
// calculate the time to sleep
int sleepTime = (int)(1000.0 * (nextTime - currTime));
// sanity check
if(sleepTime > 0)
{
// sleep until the next update
try
{
Thread.sleep(sleepTime);
}
catch(InterruptedException e)
{
// do nothing
}
}
}
}
shutdown();
}
public void stop()
{
runFlag = false;
}
public abstract void startup();
public abstract void shutdown();
public abstract void update();
public abstract void draw();
}
You input the time in milliseconds that a single logic-loop should be based on.
If you want 20 times per second then 1/20 second is the number which is not 0.2 but 0.05.
You can write it more intuitively (IMO) by writing "1.0 / 20" then you don't have to convert back and forth and can just replace 20 with the frequency.

problems converting CountDownTimer to my SimpleDateFormat output

I have a timer that counts down. I want the displayed format to be 00.00 or "ss.SS". However I haven't made any progress in hours. Without the SimpleDateFormat it displays 01.91 then goes to 01.9. This makes it hard to watch as it flickers to keep the view centered. All I really want is a way to keep the format 01.90 and not allow the 0 to be dropped. Could I accomplish this with my original code without the SimpleDateFormat?
/*
* This is my original code before I tried the SimpleDateFormat
*
* This code is fully functional and works good, it just keeps dropping the 0 every
* 10 milliseconds and makes the view shake
*
* getTimeSecs() could return 5, 10, 15, 30, 90 seconds converted to milliseconds
* getCountDownInterval() returns 10
*
*/
public void createTimer() {
myCounter = new CountDownTimer(getTimeSecs(), getCountDownInterval()) {
public void onTick(long millisUntilFinished) {
timerIsRunning = true;
if(millisUntilFinished < 10000) {
TVcountDown.setText("0" + ((millisUntilFinished / 10) / 100.0));
} else {
TVcountDown.setText("" + ((millisUntilFinished / 10) / 100.0));
}
} //end onTick()
#Override
public void onFinish() {
timerIsRunning = false;
TVcountDown.setBackgroundColor(myRes.getColor(R.color.solid_red));
TVcountDown.setTextColor(myRes.getColor(R.color.white));
TVcountDown.setText("Expired");
// Make sure vibrate feature is enabled
if(wantsVib == true) {
vib.vibrate(300);
}
} //end onFinish()
}.start();
} //end createTimer()
Here is my code after trying the SimpleDateFormat
public void createTimer() {
myCounter = new CountDownTimer(getTimeSecs(), getCountDownInterval()) {
public void onTick(long millisUntilFinished) {
timerIsRunning = true;
long current = (long) ((millisUntilFinished / 10) / 100.0);
TVcountDown.setText("" + timerDisplay.format(current));
}
#Override
public void onFinish() {
timerIsRunning = false;
TVcountDown.setBackgroundColor(myRes.getColor(R.color.solid_red));
TVcountDown.setTextColor(myRes.getColor(R.color.white));
TVcountDown.setText("Expired");
// Make sure vibrate feature is enabled
if(wantsVib == true) {
vib.vibrate(300);
}
}
}.start();
} //end createTimer()
I know! I don't even think I'm close to getting it with the SimpleDateFormat and I'm getting frustrated. It runs, but counts down only seconds, on the milliseconds side. So 15 seconds shows 00.15 not 15.00.
I don't expect someone to code it all out for me just need pointed in the right direction. All the tutorials I can find involve years, days, and such and I can't grasp the concept from that.
I'd prefer not to use the SimpleDateFormat -- cuz it hasn't been to simple for me -- and just use my original code and add a zero to the end of the milliseconds side every 10 milliseconds.
Thanks in advance.
Try this:
TVcountDown.setText(convertToMyFormat(millisUntilFinished));
and convertToMyFormat() method:
public String convertToMyFormat(long ms) {
String secString, msecString;
//constructing the sec format:
int sec = (int) (ms / 1000);
if(sec < 10) secString = "0"+sec;
else if(sec == 0) secString = "00";
else secString = ""+sec;
//constructing the msec format:
int msec = (int) ((ms-(sec*1000))/10.0);
if(msec < 10) msecString = "0"+msec;
else if(msec == 0) msecString = "00";
else msecString = ""+msec;
return secString+":"+msecString;
}
I'm not sure if I did the msec part correctly but you can tweek it as you want.
convert the number to a string and it will keep formatting. additionally you can do something like this
public String NumToStr(long i){
if (i < 10 ) {
return ("0" + Long.toString(i));
}
return Long.toString(i);
}
to make sure "9" will always come back as "09". Now set the string to the text.
actually what might be easier is this
if(millisUntilFinished < 10000) {
TVcountDown.setText("0" + Long.toString((millisUntilFinished / 10) / 100.0));
} else {
TVcountDown.setText("" + Long.toString((millisUntilFinished / 10) / 100.0));
}
Use Float.toString() or Double.toString, or whatever you need. Dont be afraid to write a little function to edit the string to make it appear as you want if you need to.
public String KeepFirstTwoCharOfString(String string){
//code to store first two Char into string
// return the string containing only first 2 chars
}

Issues with using too many Threads a benchmark program

I've programmed a (very simple) benchmark in Java. It simply increments a double value up to a specified value and takes the time.
When I use this singlethreaded or with a low amount of threads (up to 100) on my 6-core desktop, the benchmark returns reasonable and repeatable results.
But when I use for example 1200 threads, the average multicore duration is significantly lower than the singlecore duration (about 10 times or more). I've made sure that the total amount of incrementations is the same, no matter how much threads I use.
Why does the performance drop so much with more threads? Is there a trick to solve this problem?
I'm posting my source, but I don't think, that there is a problem.
Benchmark.java:
package sibbo.benchmark;
import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;
public class Benchmark implements TestFinishedListener {
private static final double TARGET = 1e10;
private static final int THREAD_MULTIPLICATOR = 2;
public static void main(String[] args) throws InterruptedException {
Benchmark b = new Benchmark(TARGET);
b.start();
}
private int coreCount;
private List<Worker> workers = new LinkedList<>();
private List<Worker> finishedWorkers = new LinkedList<>();
private double target;
public Benchmark(double target) {
this.target = target;
getSystemInfos();
printInfos();
}
private void getSystemInfos() {
coreCount = Runtime.getRuntime().availableProcessors();
}
private void printInfos() {
System.out.println("Usable cores: " + coreCount);
System.out.println("Multicore threads: " + coreCount * THREAD_MULTIPLICATOR);
System.out.println("Loops per core: " + new DecimalFormat("###,###,###,###,##0").format(TARGET));
System.out.println();
}
public synchronized void start() throws InterruptedException {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
System.out.print("Initializing singlecore benchmark... ");
Worker w = new Worker(this, 0);
workers.add(w);
Thread.sleep(1000);
System.out.println("finished");
System.out.print("Running singlecore benchmark... ");
w.runBenchmark(target);
wait();
System.out.println("finished");
printResult();
System.out.println();
// Multicore
System.out.print("Initializing multicore benchmark... ");
finishedWorkers.clear();
for (int i = 0; i < coreCount * THREAD_MULTIPLICATOR; i++) {
workers.add(new Worker(this, i));
}
Thread.sleep(1000);
System.out.println("finished");
System.out.print("Running multicore benchmark... ");
for (Worker worker : workers) {
worker.runBenchmark(target / THREAD_MULTIPLICATOR);
}
wait();
System.out.println("finished");
printResult();
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
}
private void printResult() {
DecimalFormat df = new DecimalFormat("###,###,###,##0.000");
long min = -1, av = 0, max = -1;
int threadCount = 0;
boolean once = true;
System.out.println("Result:");
for (Worker w : finishedWorkers) {
if (once) {
once = false;
min = w.getTime();
max = w.getTime();
}
if (w.getTime() > max) {
max = w.getTime();
}
if (w.getTime() < min) {
min = w.getTime();
}
threadCount++;
av += w.getTime();
if (finishedWorkers.size() <= 6) {
System.out.println("Worker " + w.getId() + ": " + df.format(w.getTime() / 1e9) + "s");
}
}
System.out.println("Min: " + df.format(min / 1e9) + "s, Max: " + df.format(max / 1e9) + "s, Av per Thread: "
+ df.format((double) av / threadCount / 1e9) + "s");
}
#Override
public synchronized void testFinished(Worker w) {
workers.remove(w);
finishedWorkers.add(w);
if (workers.isEmpty()) {
notify();
}
}
}
Worker.java:
package sibbo.benchmark;
public class Worker implements Runnable {
private double value = 0;
private long time;
private double target;
private TestFinishedListener l;
private final int id;
public Worker(TestFinishedListener l, int id) {
this.l = l;
this.id = id;
new Thread(this).start();
}
public int getId() {
return id;
}
public synchronized void runBenchmark(double target) {
this.target = target;
notify();
}
public long getTime() {
return time;
}
#Override
public void run() {
synWait();
value = 0;
long startTime = System.nanoTime();
while (value < target) {
value++;
}
long endTime = System.nanoTime();
time = endTime - startTime;
l.testFinished(this);
}
private synchronized void synWait() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
You need to understand that the OS (or Java thread scheduler, or both) is trying to balance between all of the threads in your application to give them all a chance to perform some work, and there is a non-zero cost to switch between threads. With 1200 threads, you have just reached (and probably far exceeded) the tipping point wherein the processor is spending more time context switching than doing actual work.
Here is a rough analogy:
You have one job to do in room A. You stand in room A for 8 hours a day, and do your job.
Then your boss comes by and tells you that you have to do a job in room B also. Now you need to periodically leave room A, walk down the hall to room B, and then walk back. That walking takes 1 minute per day. Now you spend 3 hours, 59.5 minutes working on each job, and one minute walking between rooms.
Now imagine that you have 1200 rooms to work in. You are going to spend more time walking between rooms than doing actual work. This is the situation that you have put your processor into. It is spending so much time switching between contexts that no real work gets done.
EDIT: Now, as per the comments below, maybe you spend a fixed amount of time in each room before moving on- your work will progress, but the number of context switches between rooms still affects the overall runtime of a single task.
Ok, I think I've found my problem, but until now, no solution.
When measuring the time every thread runs to do his part of the work, there are different possible minimums for different total amounts of threads. The maximum is the same everytime. In case that a thread is started first and then is paused very often and finishes last. For example this maximum value could be 10 seconds. Assuming that the total amount of operations that is done by every thread stays the same, no matter how much threads I use, the amount of operations that is done by a single thread has to be changed when using a different amount of threads. For example, using one thread, it has to do 1000 operations, but using ten threads, everyone of them has to do just 100 operations. Now, using ten threads, the minimum amount of time that one thread can use is much lower than using one thread. So calculating the average amount of time every thread needs to do his work is nonsense. The minimum using ten Threads would be 1 second. This happens if one thread does its work without interruption.
EDIT
The solution would be to simply measure the amount of time between the start of the first thread and the completion of the last.

Is it possible for a==a to evaluate false for some variable a in Java?

I've been posed this slightly obscure but interesting question about the behavoir of Java. Any ideas?
Yep, Try this...
public class Main
{
public static void main(String[] args)
{
double a = Double.NaN;
if( a == a ) System.out.println("equal");
}
}
http://www.ideone.com/K0d2j
Yes, for float or double NaNs (but not Float or Double). Section 4.2.3 of the JLS 3rd Ed. I believe IEEE 754 defines the operation that way. Those are the only cases.
As giddy said, concurrency can mess it up. I just tried this:
public class Madness {
private static volatile long a = 0;
public static void main(String[] args) {
long good = 0;
long bad = 0;
new Thread() {
{
setDaemon(true);
}
public void run() {
while (true)
a++;
}
}.start();
long print = System.currentTimeMillis() + 1000;
while (true) {
if (a == a)
good++;
else
bad++;
if (System.currentTimeMillis() > print) {
System.out.println(String.format("%d / %d", good, bad));
print = System.currentTimeMillis() + 1000;
}
}
}
}
Output was:
19936409 / 382
38360780 / 640
56895813 / 898
75827635 / 1159
94500958 / 1423
113184503 / 1701
131711068 / 1960
150423573 / 2239
168898106 / 2509
Admittedly, this is a case specifically designed to cause this. Removing the volatile on a changes things. I see some initial "bad" hits, but then it seems to be all good. I haven't investigated, but I have a feeling it's something to do with hot spot optimizing the code after some number of iterations.
The code for Double.isNaN()
static public boolean isNaN(double v) {
return (v != v);
}
This sounds like an interview questions. A similar questions when is x == x + 0 false which has more answers. ;)

Smooth movement in Java

I'm making a simulation in a 3D environment. So far, I have the movements of all the creatures, but it is not "smooth". I've tried quite a few things but was horribly wrong. Now I just have no idea what to do. I was thinking of implementing a vector (not vector class) but don't really know how.
import env3d.EnvObject;
import java.util.ArrayList;
abstract public class Creature extends EnvObject
{
/**
* Constructor for objects of class Creature
*/
public Creature(double x, double y, double z)
{
setX(x);
setY(y);
setZ(z);
setScale(1);
}
public void move(ArrayList<Creature> creatures, ArrayList<Creature> dead_creatures)
{
double rand = Math.random();
if (rand < 0.25) {
setX(getX()+getScale());
setRotateY(90);
} else if (rand < 0.5) {
setX(getX()-getScale());
setRotateY(270);
} else if (rand < 0.75) {
setZ(getZ()+getScale());
setRotateY(0);
} else if (rand < 1) {
setZ(getZ()-getScale());
setRotateY(180);
}
if (getX() < getScale()) setX(getScale());
if (getX() > 50-getScale()) setX(50 - getScale());
if (getZ() < getScale()) setZ(getScale());
if (getZ() > 50-getScale()) setZ(50 - getScale());
// collision detection
if (this instanceof Fox) {
for (Creature c : creatures) {
if (c.distance(this) < c.getScale()+this.getScale() && c instanceof Tux) {
dead_creatures.add(c);
}
}
}
}
}
import env3d.Env;
import java.util.ArrayList;
/**
* A predator and prey simulation. Fox is the predator and Tux is the prey.
*/
public class Game
{
private Env env;
private boolean finished;
private ArrayList<Creature> creatures;
/**
* Constructor for the Game class. It sets up the foxes and tuxes.
*/
public Game()
{
// we use a separate ArrayList to keep track of each animal.
// our room is 50 x 50.
creatures = new ArrayList<Creature>();
for (int i = 0; i < 55; i++) {
if (i < 5) {
creatures.add(new Fox((int)(Math.random()*48)+1, 1, (int)(Math.random()*48)+1));
} else {
creatures.add(new Tux((int)(Math.random()*48)+1, 1, (int)(Math.random()*48)+1));
}
}
}
/**
* Play the game
*/
public void play()
{
finished = false;
// Create the new environment. Must be done in the same
// method as the game loop
env = new Env();
// Make the room 50 x 50.
env.setRoom(new Room());
// Add all the animals into to the environment for display
for (Creature c : creatures) {
env.addObject(c);
}
// Sets up the camera
env.setCameraXYZ(25, 50, 55);
env.setCameraPitch(-63);
// Turn off the default controls
env.setDefaultControl(false);
// A list to keep track of dead tuxes.
ArrayList<Creature> dead_creatures = new ArrayList<Creature>();
// The main game loop
while (!finished) {
if (env.getKey() == 1) {
finished = true;
}
// Move each fox and tux.
for (Creature c : creatures) {
c.move(creatures, dead_creatures);
}
// Clean up of the dead tuxes.
for (Creature c : dead_creatures) {
env.removeObject(c);
creatures.remove(c);
}
// we clear the ArrayList for the next loop. We could create a new one
// every loop but that would be very inefficient.
dead_creatures.clear();
// Update display
env.advanceOneFrame();
}
// Just a little clean up
env.exit();
}
/**
* Main method to launch the program.
*/
public static void main(String args[]) {
(new Game()).play();
}
}
You haven't shown enough of your program. Basically, if you want animation to be smooth, and you want to do it yourself (as opposed to using JavaFX or something), then you need to do lots of inter-frames. So rather than advancing an entire timer tick, advance a 10th of a timer tick, move everything on a screen a tiny bit, and then advance again. You should have the background redraw happening every 10th of a second for smooth animation.
As vy32 mentioned, we need to see more of your code. But it looks like you are missing timing code.
What you probably want to do is check the time each iteration of your game loop and then sleep for a certain amount of time to achieve some desired frame rate. Otherwise your game loop will run hundreds of thousands of times a second.
Alternatively, you should be advancing your creatures by a distance that is proportional to the amount of time that has elapsed since the previous frame.
Here is an example of a very simple regulated loop ("fps" is the desired framerate):
private long frameLength = 1000000000 / fps;
public void run() {
long ns = System.nanoTime();
while (!finished) {
//Do one frame of work
step();
//Wait until the time for this frame has elapsed
try {
ns += frameLength;
Thread.sleep(Math.max(0, (ns - System.nanoTime())/10000000));
} catch (InterruptedException e) {
break;
}
}
}
It should be very easy to retrofit this into your game loop.

Categories

Resources