Yoo, hope this isn't too specific.
I'm making a sudoku and I got method that takes care of all the false x and y-coordinates for every wrong (to make them go red); which I layer in a string. If I find an incorrect number I layer the coordinates as: x,y for every wrong and then add more like: x,y,x,y,x,y ...
SudokuResultCount is my other class where I keep the coordinates, and FalseCoordinates is the string where I keep them. So when I press "Correct my sudoku"-button this method goes.
This is made in this method:
public static void totalfalsecoordinates(int array[][], int array2[][]){
SudokuResultCount.setFalseCoordinates("");
for(int x=0; x < 9; x++)
{
for(int y=0; y < 9; y++){
try{
if(array2[x][y] != array[x][y]&& array2[x][y] != 0)
{
SudokuResultCount.setFalseCoordinates(x + y + "");
}
}
catch(Exception e){
}
}
}
}
I run this method later on in this method:
try{
int falseCoordinatesLength = SudokuResultCount.getFalseCoordinates().length();
if(falseCoordinatesLength > 0)
{
SudokuMetoder.totalfalsecoordinates(KeepingUpWithTheSudokus.getSolution(), KeepingUpWithTheSudokus.getStartingvalues());
int targetStringchar = 0;
int targetStringchar1= 1;
int numbersOfLoops = SudokuResultCount.getFalseCoordinates().length();
int realnumbersOfLoops = numbersOfLoops/2;
for(int number = 0; number < realnumbersOfLoops; targetStringchar = targetStringchar + 2, targetStringchar1 = targetStringchar1 + 2, number++){
char a_char = SudokuResultCount.getFalseCoordinates().charAt(targetStringchar);
char b_char = SudokuResultCount.getFalseCoordinates().charAt(targetStringchar1);
int x = Character.getNumericValue(a_char);
int y = Character.getNumericValue(b_char);
System.out.println(y);
// int x = (int)a_char;
// int y = (int)b_char;
textFields[x][y].setStyle("-fx-border-color: red ; -fx-border-width: 2px ;");
}
}
}
catch(Exception e3){
String str = "2" + "2" + "";
char b_char = str.charAt(0);
int x = Character.getNumericValue(b_char);
System.out.println(x);
textFields[2][3].setStyle("-fx-border-color: red ; -fx-border-width: 2px ;");
textFields[2][3].setStyle("-fx-background-color: transparent, #909090, transparent, red;");
}
If the number of the string length > 0 then search through. And since I take two numbers from the String at one time, I take the length of the String and divide it by two.
Then I make them into characters so I can decide which one to take.
If I go through the coordinates: 0,1
Any wrongs? Ok then make array[0][1] shine red - otherwise move on.
Then it moves 0,1 2,3 4,5 ...
Ask for removal if too specific!
thanks
Won't most likely help anyone, but I found the answer. It messed up where I added x + y + "" into the String in which i layered the coordinates. I had to do: "" + x + "" + y + ""
Related
javascript code in processing 3.5.3 not working, not sure why. It's supposed to create circles and have them bounce around the screen, instead it makes the right amount of circles but they don't move. It seems like intlist.set() isn't working, but I'm not sure why. Help would be appreciated.
import javax.swing.JOptionPane;
int x = 200;
int y = 150;
int b = 50;
float slope = -1;
int numOfCircles = 10;
IntList initPosX = new IntList();
IntList initPosY = new IntList();
IntList exes = new IntList();
IntList whys = new IntList();
IntList xSpeeds = new IntList();
IntList ySpeeds = new IntList();
void setup()
{
numOfCircles = int(JOptionPane.showInputDialog(frame, "How many circles ya want?"));
size(800,400);
for(int i = 0; i < numOfCircles; i++)
{
int toAddX = int(random(0,400));
initPosX.append(toAddX);
int toAddY = int(random(0,300));
initPosY.append(toAddY);
exes.append(0);//(int(random(-30,30)));
whys.append(0);//(int(random(-30,30)));
xSpeeds.append(1);
ySpeeds.append(1);
}
}
void draw()
{
background(100,100,100,255);
for(int i = 0; i < numOfCircles; i++)
{
ellipse(exes.get(i) + initPosX.get(i), whys.get(i) + initPosY.get(i), 20, 20);
exes.set(i, i + xSpeeds.get(i));
whys.set(i, i + ySpeeds.get(i));
if(exes.get(i) > width || exes.get(i) <= 0)
{
print("side wall hit");
xSpeeds.set(i, i*= slope);
}
if(whys.get(i) > height || whys.get(i) <= 0)
{
print("roof hit");
ySpeeds.set(i, i*= slope);
}
}
}
The problem is at those lines:
exes.set(i, i + xSpeeds.get(i));
whys.set(i, i + ySpeeds.get(i));
What you want to do there, is add the speed to the current value of exes/whys at the index i.
But what you are actually doing is set them to the index + the speed.
Since the index is never going to change, neither are the positions.
To fix this, replace it with this:
exes.set(i, exes.get(i) + xSpeeds.get(i));
whys.set(i, whys.get(i) + ySpeeds.get(i));
Update
When changing just this, your code still won't work properly, because the collision detection:
if(exes.get(i) > width || exes.get(i) <= 0)
{
print("side wall hit");
xSpeeds.set(i, i*= slope);
}
if(whys.get(i) > height || whys.get(i) <= 0)
{
print("roof hit");
ySpeeds.set(i, i*= slope);
}
does not detect collision for the actual position, because that would be the position (exes, whys) + the initPos's, so it should be
if (exes.get(i) + initPosX.get(i) > width || exes.get(i) + initPosX.get(i) <= 0)
{
//the code
}
if (whys.get(i) + initPosY.get(i) > height || whys.get(i) + initPosY.get(i) <= 0)
{
//the code
}
If you were to start it now however, you would get an error. That is because you changing to something negative. instead of i*= slope just use int(i * slope) (because int * float returns a float, you have to convert the result to an int by using int()).
Furthermore, you again don't actually want the index, but the current value at the index:
xSpeeds.set(i, int(xSpeeds.get(i) * slope); //the same for ySpeeds
The robot can move on the plane in 4 directions: U - up, D - down, L - left, R - right. Traffic example is UUDLR, DLRUD. I have to implement the "walk" method so that it returns the robot position after passing the indicated path. So I do this:
class Main {
static int[] walk(String path) {
int[] A = {0,0};
char charFromPath;
for (int i = 0 ; i < path.length() ; i++) {
charFromPath = path.charAt(i);
if(charFromPath == 'U')
{
A[1]++;
}
if(charFromPath == 'D')
{
A[1]--;
}
if(charFromPath == 'L')
{
A[0]--;
}
if(charFromPath == 'R')
{
A[0]++;
}
}
return A;
}
public static void main(String[] args) {
{
String path="UUDLR";
int[] position = walk(path);
System.out.println("case 1 - path "+path+ " position 0,1");
if(position[0]==0 && position[1]==1)
System.out.println("the robot went right");
else
System.out.println("the robot smashed");
}
{
String path="DLRUD";
int[] position = walk(path);
System.out.println("\ncase 2 - path "+path+ " position 0,-1");
if(position[0]==0 && position[1]==-1)
System.out.println("the robot went right");
else
System.out.println("the robot smashed");
}
}}
Now in version 2 according to logic U, D, L, R, commands are UP DOWN LEFT RIGHT. Traffic example is UPUPLEFTRIGHTUP.
Now in version 3 commands are for instance 3xUP 2xLEFT DOWN RIGHT. 3xUP means move three times up and 2xLEFT 2 times left. Add a restriction in movement for the robot, he cant go outside the 10x10 area (item 10.10 or -10, -10 is the last valid value).
I have no idea how to write it. How to count the number of repetitions string in string?
You can try something like
String str = "UPUPLEFTRIGHTUP";
int countUP = ( str.split("UP", -1).length ) - 1;
int countLEFT = ( str.split("LEFT", -1).length ) - 1;
int countRIGHT = ( str.split("RIGHT", -1).length ) - 1;
int countDOWN = ( str.split("DOWN", -1).length ) - 1;
The restriction can be verified by comparing the int values to the limits of the box (10*10 in your case).
For the position, if we suppose each movement is 1 unit then :
int x = 0; //starting point in Ox axis
int y = 0; //starting point in Oy axis
x = countRIGHT - CountLeft;
y = countUP - CountDOWN;
The couple (x,y) is the position of your robot.
move function :
int[] walk(String path) {
int[] position = {0,0};
int countUP = ( path.split("UP", -1).length ) - 1; //Counts how many UP command
int countLEFT = ( path.split("LEFT", -1).length ) - 1; //Counts how many LEFT command
int countRIGHT = ( path.split("RIGHT", -1).length ) - 1; //Counts how many RIGHT command
int countDOWN = ( path.split("DOWN", -1).length ) - 1; //Counts how many DOWN command
position[0] = countRIGHT - countLEFT;
position[1] = countUP - countDown;
return position;
}
for version 2 you could split your original string and put it in an array with a method you can call on a string String [] tmpsplit = tmp.split(" ");. That way your array has inside each cell one direction (UP or DOWN or LEFT or RIGHT).
Then you can put this array in a similar for with the one that you have for version 1. Replace the charFromPath == 'U' with tmpsplit[i].equals("UP")
I know theres another question like this online but I can't get my code to work. I don't know if my if statements is incorrect or if its something else. This is an extension of my earlier questions
Remove duplicates in a 2D array and add the corresponding values
The question is still the same but except instead of using a 2D array I am using a for loop and I wan't to keep track of the previous numbers in the for loop but when I print the numbers on to the console I get duplicate r values. I hope someone can help me see the mistake. Thanks in advance!
Here is the code I am working on:
double rMax = -1;
double previous;
for(int i =1; i< 256; i++){
for(int y =1; y< 256; y++){
//image.getPixel(i, y);
String x = image.getLocationAsString(i, y);
String n = image.getValueAsString(i, y);
String delim = ", value=";
String [] tokens = n.split(delim);
double num = Double.parseDouble(tokens[1]);
//if(image.getR() < 1.43){
String [] t = x.split("r=");
String[] b = t[1].split(" mm/c");
//System.out.print("Meet b: "+b[0]);
double radius = Double.parseDouble(b[0]);
String [] theta = x.split("theta= ");
String [] token2 = theta[1].split(Character.toString(IJ.degreeSymbol));
float thetaNum = Float.parseFloat(token2[0]);
//System.out.print(" This is the theta value: "+thetaNum+" ");
if(radius == rMax){
rMax = radius;
}
String prevX = image.getLocationAsString(i-1, y-1);
String prevN = image.getValueAsString(i-1, y-1);
String [] prevT = prevX.split("r=");
String[] prevB = prevT[1].split(" mm/c");
//System.out.print("Meet b: "+b[0]);
double prev_radius = Double.parseDouble(prevB[0]);
previous = prev_radius;
if(previous == radius){
System.out.println(radius);
}
else{
System.out.println(radius);
}
//if(thetaNum <= 180.00){
data.add(radius, num);
//}
//}
}
}
System.out.println(rMax);
This is what it prints:
1.59
1.59
1.58
1.58
1.57
1.56
1.56
1.55
1.55
1.54
1.54
1.53
1.52
1.52
You're not setting the value of previous anywhere.
Update
Your code has so many problems. It'll never update rMax, for example. I think this code will do what you're trying to achieve, assuming that data is a dictionary of some kind. If not you'll need to modify the code that updates the value stored for the radius.
double rMax = -1;
double previous = -1;
for(int i =1; i< 256; i++){
for(int y =1; y< 256; y++){
String x = image.getLocationAsString(i, y);
String n = image.getValueAsString(i, y);
String delim = ", value=";
String [] tokens = n.split(delim);
double num = Double.parseDouble(tokens[1]);
String [] t = x.split("r=");
String [] b = t[1].split(" mm/c");
double radius = Double.parseDouble(b[0]);
String [] theta = x.split("theta= ");
String [] token2 = theta[1].split(Character.toString(IJ.degreeSymbol));
float thetaNum = Float.parseFloat(token2[0]);
if(radius > rMax){
rMax = radius;
}
if(radius == previous){
data[radius] += num;
}
else {
data.Add(radius, num);
}
}
}
System.out.println(rMax);
And, by the way, this code would be so much easier to read if you used Regex to capture the values from the string rather than all the confusing splits.
Im currently making a game in my spare time to improve my java but im having trouble with one of the things i want to do. Ive made the game so i can put a item into a certain position. In this example its a tower in a certain location. When this tower is placed in this location and i click on the tower i want it to output a message. However ive tried many ways to do this and i havent been able to find a solution. The code i have for this is:
public static void click(int X, int Y){
System.out.println("X. " + X + " Y. " + Y);
if(Screen.room.block[X][Y].airID == Value.tower){
System.out.println("Tower clicked");
}
}
When the tower is placed in a location the code i use for this is:
if(holdsItem){
for(int y=0; y<Screen.room.block.length; y++){
for(int x=0; x<Screen.room.block[0].length; x++){
if(Screen.room.block[y][x].contains(Screen.mse)){
if(Screen.room.block[y][x].groundID != Value.ground && Screen.room.block[y][x].airID == Value.tower){
Screen.room.block[y][x].airID = heldID;
}
}
}
}
}
When i put down a tower by:
System.out.println(Screen.room.block[y][x]);
i get
Block[x=243,y=260,width=52,height=52]
This works fine and the tower is placed. I then wanted to use the location of what the tower is placed and then if that location is pressed the message would print in the console. However this doesnt happen. Can anyone help me fix this problem.
I use a mouse listener which is:
public void mouseClicked(MouseEvent e) {
e.getX();
e.getY();
Block.click(e.getX(), e.getY());
}
When i click on a location i get:
System.out.println("X. " + X + " Y. " + Y);
X. 257 Y. 298
if this helps.
Right now you are using pixels to get the location of your object, so you need to check more than the exact "origin" pixel for each block.
public static void click(int X, int Y){
System.out.println("X. " + X + " Y. " + Y);
//Look for every block in the matrix
for ( int i = 0; i<Screen.room.block.length; i++ ) {
for ( int j = 0; j<Screen.room.block[0].length; j++ ) {
if(Screen.room.block[i][j].airID == Value.tower){
//Check if we hit within the block's bounds
if ( X >= i && X <= i+blockWidth &&
Y >= j && Y <= j+blockHeight )
System.out.println("Tower clicked");
return;
}
}
}
}
A common practice is to store your objects in some kind of list or uni-dimensional array, so that you can avoid the
for ( int i = 0; i<Screen.room.block.length; i++ ) {
for ( int j = 0; j<Screen.room.block[0].length; j++ ) {
and just do
for ( int i = 0; i<Screen.room.blocks.length; i++ ) {
to check for every block and to avoid having such a big matrix when you must check every block anyway.
Another approach: you could give each block a place in a checkers-like matrix and then transform the mouse clicked event coordinates from pixels to "block" coordinates:
public void mouseClicked(MouseEvent e) {
int x = e.getX() / widthOfABlockInPixels;
int y = e.getY() / heightOfABlockInPixels;
Block.click(x, y);
}
Say your objects are 100x100 pixels, then this would give you the right block coordinates for
(160, 150) => (1, 1)
(60, 50) => (0, 0)
and so on.
This might sound a little over-simplified, but, then again, I'm just spit-balling here. Have you thought about implementing the message into a JOptionPane.showMessageDialog? Not sure if that would be what you're looking for.
I'm trying to make the game Tetris in java.
I've gotten it to the point where:
a new block is generated when it hits the floor or its y+1 is not null (meaning there's another block under it)
public void collisionCheck(int x, int y) {
if (activetile.getY() == this.height-2 || getTileAt(x, y+1) != null) {
activetile = new Tile(this, 0, 0);
}
}
A row clears when the bottom row is full of non-null values, or the Tetris pieces (for y = 4 (the floor), loop through x till x = 4 and check if all non-null)
public void checkBottomFull(int x, int y) {
while (getTileAt(x,y) != null) {
say("(" + x + ", " + y +")");
if (x == 3) {
say("row is full");
//replace full row with tiles from above
for (int i = 0; i < 4; i++) {
for (int j = 5; j > 0; j--) {
grid[j][i] = getTileAt(i,j-1);
grid[j-1][i] = null;
}
}
break;
}
x++;
}
}
Right now, I'm using keys to move the block:
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_DOWN) {
activetile.setLocation(activetile.getX(), activetile.getY()+1);
System.out.println("coordinates: " + activetile.getX() + ", " + activetile.getY());
collisionCheck(activetile.getX(),activetile.getY());
checkBottomFull(0,4);
repaint();
}
}
There's two issues I'm having:
1) In the picture you'll notice I've dropped the block all the way to the floor... and the row cleared. After it's cleared, it will generate a block to the top left (x=0, y=1) which I have no control over.
2) On the floor there seems to be a red line... which I'm assuming is a row of blocks hidden by the JFrame... I'm not sure why that's there.
FYI: If you're wondering why grid[j][i] has the rows and columns flipped (aka, why it's not grid[i][j]) is because I instantiated it as grid = new Tile[height][width];
Any thoughts?
Thanks!
It is hard to say what is wrong without actually debugging your app.
But maybe try this one:
public void checkBottomFull(int x, int y) {
while (getTileAt(x,y) != null) {
say("(" + x + ", " + y +")");
if (x == 3) {
say("row is full");
//replace full row with tiles from above
for (int i = 0; i < 4; i++) {
for (int j = 4; j >= 0; j--) {
grid[j][i] = getTileAt(i,j-1);
grid[j-1][i] = null;
}
}
break;
}
x++;
}
}
You have 5 rows (indexed from 0 to 4) and 4 columns (indexed from 0 to 3).
What values of height and width do you pass to:
grid = new Tile[height][width];
Because from what I see you should do something like that:
grid = new Tile[5][4];
Bah,
Turns out in the key event, I needed to check if the bottom was full before checking if there is a collision.
I guess what was happening is, when I was checking collisionCheck(activetile.getX(),activetile.getY()); before checkBottomFull(0,4);, when the bottom was full, it would clear the row and set the current row equal to the row above it: grid[j][i] = getTileAt(i,j-1);, the problem was that collisionCheck was generating a new piece and the that newly generated piece was getting cleared and replaced by checkBottomFull.
Putting the collision check after the checkBottomFull ensures that the newly generated piece won't be replaced if bottom is full.