libgdx textanimation(one letter by one) - java

I'm trying to make visual novel game but i'm stuck with text animation
I tried to make it on console application for example so help me with making it on libgdx.
here's my sample code
public class TestC {
private static String message = "help me with textanimation";
public static void main(String[] args) {
for (int i = 0; i < message.length(); i++) {
System.out.print(message.charAt(i));
try {
Thread.sleep(50);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Thanks in advance

Why don't you try to make it work with LibGDX and then ask help? It goes basicaly the same except instead of letting the program sleep you have to count time passed.
final float letterSpawnTime = .2f;
float timer = 0;
String completeText = "The complete text."
String drawText = "";
int stringIndex = 0;
public void update(float delta) {
timer += delta;
if (timer >= letterSpawnTime) {
drawText = drawText + completeText.charAt(stringIndex);
stringIndex++;
timer -= letterSpawnTime;
}
font.draw(someFont, drawText, x, y, etc...);
}
Something like that (written out of my head). To be a bit more efficient initialize the StringBuilder in the constructor once and just keep appending a single character to it instead of creating a new StringBuilder instance each time the you need to append a letter.

Related

How to change dxf layer color in java using jdxf library?

I have a java code generating dxf files, I am using jdxf library. Almost everything works fine with it, there is only one thing I could not figure out. When I'm adding a new Layer, I wish to do it with a new color so that all entities I draw under this new layer shall have a "ByLayer" color, which would be this new color I specify.
I can only achieve that the entities shall have the color I specify, but their layer's default color would still be black/white. Here is my DXFHandler object:
public class DXFHandler {
//https://jsevy.com/wordpress/index.php/java-and-android/jdxf-java-dxf-library/
DXFGraphics graphics;
DXFDocument dXFDocument;
int mirrorY, mirrorX;
public DXFHandler() {
dXFDocument = new DXFDocument();
dXFDocument.setUnits(4);//set units to mm
dXFDocument.setPrecisionDigits(1);//set precision digits
dXFDocument.setViewportCenter(0, 0);
graphics = dXFDocument.getGraphics();
mirrorX=1;
mirrorY=-1;
}
public void addLayer(String layerName, Color c) {
dXFDocument.setLayer(layerName);
graphics.setColor(c);//This will only achieve that the drawing entities get this color, but the layer's color would not be touched.
}
public void drawLine(double[]x, double[]y){
if (x!=null&&y!=null&x.length==y.length) {
for (int i = 1; i < x.length; i++) {
graphics.drawLine(mirrorX*x[i-1], mirrorY*y[i-1],mirrorX*x[i],mirrorY*y[i]);
}
}
}
public void drawPoint(double[]x, double[]y){
if (x!=null&&y!=null&x.length==y.length) {
for (int i = 0; i < x.length; i++) {
graphics.drawPoint(mirrorX*x[i], mirrorY*y[i]);
}
}
}
public void drawRect(double x1, double y1, double x2, double y2){
graphics.drawRect(mirrorX*x1, mirrorY*y1, mirrorX*x2, mirrorY*y2);
}
public void saveToDXF(String outputPath) throws IOException {
String stringOutput = dXFDocument.toDXFString();
FileWriter fileWriter = new FileWriter(outputPath);
fileWriter.write(stringOutput);
fileWriter.flush();
fileWriter.close();
}
And here is an example code to test it:
public static void main(String[] args) {
String outputFile="d:\\test.dxf";
int points=500;//Number of drawn points .
String layer1Name="Layer_1";
double[]xCoordinatesOfPoints1=new double[points];//creating first test-pointset_Xcoordinates
double[]yCoordinatesOfPoints1=new double[points];//creating first test-pointset_Ycoordinates
for (int i = 0; i < xCoordinatesOfPoints1.length; i++) {
xCoordinatesOfPoints1[i]=i;
yCoordinatesOfPoints1[i]=i;
}
String layer2Name="Layer_2";
double[]xCoordinatesOfPoints2=new double[points];//creating second test-pointset_Xcoordinates
double[]yCoordinatesOfPoints2=new double[points];//creating second test-pointset_Ycoordinates
for (int i = 0; i < xCoordinatesOfPoints1.length; i++) {
xCoordinatesOfPoints2[i]=-1*i;
yCoordinatesOfPoints2[i]=i;
}
DXFHandler dXFHandler=new DXFHandler(); //Creating dxf handler object
dXFHandler.addLayer(layer1Name, Color.red);//Creating layer1
dXFHandler.drawPoint(xCoordinatesOfPoints1, yCoordinatesOfPoints1);//drawing points of layer1
dXFHandler.addLayer(layer2Name, Color.GREEN);//Creating layer2
dXFHandler.drawPoint(xCoordinatesOfPoints2, yCoordinatesOfPoints2);//drawing points of layer2
try {
dXFHandler.saveToDXF(outputFile);//Exporting dxf file
} catch (IOException ex) {
System.out.println("FAILED");
}
}
As a result I get a "test.dxf" file which has a green and red point-set. That would be fine but both layers' default color is white. I would prefer if the points' color was "ByLayer" and the layer color was green/red, as it is in my "wantedSolution.dxf", which I failed to see how to attach. I will attach it as soon as I figure out how to do that...

Java - I need to print this string of characters to a string I can use out of loop

I have been buried in this assignment for 2 days chasing down rabbit holes for possible solutions. I am beginner Java, so I am sure this shouldn't be as difficult as I am making it.
I trying to program the infamous Java Bean Machine... My professor want the Class Path to return a String Variable that only holds "R" "L" . to represent the path of the dropped ball.
Each ball should have its own Path... I can get the path... but I can not get the path to print in a string outside of the for/if statement.
Here are his instructions... in case you can see if I am interpreting this incorrectly.
Please help!! Thank you in advance for sifting through this....
my code so far ******** i have updated the code to reflect the suggestions.. Thank you... ***************** New problem is it repeats the series of letters in a line... I only need a string of 6 char ....(LRLLRL)
public class Path {
StringBuilder myPath;
public Path() {
myPath = new StringBuilder();
}
void moveRight() {
myPath.append("R");
}
void moveLeft() {
myPath.append("L");
}
public void fallLevels(int levels) {
levels = 6;
for (int i = 0; i < (levels); i++) {
if (Math.random() < 0.5) {
this.moveRight();
} else {
this.moveLeft();
}
}
}
public String getPath() {
System.out.print(myPath.toString());
return myPath.toString();
}
}
}
******Thank you all.. this class now returns the correct string for one ball...***************
here is my code so far for multiple balls... I can get a long continuous string of 6 character sequences... I need each sequence to be a searchable string...I am not sure if I need to alter the Path class or if its something in the simulateGame() method. I think I can take it after this hump... Thank you again....
public class BeanMachine {
int numberOfLevels;
int[] ballsInBins;
Path thePath = new Path();
public BeanMachine(int numberOfLevels) {
this.numberOfLevels = 6;
ballsInBins = new int[this.numberOfLevels + 1];
// this.numberOfLevels +
}
public void simulateGame(int number) {
//looping through each ball
for (int i = 0; i < numberOfLevels -1; i++) {
thePath.fallLevels(0);
}
thePath.getPath().toString();
}
*** this isn't the entire code for this class... I have to get this method correct to continue....
Problem with your code:
if (Math.random() < 0.5) {
**loop = this.myPath = "R";**
} else {
**loop = this.myPath ="L";**
}
Change this to:
if (Math.random() < 0.5) {
**loop = this.myPath + "R";**
} else {
**loop = this.myPath + "L";**
}
Just added ** to highlight where there is wrong in your code

Instance Variable Changing

I would like to make movement of a square with only using Instance Variable. I'm having troubles this is my code :
I have one for Variables.JAVA for Variables :
public class Variables {
String name;
int Playerx;
int Playery;
int Playerw;
int Playerh;
}
and one where it is the main but doesn't change the variables above. (simplified)
public static void main(String args[]) throws InterruptedException {
while (true) {
Variables P = new Variables(){
synchronized (c) {
c.clear();
first_level();
P.Playerx = 50;
P.Playery = 50;
P.Playerw = 100;
P.Playerh = 100;
c.drawRect(P.Playerx, P.Playery, P.Playerw, P.Playerh);
}
Thread.sleep(25);
// Controls
if (c.isKeyDown(Console.VK_UP)) {
P.Playery -= 10;
}
else if (c.isKeyDown(Console.VK_DOWN)) {
P.Playery += 10;
}
else if (c.isKeyDown(Console.VK_LEFT)) {
P.Playerx -= 10;
}
else if (c.isKeyDown(Console.VK_DOWN)) {
P.Playery += 10;
}
}
The P.Player(x,y,w,h) don't change?
How can this be solved?
You are setting the defaults in every iteration, your code is synchronic and therefore responding to the keys is done after you draw, and in the next iteration you are overriding the values again so you will never see any changes.
In addition you instantiate a new P object every time and not keeping the previous instances alive, therefore they are GC.

Java - NullPoinerException Array of objects [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Can't figure this out, I've created a simple class of coordinates to hold x and y ints. In another class I have a global array of Coordinates declared called "ords". In my loop I'm adding Coordinates. When trying to use method getX() and getY() from the Coordinates class in my getaction method, I get a null pointer exception. I'm sure the objects are not null, but I still can't figure out whats going wrong. Any help appreciated.
import java.util.*;
import org.w2mind.net.*;
import java.io.Serializable;
public class ConorsMind implements Mind
{
int [][] surroundings = new int [12][16];
Coordinates [] ords = new Coordinates [192];
int currentX;
int currentY;
//====== Mind must respond to these methods: ==========================================================
// newrun(), endrun()
// getaction()
//======================================================================================================
public void newrun() throws RunError
{
}
public void endrun() throws RunError
{
}
private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++)
{
for(int z = 0; z < 12; z++)
{
surroundings[z][i] = someArray[counter];
if(surroundings[z][i] ==0) {
currentX=z;
currentY=i;
}
else if(surroundings[z][i]==4){
ords[n]= new Coordinates(z,i);
n++;
}
System.out.print(z+" , "+i+": "+surroundings[z][i]);
System.out.println();
counter++;
}
}
}
public Action getaction ( State state )
{
String s = state.toString();
String[] x = s.split(",");
int act =MinerWorldUpdated.NO_ACTIONS;
int counter = 0;
int [] surround = new int [192];
//in this way user will have ability to see what surrounds him
for(int i = 11; i < 203; i++)
{
surround[counter] = Integer.parseInt(x[i]);
counter++;
}
formTwoDimmensional(surround);
int [] response = new int [x.length];
for(int i = 0; i < x.length; i++)
{
response[i] = Integer.parseInt ( x[i] );
}
System.out.println("Current position: "+currentX+" ,"+currentY);
int coalX=ords[0].getX();
int coalY=ords[0].getY();
System.out.println("Coal position: "+coalX+" ,"+coalY);
if(coalX != 0 && coalY !=0)
{
if(coalX>currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
else if(coalX<currentX)
{
act=MinerWorldUpdated.ACTION_DOWN;
}
else if(coalY<currentY)
{
act=MinerWorldUpdated.ACTION_LEFT;
}
}
String a = String.format ( "%d", act );
return new Action ( a );
}
}
class Coordinates implements Serializable
{
private int x;
private int y;
public Coordinates(int x1, int y1)
{
x=x1;
y=y1;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
Error is as follows:
java.lang.NullPointerException
at ConorsMind.getaction(ConorsMind.java:146)
The error is stemming from the following two lines:
int coalX=ords[0].getX();
int coalY=ords[0].getY();
I am calling formTwoDimensional() and its working perfectly, the ords objects are being created successfully and are not null as testing with System.out.println(ords[n].getX()) is printing the expected result when placed in my else if(surroundings[z][i]==4) block.
You need to make sure that you're calling formTwoDimensional(). If you are indeed, then it's likely that you're not ever getting into your else if block in the nested for loop, and hence ords[0] is never actually being set, so when you try to access it, it's null.
The other thing to do, if you don't want to post the rest of your code, is to add some more debugging code. See below the boolean zero_pos_set. But make sure that you see the print "Zero pos set" before your program crashes. My bet is that you don't.
public class ConorsMind implements Mind
{
int [][] surroundings = new int [12][16];
Coordinates [] ords = new Coordinates [192];
boolean zero_pos_set = false;
private void formTwoDimmensional(int [] someArray)
{
int counter = 0;
int n=0;
for(int i = 0; i < 15; i++) {
for(int z = 0; z < 12; z++) {
surroundings[z][i] = someArray[counter];
if(surroundings[z][i] ==0) {
currentX=z;
currentY=i;
} else if(surroundings[z][i]==4) {
zero_pos_set = true;
ords[n]= new Coordinates(z,i);
n++;
}
counter++;
}
}
}
public Action getaction ( State state ) {
if(zero_pos_set) {
System.out.println("Zero pos set!");
}
int coalX=ords[0].getX();
int coalY=ords[0].getY();
System.out.println("Coal position: "+coalX+" ,"+coalY);
return new Action ( a );
}
}
Based on all of the debugging information posted within this thread, it seems that in your getaction() function, you're being passed some state, that doesn't contain 4.
When you parse this information and pass it to formTwoDimensional(), you will never reach the else if block, and so ords[0], or any other ords[n], will never be set.
As a result, when you try to access ords[0] back in your getaction() function, you actually get null, and hence your NullReferenceException.
It's an order of operations issue.
If you never make a call to formTwoDimmensional(), you'll never initialize anything inside of your array. Be sure you're calling that first.
The actual NPE happens when you attempt to call coalX=ords[0].getX();, which won't work if ords[0] is null.

Non-deterministic progress bar on java command line

I have a console application in which I would like to put a non-deterministic progress bar on the command line while some heavy computations are done. Currently I simply print out a '.' for each iteration in a while loop similar to the following:
while (continueWork){
doLotsOfWork();
System.out.print('.');
}
which works but I was wondering if anyone had a better/cleverer idea since this can get to be a little bit annoying if there are many iterations through the loop.
Here an example to show a rotating progress bar and the traditional style :
import java.io.*;
public class ConsoleProgressBar {
public static void main(String[] argv) throws Exception{
System.out.println("Rotating progress bar");
ProgressBarRotating pb1 = new ProgressBarRotating();
pb1.start();
int j = 0;
for (int x =0 ; x < 2000 ; x++){
// do some activities
FileWriter fw = new FileWriter("c:/temp/x.out", true);
fw.write(j++);
fw.close();
}
pb1.showProgress = false;
System.out.println("\nDone " + j);
System.out.println("Traditional progress bar");
ProgressBarTraditional pb2 = new ProgressBarTraditional();
pb2.start();
j = 0;
for (int x =0 ; x < 2000 ; x++){
// do some activities
FileWriter fw = new FileWriter("c:/temp/x.out", true);
fw.write(j++);
fw.close();
}
pb2.showProgress = false;
System.out.println("\nDone " + j);
}
}
class ProgressBarRotating extends Thread {
boolean showProgress = true;
public void run() {
String anim= "|/-\\";
int x = 0;
while (showProgress) {
System.out.print("\r Processing " + anim.charAt(x++ % anim.length()));
try { Thread.sleep(100); }
catch (Exception e) {};
}
}
}
class ProgressBarTraditional extends Thread {
boolean showProgress = true;
public void run() {
String anim = "=====================";
int x = 0;
while (showProgress) {
System.out.print("\r Processing "
+ anim.substring(0, x++ % anim.length())
+ " ");
try { Thread.sleep(100); }
catch (Exception e) {};
}
}
}
Try using a carriage return, \r.
In GUI applications the approach is generally a spinning circle or bouncing/cycling progress bar. I remember many console applications using slashes, pipe and hyphen to create a spinning animation:
\ | / -
You could also use a bouncing character in brackets:
[-----*-----]
Of course, as the other answered mentioned, you want to use return to return to the start of the line, then print the progress, overwriting the existing output.
Edit: Many cooler options mentioned by Will in the comments:
Cooler ASCII Spinners?
If you know how much work you have to do and how much is left (or done), you might consider printing out a percent complete bar graph sort of progress bar. Depending on the scope of this project, this could simply be in ascii or you could also consider using graphics.

Categories

Resources