We were giving a this program in class and asked to try it our at home but it doesn't work, I'm guessing there is something wrong with the algorithm. Can someone help me out?
import java.awt.Graphics;
import javax.swing.JApplet;
public class rotationalTransformation extends JApplet {
int[] x=new int[3];
int[] y=new int[3];
int[][] tMatrix=new int[3][3];
int no_pts=3;
public void start()
{
x[0]= 10;
x[1]= 20;
x[2]= 30 ;
y[0]= 10;
y[1]= 30;
y[2]= 10 ;
}
public void paint(Graphics g)
{
try {
System.out.println("Before Rotation");
g.drawPolygon(x, y, no_pts);
matrixIdentity(tMatrix);
System.out.println("Identity Matrix Created");
rotation(60,10,10);
System.out.println("Rotating");
for(int a=0; a<3;a++)
{
for(int c=0; c<3;c++)
{
System.out.print(tMatrix[a][c] + " ");
}
System.out.println();
}
for(int a=0; a<3;a++)
{
System.out.println(x[a] + " " + y[a]);
}
transformPoints();
System.out.println("After Rotation");
g.drawPolygon(x, y, no_pts);
}
catch(Exception e){}
}
void matrixIdentity(int[][] m)
{int i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{ if(i==j)
{
m[i][j]=1;
}
else
m[i][j]=0;
}
}
void transformPoints()
{
int tmp;
for(int a=0; a<3;a++)
{
tmp=tMatrix[0][0]*x[a]+ tMatrix[0][1]*y[a]+tMatrix[0][2];
y[a]=tMatrix[1][0]*x[a]+tMatrix[1][1]*y[a]+tMatrix[1][2];
x[a]=tmp;
}
}
void rotation(double degree,int rx,int ry)
{ int a;
a = (int) (degree * 3.14/180);
tMatrix[0][0]= (int) Math.cos(a) ;
tMatrix[0][1]= (int) -Math.sin(a) ;
tMatrix[0][2]= (int) (rx*(1-Math.cos(a))+ ry*Math.sin(a));
tMatrix[1][0]= (int) Math.sin(a) ;
tMatrix[1][1]= (int) Math.cos(a);
tMatrix[1][2]= (int) (ry*(1-Math.cos(a))-rx*Math.sin(a));
}
}
It prints the original shape but does not print the rotated shape.
I think you should put one more line to be able to see the rotation.
transformPoints();
System.out.println("After Rotation");
g.drawPolygon(x, y, no_pts);
//this line will repaint with new position
this.repaint();
}
Hope this helps.
Related
I'm trying to build a Snake Game, where the snake is eating square orbs.
Before, the program was running perfectly, but when I ran it a couple of days ago, it yelled at me for something about a NullPointerException. I tried looking for what caused it, and it was in my Snake class.
Here is the code for the main class:
Snake s;
Score score;
//Menu m;
int sc1 = 20;
PVector food;
void setup() {
size(700, 700);
//m = new menu;
//m.show();
s = new Snake();
score = new Score();
//m.startGame();
frameRate(10);
}
void pickLocation() {
int cols = width/sc1;
int rows = height/sc1;
food = new PVector(floor(random(cols-20)), floor(random(rows-20)));
food.mult(sc1);
}
void draw() {
background(51);
if (s.eat(food)) {
pickLocation();
score.addPoints(10);
}
pickLocation();
score.show();
s.update();
s.show();
s.death();
if (s.dead == true) {
score.highScores();
}
if (score.totalScore != s.i/10) {
score.totalScore = s.i * 10;
}
if (s.dead && score.totalScore < score.highScore) {
score.totalScore = 0;
}
fill(255, 0, 100);
rect(food.x, food.y, sc1, sc1);
}
void keyPressed() {
if (keyCode == UP) {
s.dir(0, -1);
} else if (keyCode == DOWN) {
s.dir(0, 1);
} else if (keyCode == RIGHT) {
s.dir(1, 0);
} else if (keyCode == LEFT) {
s.dir(-1, 0);
}
}
The menu I commented out right now.
The Score class:
class Score {
int totalScore = 0; //will add the total score to the
int highScore; //will hold the user's high score in it.
int tempScore; //will hold the user's score after the snake dies.
Score() {
}
//this method is used when the snake eats the
//food. Eating the food will give 10 points to it.
void addPoints(int x) {
totalScore = totalScore + x;
}
//this method will calculate to see if the user
//has a new high score, only if the snake has
//officially died.
void highScores() {
if (totalScore > highScore) {
text("new highscore!", height/2, width/2);
highScore = totalScore;
totalScore = 0;
}
}
void show() {
text("Score: " + totalScore, 20, 20);
text("High Score: " + highScore, 20, 40);
}
}
And finally, my Snake class, where the problem is located at:
class Snake {
float x, y;
float xSpeed = 1;
float ySpeed = 0;
int total = 0;
ArrayList<PVector> tail = new ArrayList<PVector>();
boolean dead = false;
int i = 0;
Snake() {
}
boolean eat (PVector pos) {
float d = dist(x, y, pos.x, pos.y);
if (d < 1) {
total++;
return true;
} else {
return false;
}
}
void dir(float x, float y) {
xSpeed = x;
ySpeed = y;
}
void death() {
for (i = 0; i < tail.size(); i++) {
PVector pos = tail.get(i);
float d = dist(x, y, pos.x, pos.y);
if (d < 1) {
println("starting over");
total = 0;
tail.clear();
dead = true;
} else {
dead = false;
}
}
}
void update() {
if (total > 0) {
if (total == tail.size() && !tail.isEmpty()) {
tail.remove(0);
}
tail.add(new PVector(x, y));
}
x = x + xSpeed * sc1;
y = y + ySpeed * sc1;
x = constrain(x, 0, width-sc1);
y = constrain(y, 0, height-sc1);
}
void show() {
fill(0, 255, 0);
for (PVector v : tail) {
rect(v.x, v.y, sc1, sc1);
}
rect(x, y, sc1, sc1);
//rect(x, y, w, h);
}
}
My question is, is there something who can recognize the error and what should I do to fix such an error, please.
You need to get into the habit of debugging your code to understand exactly what's going on. You know that this line is throwing the NPE:
float d = dist(x, y, pos.x, pos.y);
So next, you need to understand the values of every variable on that line. You could just print them out:
boolean eat (PVector pos) {
println("x: " + x);
println("y: " + y);
println("pos: " + pos);
float d = dist(x, y, pos.x, pos.y);
If you do this, you'll see this output:
x: 0.0
y: 0.0
pos: null
This tells you that your pos variable is null, which is what's causing your NullPointerException.
Now you can trace backwards through your code to understand why the eat() function is being given a null argument.
In the future, please narrow your problem down to a MCVE instead of posting your whole program.
I'm attempting to use these methods to find a color in a rectangular area on the screen. However there are sometimes millions of pixels on a screen, and I'm only achieving about 35 iterations of getColor a second at the moment. There must be something in my code causing this to run extremely slowly.
How can I scan my screen quicker than this? Ideally I'd like to scan the entire screen for a color in less than a second, not 8 hours as it stands now :P
Here are my two methods.
public static int getColor(int x, int y){
try{
return(robot.getPixelColor(x, y).getRGB() * -1);
}catch(Exception e){
System.out.println("getColor ERROR");
return 0;
}
}
//returns first instance of color,
//Begins top left, works way down to bottom right
public static Point findColor(Box searchArea, int color){
System.out.println("Test");
if(searchArea.x1 > searchArea.x2){
int temp = searchArea.x1;
searchArea.x1 = searchArea.x2;
searchArea.x2 = temp;
}
if(searchArea.y1 > searchArea.y2){
int temp = searchArea.y1;
searchArea.y1 = searchArea.y2;
searchArea.y2 = temp;
}
for(int i = searchArea.x1;i <=searchArea.x2; i++){
for(int j = searchArea.y1;j<=searchArea.y2;j++){
if(getColor(i, j) == color){
return new Point(i, j);
}
System.out.println(i + " " + j);
}
}
return new Point(-1, -1);
}
Robot#getColor will be very slow, especially when used in this manner.
A better solution would be to grab a screen shot (even in small chunks) and process the resulting BufferedImage.
Using the following example I got...
Took 0 seconds to scan image
Took 3 seconds to scan screen
For an area of 10x10
Example code...
import java.awt.AWTException;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TestColorGrab {
private static Robot robot;
public static void main(String[] args) {
try {
robot = new Robot();
} catch (AWTException ex) {
Logger.getLogger(TestColorGrab.class.getName()).log(Level.SEVERE, null, ex);
}
new TestColorGrab();
}
public TestColorGrab() {
Rectangle bounds = new Rectangle(0, 0, 10, 10);
long start = System.currentTimeMillis();
scanImageArea(bounds);
System.out.println("Took " + ((System.currentTimeMillis() - start) / 1000), TimeUnit.SECONDS) + " seconds to scan image");
start = System.currentTimeMillis();
scanRobotArea(bounds);
System.out.println("Took " + ((System.currentTimeMillis() - start) / 1000) + " seconds to scan screen");
}
public static int getColor(int x, int y) {
try {
return (robot.getPixelColor(x, y).getRGB() * -1);
} catch (Exception e) {
System.out.println("getColor ERROR");
return 0;
}
}
public static void scanRobotArea(Rectangle searchArea) {
for (int i = searchArea.x; i < searchArea.x + searchArea.width; i++) {
for (int j = searchArea.y; j < searchArea.y + searchArea.height; j++) {
getColor(i, j);
}
}
}
public static void scanImageArea(Rectangle searchArea) {
BufferedImage image = robot.createScreenCapture(searchArea);
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
image.getRGB(x, y);
}
}
}
}
Take out the print. You are writing to the console a million times.
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);
}
});
}
}
I'm trying to draw a circle with the help of Java but I'm stuck
This is what I've done so far,
public class Circle {
public static void DrawMeACircle(int posX, int posY, int radius) {
int a = 10;
int b = 10;
int x = posX - a; //x = position of x away from the center
int y = posY - b;
int xSquared = (x - a)*(x - a);
int ySquared = (y - b)*(y - b);
for (int i = 0;i <=20; i++) {
for (int j = 1;j <=20; j++) {
if (Math.abs(xSquared) + (ySquared) >= radius*radius && Math.abs(xSquared) + (ySquared) <= radius*radius) {
System.out.println("#");
} else {
System.out.println(" ");
}
}
}
}
public static void main(String[] args){
DrawMeACircle(5,5,5);
}
}
As you can see, this doesn't work out properly. Does anyone know how this can be solved?
I'm thankful for any help possible, Michael.
First of all, your inner if condition does not depend from i and j, so is a constant. That means the same symbol is printed every time, a space symbol.
Next, you're using System.out.println(" "); every time, adding a newline to each symbol. So, result looks like a column of spaces.
Last, but not least: drawing area is limited by 20x20 "pixels" and unable to fit large circles.
You can fix all these points together with something like
public class Circle {
public static void DrawMeACircle(int posX, int posY, int radius) {
for (int i = 0;i <= posX + radius; i++) {
for (int j = 1;j <=posY + radius; j++) {
int xSquared = (i - posX)*(i - posX);
int ySquared = (j - posY)*(j - posY);
if (Math.abs(xSquared + ySquared - radius * radius) < radius) {
System.out.print("#");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args){
DrawMeACircle(5,15,5);
}
}
which gives us somewhat similar to the circle.
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();
}
}