Side Collisions - java
I'm making a tilemap game and I've got the simple collisions down. However to make the game work I have to know which side of the rectangle hit the wall/brick. Just putting a simple collision code inside of the main collision:
if(spriteX < brickX + brickwidth) {}
doesn't work. The main collision code at the moment is:
for(int counter = 0; counter < 31; counter++) {
if(spriteX + 40 >= collisionX[counter] && collisionX[counter] + 100 >= spriteX
&& spriteY + 40 >= collisionY[counter] && collisionY[counter] + 100 >= spriteY) {
velX = 0;
velY = 0;
collisions = counter;
} else {
if(counter == collisions && jumping == false) {
fall();
}
}
}
If you want the entire class:
package Main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class Panel extends JPanel implements Runnable, KeyListener {
// dimensions
public static final int width = 800;
public static final int height = 800;
public static final int scale = 1;
// main loop
private Thread thread;
private boolean running = false;
private int FPS = 60;
private int targetTime = 1000 / FPS;
// drawing
private Graphics2D g;
private BufferedImage image;
int x;
int y;
boolean makeCollision = false;
// sprite
int spriteX = 210;
int spriteY = 200;
int velX = 0;
int velY = 10;
public boolean notOnGround = true;
int counter;
int collisionsCounter;
int jumps = 0;
public int row;
public int column;
public boolean collision;
public boolean jumping = false;
public String side = null;
// tilemap
int[][] map = {
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 1, 0, 0, 1, 1},
{1, 0, 0, 0, 0, 1, 1, 1},
{1, 0, 0, 0, 1, 1, 0, 1},
{1, 0, 0, 1, 1, 0, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1}
};
int[] collisionX = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
int[] collisionY = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
int[] jump = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
int collisions;
public Panel() {
setPreferredSize(new Dimension(width * scale, height * scale));
setFocusable(true);
requestFocus();
}
public void addNotify() {
super.addNotify();
if(thread == null) {
running = true;
addKeyListener(this);
thread = new Thread(this);
thread.start();
}
}
public void init() {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) image.getGraphics();
}
public void update() {
if(spriteY < jump[0]) {
System.out.println(jump[0]);
jumping = false;
fall();
}
}
public void draw() {
g.clearRect(0, 0, WIDTH, HEIGHT);
x = 0;
y = 0;
for(column = 0; column <= 7; column++) {
x = 0;
for(row = 0; row <= 7; row++) {
changeColor(row, column, g);
g.fillRect(x, y, 100, 100);
x = x + 100;
}
y = y + 100;
}
g.setColor(Color.YELLOW);
g.fillRect(spriteX, spriteY, 40, 40);
spriteX += velX;
spriteY += velY;
for(int counter = 0; counter < 31; counter++) {
if(spriteX + 40 >= collisionX[counter] && collisionX[counter] + 100 >= spriteX
&& spriteY + 40 >= collisionY[counter] && collisionY[counter] + 100 >= spriteY){
velX = 0;
velY = 0;
collisions = counter;
} else {
if(counter == collisions && jumping == false) {
fall();
}
}
}
}
public void changeColor(int rowGive, int columnGive, Graphics g) {
if(map[rowGive][columnGive] == 1) {
g.setColor(Color.BLACK);
if(counter < 30) {
collisionX[counter] = x;
collisionY[counter] = y;
}
counter++;
} else {
g.setColor(Color.WHITE);
}
}
public void fall() {
velY = 5;
}
public void drawToScreen() {
Graphics g2 = getGraphics();
g2.drawImage(image, 0, 0, width * scale, height * scale, null);
g2.dispose();
}
public void run() {
init();
long wait;
long elapsed;
long start;
while(running) {
start = System.nanoTime();
update();
draw();
drawToScreen();
elapsed = System.nanoTime() - start;
wait = targetTime - elapsed / 1000000;
if(wait < 0) wait = 5;
try {
thread.sleep(wait);
} catch(Exception e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_RIGHT) {
velX = 5;
}
if(code == KeyEvent.VK_LEFT) {
velX = -5;
}
if(code == KeyEvent.VK_SPACE && jumping == false) {
jumping = true;
velY = -5;
jump[0] = spriteY - 100;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}}
Let's try to divide the problem a little bit. You don't need to find out when a rectange hit a wall: you need to find when the left side of the rectangle hit the right side of the wall and when the right side of the rectangle hit the left side of the wall.
To be more precise: don't test objects. Divide your object in collision surfaces (left and right sides in your case), find a way to modelize them (usually x and x+width are the left and right side of your rectangle, if x is the x coordinate of your topleft corner). And test both at the same time with an "or" condition.
if(spriteX < brickX + brickwidth || spriteX + spritewidth > brickX) {}
edit Reading your complete class a little more closely, it looks like you do something similar but you use "&&" condition, meaning you can never be true since both side collisions cannot happen at the same time. But I may be wrong, can you tell me ?
While not strictly about your collision problem I've noticed a "bug" in draw() that is causing your map array to be displayed flipped around the -45 angle.
You should be incrementing y when row is incremented and x when column is incremented. Do this and your display will look the same as your map initialization code.
In other words this:
public void draw() {
g.clearRect(0, 0, WIDTH, HEIGHT);
x = 0;
y = 0;
for(column = 0; column <= 7; column++) {
y = 0;
for(row = 0; row <= 7; row++) {
changeColor(row, column, g);
g.fillRect(x, y, 100, 100);
y = y + 100;
}
x = x + 100;
}
...
will make this
int[][] map = {
{1, 1, 1, 1, 1, 1, 1, 1},
{1, 0, 0, 1, 0, 0, 1, 1},
{1, 0, 0, 0, 0, 1, 1, 1},
{1, 0, 0, 0, 1, 1, 0, 1},
{1, 0, 0, 1, 1, 0, 0, 1},
{1, 0, 0, 1, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1}
};
look like this
instead of this
Related
How do I enter data from user input into a 2D array in Java?
I have a 2D array that needs it's values to be changed based on user input. private static double nursesArray[][] = { {2020, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2021, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2022, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2023, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2024, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; The program revolves around it asking the user for the base wage in the year 2020 for the second column (index 1). The program will then ask the user to enter the percent differences in each of the years below, going down each row in that same column. This process needs to be iterated in each of the columns all the way to the end. The way I have the rest of my code set up is that it uses the array as an argument for the method. public class nursesUnion { private static double nursesArray[][] = { {2020, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2021, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2022, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2023, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2024, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; public static void dataEntry(double arr[][]) { Scanner inp = new Scanner(System.in); } ... I really have no idea where to begin for this. Java is a new language for me and I haven't fully wrapped my head around it yet.
Assuming user already knows how many values they need to enter, you can start with this basic verion: public static void dataEntry(double arr[][]) { Scanner inp = new Scanner(System.in); int rows = nursesArray.length; int columns = nursesArray[0].length; for (int row = 0; row < rows; row++) { System.out.println("Please, enter values for year " + nursesArray[row][0]); // starts with 1 to skip the year. for (int column = 1; column < columns; column++) { nursesArray[row][column] = inp.nextDouble(); } } } It just iterates trough rows and columns from left to right, from top to bottom.
public static void dataEntry(double arr[][]) { Scanner inp = new Scanner(System.in); for(int column = 1; column < arr[0].length; column++){ System.out.println("Enter base wage for col:"+column); arr[0][column]=inp.nextInt(); System.out.println("Enter % increase per year"); int increase=inp.nextInt(); for(int row=1; row<arr.length; row++){ arr[row][col] += arr[row-1][column]*increase/100; } } }
How to implement dfs using recursion?
I'm trying to implement DFS with recursion using the following code, public static void dfs(int i, int[][] mat, boolean [] visited){ visited[i] = true; // Mark node as "visited" System.out.print(i + "\t"); for ( int j = 0; j < visited.length; j++ ){ if ( mat[i][j] ==1 && !visited[j] ){ dfs(j, mat, visited); // Visit node } } } I have a matrix and an array for tracking visited nodes, // adjacency matrix for uni-directional graph int [][] arr = { // 1 2 3 4 5 6 7 8 9 10 { 0, 1, 1, 1, 0, 0, 0, 0, 0, 0}, // 1 { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, // 2 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // 3 { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, // 4 { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0}, // 5 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // 6 { 0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, // 7 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // 8 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, // 9 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} // 10 }; boolean [] visited = new boolean[10]; for (int i =0; i< visited.length; ){ visited[i++] = false; } I'm making the call as following, dfs(1, arr, visited); This return // 1 6 7 8 9 which is not correct. It should return : [1 2 7 8 9 10 3 4 5 6] The graph is as following, How can I improve my code ?
Your code is perfectly correct, just call is incorrect. You're calling the dfs on the 1st node, but root is at 0th node. So if you just replace dfs(1, arr, visited); with dfs(0, arr, visited); it would print the correct order of indices, which means every element would be one less than your required result as Java array index starts at 0. Also there's no need to initialize a primitive array as Java primitive arrays are already initialized and default value of boolean is false. Following is the code after modifications public class Dfs { public static void main(String[] args) { int[][] arr = { // 1 2 3 4 5 6 7 8 9 10 { 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 }, // 1 { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, // 2 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 3 { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 }, // 4 { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, // 5 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 6 { 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 }, // 7 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // 8 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, // 9 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } // 10 }; boolean [] visited = new boolean[10]; dfs(0, arr, visited); } public static void dfs(int i, int[][] mat, boolean[] visited) { if(!visited[i]) { visited[i] = true; // Mark node as "visited" System.out.print( (i+1) + " "); for (int j = 0; j < mat[i].length; j++) { if (mat[i][j] == 1 && !visited[j]) { dfs(j, mat, visited); // Visit node } } } } } Output 1 2 7 8 9 10 3 4 5 6
Read string from USB HID RFID Reader with Java
I'm trying to read a String from a via USB connected RFID-Reader. The Reader is recognized correctly inside my appliaction. But I do not know how to read the transferred characters into a String. If I do not detach the device, the String is printed like by a Keyboard (as you would expect from a HID). What I want is to catch that String inside my Java application only. This is the reason why I detach the USB device. For example my application prints '"''#$&' to the console (see code below) or something like this [0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] But what I wanted to read is 05006790. I think that there is a stupid false in my attempt. I hope that someone can help me to figure out how I have to read the Bytes into a String correctly. Thank you very much. CODE FOLLOWS HERE Context context = new Context(); int result = LibUsb.init(context); DeviceList list = new DeviceList(); result = LibUsb.getDeviceList(context, list); for (Device device: list) { int address = LibUsb.getDeviceAddress(device); int busNumber = LibUsb.getBusNumber(device); DeviceDescriptor descriptor = new DeviceDescriptor(); DeviceHandle handle = new DeviceHandle(); int resultOpen = LibUsb.open(device, handle); // if (resultOpen < 0) // handle = null; int resultDescriptor = LibUsb.getDeviceDescriptor(device, descriptor); // if (resultDescriptor< 0) // handle = null; if(descriptor.idVendor() == 0x8ff && descriptor.idProduct() == 0x0009) { System.out.println("found"); LibUsb.detachKernelDriver(handle, 0); } } UsbServices services = UsbHostManager.getUsbServices(); UsbDevice deviceHigh = findDevice(services.getRootUsbHub(), (short) 0x8ff, (short) 0x0009); if(deviceHigh != null) { System.out.println("found high"); UsbConfiguration configuration = deviceHigh.getActiveUsbConfiguration(); UsbInterface iface = configuration.getUsbInterface((byte) 0x00); iface.claim(); UsbEndpoint endpoint = iface.getUsbEndpoint((byte) 0x81); UsbPipe pipe = endpoint.getUsbPipe(); pipe.open(); byte[] buffer = new byte[128]; int rx = 0; rx = pipe.syncSubmit(buffer); System.out.printf("%d bytes received\n", rx); System.out.println(Arrays.toString(buffer)); iface.release(); }
Colision detecting in java(Tiled map)
Here i have a code with a picture moving around the map. How to make this picture colide when interacte with map tiles ? I'm a beginer at java so i have no ideas. Any Help or advise is very welcome. Code: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import javax.swing.Timer; import javax.imageio.ImageIO; import javax.swing.JFrame; import org.omg.CORBA.portable.InputStream; import java.io.Reader; public class NewTest extends JFrame implements KeyListener { /** * */ private static final long serialVersionUID = 1L; private Image TestImage; private BufferedImage bf; private BufferedImage bufferedImage; private int cordX = 100; private int cordY = 100; public int mapy=25; public int mapx=mapy; public int size= 20; private boolean down, up, left, right; private Image wall = Toolkit.getDefaultToolkit().getImage("image/Koala.jpg"); private Image no = Toolkit.getDefaultToolkit().getImage("image/house.jpg"); public static int[][] map = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 10, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 11}, {0, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 0, 4, 0, 5, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}, {0, 12, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 13}}; public NewTest() throws IOException { setTitle("Testing...."); setSize(mapy*size+50,mapx*size+50); imageLoader(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void imageLoader() throws IOException { TestImage = Toolkit.getDefaultToolkit().getImage("image/Koala.jpg"); addKeyListener(this); } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ bf = new BufferedImage( this.getWidth(),this.getHeight(), BufferedImage.TYPE_INT_RGB); try{ animation(bf.getGraphics()); g.drawImage(bf,0,0,null); }catch(Exception ex){ } } public void animation(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; for (int y = 0; y <= mapy; y++){ for (int x = 0; x <= mapx; x++){ int L = x * size; int U = y * size; int R = size; int D = size; /// g2d.rotate(Math.toRadians(-90)); if (map[y][x] == 1){ //no black wall g2d.setColor(Color.green); g2d.fillRect(L, U, R, D); }else if (map[y][x] == 2){ //on left g2d.setColor(Color.green); g2d.fillRect(L, U, R, D); g2d.setColor(Color.black); g2d.fillRect(L-size/2 +2, U, 8, size); }else if (map[y][x] == 3){ //on right g2d.setColor(Color.green); g2d.fillRect(L, U, R, D); g2d.setColor(Color.black); g2d.fillRect(L+size, U, 8, size); }else if (map[y][x] == 4){ //on top g2d.setColor(Color.green); g2d.fillRect(L, U, R, D); g2d.setColor(Color.black); g2d.fillRect(L, U-size/2 + 2, size, 8); }else if (map[y][x] == 5){ //on bottom g2d.setColor(Color.green); g2d.fillRect(L, U, R, D); g2d.setColor(Color.black); g2d.fillRect(L, U+size, size, 8); }else if (map[y][x] == 10){ //on bottom g2d.setColor(Color.green); g2d.fillRect(L, U, R, D); g2d.setColor(Color.black); g2d.fillRect(L, U-size/2 + 2, size, 8); g2d.fillRect(L-size/2 +2, U, 8, size ); }else if (map[y][x] == 11){ //on bottom g2d.setColor(Color.green); g2d.fillRect(L, U, R, D); g2d.setColor(Color.black); g2d.fillRect(L, U+size, size, 8); }else if (map[y][x] == 12){ //on bottom g2d.setColor(Color.green); g2d.fillRect(L, U, R, D); g2d.setColor(Color.black); g2d.fillRect(L, U+size, size, 8); }else if (map[y][x] == 13){ //on bottom g2d.setColor(Color.green); g2d.fillRect(L, U, R, D); g2d.setColor(Color.black); g2d.fillRect(L, U+size, size, 8); } } } g.drawImage(TestImage, cordX, cordY,20 , 20, this); } public static void main(String[] args) { try { new NewTest(); } catch (IOException e) { e.printStackTrace(); } } public void keyPressed(KeyEvent ke) { switch (ke.getKeyCode()) { case KeyEvent.VK_RIGHT: right = true; break; case KeyEvent.VK_LEFT: left = true; break; case KeyEvent.VK_DOWN: down = true; break; case KeyEvent.VK_UP: up = true; break; } updateState(); } public void keyReleased(KeyEvent ke) { switch (ke.getKeyCode()) { case KeyEvent.VK_RIGHT: right = false; break; case KeyEvent.VK_LEFT: left = false; break; case KeyEvent.VK_DOWN: down = false; break; case KeyEvent.VK_UP: up = false; break; } updateState(); } protected void updateState() { if (right) { cordX += 5; } else if (left) { cordX -= 5; } if (down) { cordY += 5; } else if (up) { cordY -= 3; } if (down && up) { cordY += 0; cordX += 0; } if (right && left) { cordX += 0; cordY += 0; } System.out.printf("X:");System.out.println(cordX); System.out.printf("Y:");System.out.println(cordY); repaint(); } public void keyTyped(KeyEvent ke) { } } Thank you for help!
Good approach is to seperate visual and reality model. It means deep in the program, you have your "physics rules" and all objects and based on that model, you draw it. You can start with creating class like this public class ObjectInMyGame{ private int posx; private int posy; private int width; private int height; private Image image; private int movingX; private int movingY; //Note that it is good to use Point or something like that, instead of posx, posy. } Then it is good to have some kind of "game controller", which is running your whole world. public class GameController{ List<ObjectInMyGame> objects; public updateGame(){ for (ObjectInMyGame object : objects){ object.doSomething(); //sometimes it is good idea to let objects itself do something } } } So for example, when you move object, you can check, if he collide or not and then decide what to do.
use fileReader in java to read one character at a time
As a part of a school exercise, I am trying to read characters from a text file and count the frequency of the characters appeared the text file. I stored the frequency in an array, where the index is the ASCII code of the char, and the number in the array is the frequency. int c; FileReader fr = new FileReader (inputFile); int [] freq = new int [200]; while ( (c= fr.read())!= -1){ int index = c; freq [index]= freq [index]+1; } PrintWriter pw = new PrintWriter(new FileWriter(outputFile)); for (int i =0; i<frequency.length; i++) { if(frequency[i]!=0){ pw.println( ((char)i) + " " +frequency[i]); Somehow this method only works with text files with a single line, like "abcdefgh". It doesn't work with files with multiple lines, like "ab /newline cde /newline..." For this type of file, it will generate a blank line and some numbers on top of the result when I print out the array. I really couldn't figure out why.
It looks fine to me. import java.io.FileReader; import java.util.Arrays; public class Foo { public static void main(String[] args) throws Exception { FileReader fr = new FileReader("/tmp/a"); int[] freq = new int[200]; int c; while ((c = fr.read()) != -1) { freq[c] = freq[c] + 1; } System.out.println(Arrays.toString(freq)); } } Example contents of /tmp/a: abc def Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] edit - In response to the revised question: The output is 2 a 1 b 1 c 1 d 1 e 1 f 1 The file has two line breaks, so the program is writing a line break, and then "2". I'm guessing you want to convert the characters to something like their Java escape sequences. Here's a solution using Apache commons-lang: import org.apache.commons.lang3.StringEscapeUtils; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Foo { public static void main(String[] args) throws Exception { write(read()); } static int[] read() throws IOException { FileReader fr = new FileReader("/tmp/a"); int[] freq = new int[200]; int c; while ((c = fr.read()) != -1) { freq[c] = freq[c] + 1; } return freq; } static void write(int[] freq) throws IOException { try (PrintWriter pw = new PrintWriter(new FileWriter("/tmp/b"))) { for (int i = 0; i < freq.length; i++) { if (freq[i] != 0) { char c = (char) i; String s = StringEscapeUtils.escapeJava("" + c); pw.println(s + " " + freq[i]); } } } } } Output: \n 2 a 1 b 1 c 1 d 1 e 1 f 1