Average X and Y coordinate from a mouse JAVA - java

How can I calculate the average of 12 coordinates that are received from an mouse IR event in JAVA?
What I mean is:
Every movement is sended in X and Y coordinates to me.
Buffer these coordinates in 12 coordinates
Calculate the average of these 12 coordinates
I know how to get the average of an array, but how does it work when the X is a coordinate? The X is not defined yet, because it change, so how can I do this?
Something like this does the job:
int count = 0;
double buffer = 0;
while(true){ // loop waarin inputs binnen komen
if(true){ // stel dat je een input binnenkrijgt
count++;
buffer += oX;
if( count == 12 ){ // als je er 12 gekregen hebt
//send_output( buffer/12 ); // verzend
// reset buffer en count
System.out.println(buffer/12);
buffer = 0;
count = 0;
}
}
}
#edit
Maybe to understand it better:
public void onIrEvent(IREvent arg0) {
int oX;
int oY;
oX = arg0.getAx()/10;
oY = arg0.getAy()/10;
The oX and oY have to be putted in a buffer where there can be in 12 coordinates. Then calculate the average of them.
thanks in advance
kind regards
Pascal

Make bufferX , and bufferY two variables public ; and set them in this method
int i =0;
public void onIrEvent(IREvent arg0) {
int oX;
int oY;
oX = arg0.getAx()/10;
oY = arg0.getAy()/10;
/////////////here set the buffer
if(i<12){
bufferX += oX;
bufferY +=oY;
}
i++;
}
Try this Example:
public class MouseMotionEventDemo extends JPanel implements MouseMotionListener {
private int mX, mY;
int bufferX = 0;
int bufferY = 0;
int count = 0;
public MouseMotionEventDemo() {
addMouseMotionListener(this);
setVisible(true);
}
public void mouseMoved(MouseEvent me) {
mX = (int) me.getPoint().getX();
mY = (int) me.getPoint().getY();
bufferX += mX;
bufferY += mY;
System.out.println("X: "+mX+" Y:"+mY);
count++;
if (count == 12) {
System.out.println("X average =" +bufferX / 12);
System.out.println("Y average =" +bufferY / 12);
count = 0;
}
}
public void mouseDragged(MouseEvent me) {
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new MouseMotionEventDemo());
f.setSize(200, 200);
f.show();
}
}

Related

Assistance with creating grid/ball (objects?) in Java

I'm trying to create a Roomba program with a ball that bounces around the screen that cleans the tiles that it passes over. The program should start with all grey tiles and when the ball passes over them then the tiles turn white. Currently I have the ball that bounces around everywhere and a grid method which creates a 5x5 grid.
I have encountered two problems:
I cannot make the grid and the ball appear in the same simulation while running the program, it's either one or the other.
I'm having trouble with finding a way to analyze if the ball has passed over certain squares in the grid, perhaps I need to create an object for the grid/ball?
My code:
import edu.princeton.cs.introcs.StdDraw;
public class Roomba {
private static int windowWidth = 200;
private static int windowHeight = 200;
private static double x = 100;
private static double y = 100;
private static double vx = 2;
private static double vy = 4;
private static int radius = 5;
private static boolean inGame = true;
public static void updateLocations() {
x += vx;
y += vy;
}
public static void drawGrid() {
StdDraw.setScale(0, 5);
int[][] grid = new int[5][5];
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid.length; y++) {
grid[x][y] = 255;
}
}
for (int x = 0; x < grid.length; x++) {
for (int y = 0; y < grid.length; y++) {
StdDraw.square(x, y, 1);
}
}
}
public static void updateVelocities() {
if (y + radius >= windowHeight) {
vy = -vy;
} else if (y - radius <= 0) {
vy = -vy;
}
if (x >= 194 || x <= 6) {
vx = -vx;
}
}
public static void setBackground() {
StdDraw.clear(StdDraw.GRAY);
// drawGrid();
}
public static void drawBall() {
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.filledCircle(x, y, radius);
// StdDraw.setPenColor(StdDraw.RED);
// StdDraw.filledSquare(x + 3, y + 3, 1);
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(100, 70, "x is: " + x + " y is: " + y);
}
public static void draw() {
setBackground();
drawBall();
}
public static void main(String[] args) {
StdDraw.setCanvasSize(800, 800);
StdDraw.setXscale(0, windowWidth);
StdDraw.setYscale(0, windowHeight);
while (true) {
if (inGame) {
draw();
updateVelocities();
updateLocations();
} else {
StdDraw.text(100, 100, "Game Over");
}
// change to if all tiles have been cleaned
// if (x + radius > windowWidth || x - radius < 0) {
// inGame = false;
// }
StdDraw.show(20);
}
}
}
Maybe the background is being drawn over the ball or vice verse? Try to draw the ball first then the background? Make sure the ball is actually being rendered at the correct size and not as the entire screen. I'm not to familiar with 2D graphics but maybe there is some z fighting?

Java - Moving Randomly Generated Tilemap

I'm pretty fresh to java but I wanted to create a exploration type game. I researched for the last 2 weeks and was able to implement the diamond square algorithm for some pretty sweet terrain. But now I'm having trouble trying figure out how to move the map and how to continue the random generation. Here's what I have so far.
Game.java
package com.game.main;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.Random;
//import java.util.Random;
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 5420209024354289119L;
public static final int WIDTH = 1000, HEIGHT = WIDTH / 12 * 9;
private Thread thread;
private boolean running = false;
//private Random r;
private Handler handler;
public Game(){
handler = new Handler();
this.addKeyListener(new KeyInput(handler));
new Window(WIDTH, HEIGHT, "Game", this);
final int[][] map = DSAlgorithm.makeHeightMap(10, 45, 200);
//r = new Random();
handler.addObject(new Player(WIDTH/2 - 32, HEIGHT/2 - 32, ID.Player));
//handler.addObject(new World(0, 0, ID.World));
int squareSize = 10;
for(int y = 0; y < map.length; y+=squareSize){
for(int x = 0; x < map.length; x+=squareSize){
int value = map[x][y];
handler.addObject(new TerrianTile(x, y, value));
}
}
}
public synchronized void start(){
thread = new Thread(this);
thread.start();
running = true;
}
public synchronized void stop(){
try {
thread.join();
running = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void run(){
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int frames = 0;
while (running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
delta --;
}
if (running)
render();
frames++;
if (System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: " + frames);
frames = 0;
}
}
stop();
}
private void tick(){
handler.tick();
}
private void render(){
BufferStrategy bs = this.getBufferStrategy();
if (bs == null){
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
handler.render(g);
g.dispose();
bs.show();
}
public static void main(String args[]){
new Game();
}
public static int randInt(int min, int max){
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
Window.java
package com.game.main;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Window extends Canvas {
private static final long serialVersionUID = -1478604005915452565L;
public Window(int width, int height, String title, Game game) {
JFrame frame = new JFrame(title);
frame.setPreferredSize(new Dimension(width, height));
frame.setMaximumSize(new Dimension(width, height));
frame.setMinimumSize(new Dimension(width, height));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(game);
frame.setVisible(true);
game.start();
}
}
DSAlgorithm.java
package com.game.main;
public class DSAlgorithm {
/**
* This method uses the seed value to initialize the four corners of the
* map. The variation creates randomness in the map. The size of the array
* is determined by the amount of iterations (i.e. 1 iteration -> 3x3 array,
* 2 iterations -> 5x5 array, etc.).
*
* #param iterations
* the amount of iterations to do (minimum of 1)
* #param seed
* the starting value
* #param variation
* the amount of randomness in the height map (minimum of 0)
* #return a height map in the form of a 2-dimensional array containing
* integer values or null if the arguments are out of range
*/
public static int[][] makeHeightMap(int iterations, int seed, int variation) {
if (iterations < 1 || variation < 0) {
return null;
}
int size = (1 << iterations) + 1;
int[][] map = new int[size][size];
final int maxIndex = map.length - 1;
// seed the corners
map[0][0] = seed;
map[0][maxIndex] = seed;
map[maxIndex][0] = seed;
map[maxIndex][maxIndex] = seed;
for (int i = 1; i <= iterations; i++) {
int minCoordinate = maxIndex >> i;// Minimum coordinate of the
// current map spaces
size = minCoordinate << 1;// Area surrounding the current place in
// the map
diamondStep(minCoordinate, size, map, variation);
squareStepEven(minCoordinate, map, size, maxIndex, variation);
squareStepOdd(map, size, minCoordinate, maxIndex, variation);
variation = variation >> 1;// Divide variation by 2
}
return map;
}
/**
* Calculates average values of four corner values taken from the smallest
* possible square.
*
* #param minCoordinate
* the x and y coordinate of the first square center
* #param size
* width and height of the squares
* #param map
* the height map to fill
* #param variation
* the randomness in the height map
*/
private static void diamondStep(int minCoordinate, int size, int[][] map,
int variation) {
for (int x = minCoordinate; x < (map.length - minCoordinate); x += size) {
for (int y = minCoordinate; y < (map.length - minCoordinate); y += size) {
int left = x - minCoordinate;
int right = x + minCoordinate;
int up = y - minCoordinate;
int down = y + minCoordinate;
// the four corner values
int val1 = map[left][up]; // upper left
int val2 = map[left][down]; // lower left
int val3 = map[right][up]; // upper right
int val4 = map[right][down];// lower right
calculateAndInsertAverage(val1, val2, val3, val4, variation,
map, x, y);
}
}
}
/**
* Calculates average values of four corner values taken from the smallest
* possible diamond. This method calculates the values for the even rows,
* starting with row 0.
*
* #param minCoordinate
* the x-coordinate of the first diamond center
* #param map
* the height map to fill
* #param size
* the length of the diagonals of the diamonds
* #param maxIndex
* the maximum index in the array
* #param variation
* the randomness in the height map
*/
private static void squareStepEven(int minCoordinate, int[][] map,
int size, int maxIndex, int variation) {
for (int x = minCoordinate; x < map.length; x += size) {
for (int y = 0; y < map.length; y += size) {
if (y == maxIndex) {
map[x][y] = map[x][0];
continue;
}
int left = x - minCoordinate;
int right = x + minCoordinate;
int down = y + minCoordinate;
int up = 0;
if (y == 0) {
up = maxIndex - minCoordinate;
} else {
up = y - minCoordinate;
}
// the four corner values
int val1 = map[left][y]; // left
int val2 = map[x][up]; // up
int val3 = map[right][y];// right
int val4 = map[x][down]; // down
calculateAndInsertAverage(val1, val2, val3, val4, variation,
map, x, y);
}
}
}
/**
* Calculates average values of four corner values taken from the smallest
* possible diamond. This method calculates the values for the odd rows,
* starting with row 1.
*
* #param minCoordinate
* the x-coordinate of the first diamond center
* #param map
* the height map to fill
* #param size
* the length of the diagonals of the diamonds
* #param maxIndex
* the maximum index in the array
* #param variation
* the randomness in the height map
*/
private static void squareStepOdd(int[][] map, int size, int minCoordinate,
int maxIndex, int variation) {
for (int x = 0; x < map.length; x += size) {
for (int y = minCoordinate; y < map.length; y += size) {
if (x == maxIndex) {
map[x][y] = map[0][y];
continue;
}
int left = 0;
int right = x + minCoordinate;
int down = y + minCoordinate;
int up = y - minCoordinate;
if (x == 0) {
left = maxIndex - minCoordinate;
} else {
left = x - minCoordinate;
}
// the four corner values
int val1 = map[left][y]; // left
int val2 = map[x][up]; // up
int val3 = map[right][y];// right
int val4 = map[x][down]; // down
calculateAndInsertAverage(val1, val2, val3, val4, variation,
map, x, y);
}
}
}
/**
* Calculates an average value, adds a variable amount to that value and
* inserts it into the height map.
*
* #param val1
* first of the values used to calculate the average
* #param val2
* second of the values used to calculate the average
* #param val3
* third of the values used to calculate the average
* #param val4
* fourth of the values used to calculate the average
* #param variation
* adds variation to the average value
* #param map
* the height map to fill
* #param x
* the x-coordinate of the place to fill
* #param y
* the y-coordinate of the place to fill
*/
private static void calculateAndInsertAverage(int val1, int val2, int val3,
int val4, int variation, int[][] map, int x, int y) {
int avg = (val1 + val2 + val3 + val4) >> 2;// average
int var = (int) ((Math.random() * ((variation << 1) + 1)) - variation);
map[x][y] = avg + var;
}
public static void main(String[] args) {
}
}
Handler.java
package com.game.main;
import java.awt.Graphics;
import java.util.LinkedList;
public class Handler {
LinkedList<GameObject> object = new LinkedList<GameObject>();
LinkedList<Tiles> tile = new LinkedList<Tiles>();
public void tick(){
for (int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.tick();
}
for (int t = 0; t < tile.size(); t++){
Tiles tempObject = tile.get(t);
tempObject.tick();
}
}
public void render(Graphics g){
for (int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.render(g);
}
for (int t = 0; t < tile.size(); t++){
Tiles tempObject = tile.get(t);
tempObject.render(g);
}
}
public void addObject(GameObject object){
this.object.add(object);
}
public void removeObject(GameObject object){
this.object.remove(object);
}
public void addObject(Tiles tile){
this.tile.add(tile);
}
public void removeObject(Tiles tile){
this.tile.remove(tile);
}
}
Tiles.java
package com.game.main;
import java.awt.Graphics;
import java.util.LinkedList;
public class Handler {
LinkedList<GameObject> object = new LinkedList<GameObject>();
LinkedList<Tiles> tile = new LinkedList<Tiles>();
public void tick(){
for (int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.tick();
}
for (int t = 0; t < tile.size(); t++){
Tiles tempObject = tile.get(t);
tempObject.tick();
}
}
public void render(Graphics g){
for (int i = 0; i < object.size(); i++){
GameObject tempObject = object.get(i);
tempObject.render(g);
}
for (int t = 0; t < tile.size(); t++){
Tiles tempObject = tile.get(t);
tempObject.render(g);
}
}
public void addObject(GameObject object){
this.object.add(object);
}
public void removeObject(GameObject object){
this.object.remove(object);
}
public void addObject(Tiles tile){
this.tile.add(tile);
}
public void removeObject(Tiles tile){
this.tile.remove(tile);
}
}
TerrianTile.java
package com.game.main;
import java.awt.Color;
import java.awt.Graphics;
public class TerrianTile extends Tiles {
public TerrianTile(int x, int y, int tileType) {
super(x, y, tileType);
}
public void tick(){
}
public void render(Graphics g){
if (tileType <= 0){
g.setColor(Color.BLUE);
g.fillRect(x, y, 10, 10);
}
//water
if (tileType > 0 && tileType < 40){
g.setColor(Color.BLUE);
g.fillRect(x, y, 10, 10);
}
//sand
if (tileType >= 40 && tileType < 55){
g.setColor(Color.YELLOW);
g.fillRect(x, y, 10, 10);
}
//grass
if (tileType >= 55 && tileType < 120){
g.setColor(Color.GREEN);
g.fillRect(x, y, 10, 10);
}
//forest
if (tileType >= 120 && tileType < 140){
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x, y, 10, 10);
}
//stone
if (tileType >= 140 && tileType < 170){
g.setColor(Color.GRAY);
g.fillRect(x, y, 10, 10);
}
//snow
if (tileType >= 170){
g.setColor(Color.WHITE);
g.fillRect(x, y, 10, 10);
}
}
}
KeyInput.java
package com.game.main;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyInput extends KeyAdapter{
private Handler handler;
public KeyInput(Handler handler){
this.handler = handler;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
for (int i = 0; i < handler.object.size(); i++){
GameObject tempObject = handler.object.get(i);
if (tempObject.getId() == ID.Player){
// key events for player 1
if (key == KeyEvent.VK_W) tempObject.setVelY(-5);
if (key == KeyEvent.VK_S) tempObject.setVelY(5);
if (key == KeyEvent.VK_D) tempObject.setVelX(5);
if (key == KeyEvent.VK_A) tempObject.setVelX(-5);
}
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
for (int i = 0; i < handler.object.size(); i++){
GameObject tempObject = handler.object.get(i);
if (tempObject.getId() == ID.Player){
// key events for player 1
if (key == KeyEvent.VK_W) tempObject.setVelY(0);
if (key == KeyEvent.VK_S) tempObject.setVelY(0);
if (key == KeyEvent.VK_D) tempObject.setVelX(0);
if (key == KeyEvent.VK_A) tempObject.setVelX(0);
}
}
}
}
Not sure if there is way to container the tiles in a rectangle and then move the rectangle. Any help would be much appreciated.
I dont really know what you mean by moving the tiles in a rectangle but if you just simply want to move all of them in a certain direction you could use g.translate(dx, dY) before you draw them.
Or if the terrain doesnt change you could draw them on an image at the beginning and then draw the image each frame at diffrent positions.

Parabolas within bounds

I have a JPanel 200x200.
I trying to create a function that will generate random parabola's with the bounds of the JPanel, with a constraint that the height can't be lower than a 100 (middle of the screen), I basically want to move a shape around these parabolas
Here is some code I'm using to get started:
Random random = new Random(); int y; int x;
int size = random.nextInt(10);
int translation = random.nextInt(50);
int height = random.nextInt(100) - 200; //between 100 and 200
//Parabola functions : y = ((x/7 - 30))^2
// x and y are coordiates of where the shape is drawn
while(y != 200){
y = (float)Math.pow((float)xloc / size - translation ,2) + height;
x++;
}
I've been researching about FlatteningPathIterator but not too sure how to use them. my function
y = (float)Math.pow((float)xloc / size - translation ,2) + height;`
prints parabola's sometimes outside the bounds, how would i edit it to print parabola's inside the bounds?
There is a Java Swing shape generator for this called Quad2dCurve. The getPathIterator call gives you an enumerator for points on the curve.
Here is some example code:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Random;
import javax.swing.*;
final class TestCanvas extends JComponent {
int size = 200;
int n = 10;
float[] ph = new float[n];
float[] pw = new float[n];
float[] px = new float[n];
Random gen = new Random();
TestCanvas() {
makeRandomParabolas();
setFocusable(true);
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
makeRandomParabolas();
repaint();
float [] coords = new float [6];
for (int i = 0; i < n; i++) {
PathIterator pi = getQuadCurve(i).getPathIterator(null, 0.1);
System.out.print(i + ":");
while (!pi.isDone()) {
switch (pi.currentSegment(coords)) {
case PathIterator.SEG_MOVETO:
System.out.print(" move to");
break;
case PathIterator.SEG_LINETO:
System.out.print(" line to");
break;
default:
System.out.print(" unexpected");
break;
}
System.out.println(" (" + coords[0] + "," + coords[1]+")");
pi.next();
}
System.out.println();
}
}
});
}
QuadCurve2D.Float getQuadCurve(int i) {
return new QuadCurve2D.Float(px[i] - pw[i], size,
px[i], size - (2 * ph[i]),
px[i] + pw[i], size);
}
void makeRandomParabolas() {
for (int i = 0; i < n; i++) {
float x = 0.2f + 0.6f * gen.nextFloat();
px[i] = size * x;
pw[i] = size * (Math.min(x, 1 - x) * gen.nextFloat());
ph[i] = size * (0.5f + 0.5f * gen.nextFloat());
}
}
#Override
protected void paintComponent(Graphics g0) {
Graphics2D g = (Graphics2D) g0;
for (int i = 0; i < n; i++) {
g.draw(getQuadCurve(i));
}
}
}
public class Main extends JFrame {
public Main() {
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new TestCanvas());
getContentPane().setPreferredSize(new Dimension(200, 200));
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main().setVisible(true);
}
});
}
}

If statement confusion

Below is my code. I am trying to make the center sphere rotate part of the way around its orbit, then when it hits the point on its orbit (-orbitRadius, 0) it simply moves off to the left. I used an if statement, but it does not work properly. The issue is that I need to somehow make the code such that once the if statement is invoked, the coordinates are calculated using the version in the if loop and not the original formulas. It only does this for one frame as is. Can anyone help?
import java.util.*;
import java.awt.*;
public class Spiral
{
public static void main(String[] args)
{
int rcircle = 200;
int radius = 0;
escape(rcircle, radius);
}
public static void escape (int rcircle, int radius)
{
StdDraw.setCanvasSize(600, 400);
StdDraw.setXscale(0, 600);
StdDraw.setYscale(0, 400);
double xprof;
double yprof;
long T0 = System.currentTimeMillis();
final int FRAME_TIME = 50;
for (int t = 0; t<= 1000; t++) { // note: Prof. Yang starts in his optimal position
double x = (Math.cos(Math.toRadians(0+(3)*4)*t)*rcircle/12 + 300);
double y = (Math.sin(Math.toRadians(0+(3)*4)*t)*rcircle/12 + 200);
if (y == 0) {
x = (300 - rcircle/12) - 12*t;
y = 0;
}
StdDraw.circle(x, y, 10);
xprof = (Math.cos(Math.toRadians(0+4*t))*rcircle + 300);
yprof = (Math.sin(Math.toRadians(0+4*t))*rcircle + 200);
StdDraw.filledCircle(xprof, yprof, 10);
StdDraw.show(FRAME_TIME);
StdDraw.clear();
}
}
}
You have a number of problems:
There is an offset of 200 added to y so y will never be zero
There will most likely be some rounding error so checking to 200 is not much better. Try something like:
if (Math.abs(y-200) < 0.0001)
Your code will not make the sphere continue going left, as y will be recalculated next time round the loop. Once the
The sphere starts at (orbitRadius, 200) so if you fix point 3, the sphere will just move to the left (as y == 200)
Here is a solution with 1-3 fixed:
import java.util.*;
import java.awt.*;
public class Spiral
{
public static void main(String[] args)
{
int rcircle = 200;
int radius = 0;
escape(rcircle, radius);
}
public static void escape (int rcircle, int radius)
{
StdDraw.setCanvasSize(600, 400);
StdDraw.setXscale(0, 600);
StdDraw.setYscale(0, 400);
double xprof;
double yprof;
long T0 = System.currentTimeMillis();
final int FRAME_TIME = 50;
double y = 0;
for (int t = 0; t<= 1000; t++) { // note: Prof. Yang starts in his optimal position
double x = (Math.cos(Math.toRadians(0+(3)*4)*t)*rcircle/12 + 300);
if (Math.abs(y-200) < 0.0001) {
x = (300 - rcircle/12) - 12*t;
y = 200;
} else {
y = (Math.sin(Math.toRadians(0+(3)*4)*t)*rcircle/12 + 200);
}
StdDraw.circle(x, y, 10);
xprof = (Math.cos(Math.toRadians(0+4*t))*rcircle + 300);
yprof = (Math.sin(Math.toRadians(0+4*t))*rcircle + 200);
StdDraw.filledCircle(xprof, yprof, 10);
StdDraw.show(FRAME_TIME);
StdDraw.clear();
}
}
}

Cant find any possible errors but Java says different

I've got a problem, I'm programming in Java and when I went to run it, It came up with a list of about 6 errors. These
Exception in thread "Display" java.lang.ArrayIndexOutOfBoundsException: 64
at com.cmnatic.mld.graphics.Screen.clear(Screen.java:27)
at com.cmnatic.mld.Game.render(Game.java:107)
at com.cmnatic.mld.Game.run(Game.java:77)
at java.lang.Thread.run(Unknown Source)
If it helps, here is my code (ofc it does)
Game.java:
package com.cmnatic.mld;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import com.cmnatic.mld.graphics.Screen;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static int width = 300; // 300 * 3 = 900
public static int height = width / 16 * 9; //168.75 * 3 = 506.25
public static int scale = 3;
public static String title = "CMNatic's MLD Entry #49";
private Thread thread;
private JFrame frame;
private boolean running = false;
private Screen screen;
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
private int[] pixels =((DataBufferInt)image.getRaster().getDataBuffer()).getData();
public Game() {
Dimension size = new Dimension(width * scale, height * scale);
setPrefferedSize(size);
screen = new Screen(width, height);
frame = new JFrame();
this.setSize(900,506);
}
private void setPrefferedSize(Dimension size) {
}
public synchronized void start() {
running = true;
thread = new Thread(this , "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
final double ns = 100000000.0 / 60.0; // nano-seconds = 1000000000 (9 0'S) / 60.0
double delta = 0;
int frames = 0;
int updates = 0;
while (running) {
long now = System.nanoTime();
delta += (now-lastTime) / ns; //nano-seconds (ns)
lastTime = now;
while (delta >= 1) {
update();
updates++;
delta--;
}
render();
frames++;
if (System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println(updates + " ups, " + frames + " fps");
frame.setTitle(title + " | " + updates + "ups, " + frames);
updates = 0;
frames = 0;
}
}
stop();
}
int x = 0, y = 0;
public void update() {
y++;
if (y % 10 == 0) x++;
x++;
//y++;
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Screen.Java
package com.cmnatic.mld.graphics;
import java.util.Random;
public class Screen {
private int width, height;
public int[] pixels;
public final int MAP_SIZE = 8;
public final int MAP_SIZE_MASK = MAP_SIZE - 1;
public int[] tiles = new int[MAP_SIZE * MAP_SIZE];
private Random random = new Random();
public Screen(int width, int height) {
this.width = width;
this.height = height;
pixels = new int[width * height]; // 50,400
for (int i = 0; i < MAP_SIZE * MAP_SIZE; i++) {
tiles[i] = random.nextInt(0xffffff);
}
}
public void clear() {
for (int i = 0; i < pixels.length; i++) {
tiles[i] = random.nextInt(0xffffff);
tiles[0] = 0;
}
}
public void render(int xOffset, int yOffset) {
for (int y = 0; y < height; y++) {
int yy = y + yOffset;
//if (yy < 0 || y >= height) break;
for (int x = 0; x < width; x++) {
int xx = x + xOffset;
//if (xx < 0 || x >= width) break;
int tileIndex = ((xx >> 4) + xOffset& MAP_SIZE_MASK) + ((yy >> 4)& MAP_SIZE_MASK) * MAP_SIZE;
pixels[x + y * width] = tiles[tileIndex];
}
}
}
}
If anyone could help, I would be forever grateful!
In Screen.clear() you have:
for (int i = 0; i < pixels.length; i++) {
tiles[i] = random.nextInt(0xffffff);
tiles[0] = 0;
}
But based on your comments, pixels is clearly larger than tiles. You probably meant tiles.length in that for loop (I'm presuming clear is supposed to be doing the same thing you are doing in that loop at the end of the Screen constructor).
In general, when you see an ArrayIndexOutOfBoundsException, it precisely means that an array index is out of bounds. When you run into that, look carefully at your code and try to find any opportunities for that to happen. In this case, the use of a different array's length in the index loop is a big red flag.
Also, incidentally, the tiles[0] = 0 in that loop looks like it isn't supposed to be there.
Your problem is that you're using pixels and tiles interchangeably in your clear method. The logical "board" size is 8x8, but your pixels array is sized based on the passed-in parameters. You then try to iterate over the 50k or so pixels in the 8x8 board and promptly run off the end.
Additionally, both of those arrays are very obviously representing two-dimensional concepts (a board and a screen), and it makes your code much clearer to use a two-dimensional array:
int pixels[][] = new int[width][height];

Categories