I'm doing a project that does the following in a nutshell:
reads integers from a file
stores them in an array
creates a bargraph of the numbers with an average line
the numbers above average go up, the numbers below go down (both are also different colors)
It compiles correctly, the JFrame window pops up, but no data is printed out. It's just an empty window.
Here is my code:
package basicgraphicstester;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class BasicGraphicsTester extends JFrame {
private Image fImageBuffer;
private Insets fInsets;
private Graphics g;
private static final int WIDTH = 800, HEIGHT = 600;
private static final Color OVER_AVERAGE = Color.blue,
UNDER_AVERAGE = Color.red;
int[] data;
public BasicGraphicsTester() throws FileNotFoundException
{ ReadInputData();
addWindowListener(new WindowCloser());
setVisible(true);
fInsets = getInsets();
setSize(WIDTH + fInsets.left + fInsets.right, HEIGHT + fInsets.top +fInsets.bottom);
setTitle("Bar Graph");
setResizable(false);
if (((fImageBuffer = createImage(WIDTH, HEIGHT)) != null) &&
((g = fImageBuffer.getGraphics()) != null)) Run();
else System.exit(1);
}
class WindowCloser extends WindowAdapter
{ public void WindowClosing(WindowEvent e )
{ System.exit(0); }
}
private void Run()
{ DrawAverageLine();
DrawBars();
}
private void DrawBars()
{
double arrayAverage = arrayAverage(data);
int average = averageLine(data);
int max = getMaxValue(data);
int min = getMinValue(data);
int barWidth = 57;
double barHeight;
for (int i = 0; i < data.length; i++) {
barHeight = (600 * (max - data[i]))/(max - min);
if (data[i] > average) {
g.setColor(OVER_AVERAGE);
g.fillRect((int)barWidth * i, (int)barHeight, (int)barWidth,
(average - (int)barHeight));
}
else if (barHeight == average) {
g.setColor(Color.green);
g.fillRect((int)barWidth * i, average, (int)barWidth, 0);
}
else {
g.setColor(UNDER_AVERAGE);
g.fillRect((int)barWidth * i, average, (int)barWidth,
((int)barHeight - average));
repaint();
}
} //for loop
} //DrawBar
private void DrawAverageLine()
{
int average = averageLine(data);
g.drawLine(0, average, 800, average);
}
public static int getMaxValue(int[] data) {
int maxValue = data[0];
for (int i=1;i < data.length;i++) {
if (data[i] > maxValue)
maxValue = data[i];
}
return maxValue;
}
public static int getMinValue(int[] data) {
int minValue = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i] < minValue)
minValue = data[i];
}
return minValue;
}
public static double arrayAverage(int[] data) {
double result = 0.0;
for (int i = 0; i < data.length; i++) {
result = result + data[i];
}
result = result/data.length;
return result;
}
public static int averageLine (int[] data) {
int max = getMaxValue(data);
int min = getMinValue(data);
return (HEIGHT * max - (int)arrayAverage(data)) / (max - min);
}
public void paint( Graphics g)
{ if (fImageBuffer != null )
g.drawImage(fImageBuffer, fInsets.left, fInsets.top, null);
}
public void ReadInputData() throws FileNotFoundException {
try {Scanner readFile = new Scanner(new File("BarChart.data"));
data = new int [13];
for (int i = 0; i < data.length; i++)
data[i] = readFile.nextInt();
} //try
catch (FileNotFoundException e) {
System.out.println(e);
}
} // ReadInputData
public static void main(String[] args) throws FileNotFoundException {
new BasicGraphicsTester();
}
}
Please help. Thanks in advance.
A JFrame is an empty frame. You need to put a JPanel inside your frame, and override the latter's paintComponent() method in order to render your data on screen.
This is not how you do graphics or drawing with Swing, and I'd be interested to see what tutorial you've read recommends you to get the Graphics object as you're doing. Instead you should draw in the paintComponent(...) method of a class that extends JComponent such as a JPanel, using the Graphics instance provided as a parameter by the JVM, and then add this component to your JFrame. You will want to read the painting in Swing tutorial which is part of the standard Swing tutorials.
If you want to draw right into the JFrame you still have to override ContentPane's paint, not JFrame's paint method AFAIK.
And yes, a better way would be to implement your own component (for example by extending JPanel) and place it inside the JFrame (remember it has to be placed in ContentPane).
Check JFrame javadocs about ContentPane.
I recently wrote something similar in JavaFX using the BarGraph component. I'll post the source code if it would be helpful, but maybe you need to use swing and the point of your project is to make your own bar graph.
View my javafx bar graph
Related
public class ChutesAndLadders2d {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] numbersOnBoard = new int [6][6];
boardSetUpA (numbersOnBoard);
printTwoD(numbersOnBoard);
}
public static void boardSetUpA (int[][]twoD) {
//Square with even size
//even rows
for (int row = 0;row<twoD.length; row ++) {
if (row %2 ==0) {
int num = twoD.length*(twoD.length-row);
for (int col = 0; col<twoD[row].length; col ++ ) {
twoD[row][col] = num;
num--;
}
}//
else {
int num = twoD.length*(twoD.length-(row + 1))+ 1;
for (int col = 0; col<twoD[row].length; col ++ ) {
twoD[row][col] = num;
num++;
}
}
}//for row
}//
public static void printTwoD(int [][] array){
for (int row = 0; row < array.length; row++){
for (int column = 0; column < array[row].length; column++){
System.out.print(array[row][column] + "\t");
}
System.out.println();
}
}
public static void boardDetails(String[][]board) {
for (int row = 0;row<board.length; row++){
for (int col = 0;col<board[row].length; col++){
if( col+2 == row||col+1 == row*2 ){
board[row][col] = "Lad"; // Append value
}
else if (col*2 == row|| row*2 == col){
board[row][col] = "Cht";// Append value
}
else {
board[row][col] = " ";
}
}
board[board.length-1][0] = "Start";
if (board.length%2 ==0) {
board[0][0] = "End";}
else {
board[0][board.length-1]="End";
}
}
}
public static void printBoard (int[][]twoD, String[][]strTwoD) {
//Printing
for (int row = 0;row<twoD.length;row++) {
for (int col = 0;col<twoD[row].length;col++) {
System.out.print(twoD[row][col] + " "+strTwoD[row][col]+"\t\t");
}
System.out.println("\n");
}
}
}
This is the starter code I have for setting up the snakes and ladders game. I also tried to set the chutes/snakes and ladders on the board but it is not printing. How should I fix it and how do I develop this code to have three methods: update the moves of a player once he reaches a snake, a ladder, and once he rolls his die, from one place to another?
Is it possible to implement a Shutes & Ladders game using a 2D Array? For sure! Does that make sense in an object-oriented language such as Java? I dont know ....
What do you need for that?
A square board with e.g. 36 playing fields.
Connections between two playing fields. (shutes and ladders)
Pawns and a dice.
A renderer that outputs the playing field (as text or graphics).
A program that allows input and connects everything to a functioning game.
Here is an example that works with a List instead of an Array. That can certainly be changed if it is necessary for your purposes.
I hope this is of some help to you.
P.S .: After the start, the board is displayed with field numbers. Shutes are shown as red lines. Ladders as green lines. Keys 1-6 on the keyboard simulate rolling the dice..
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
public class ChutesAndLadders2d {
public static void main(String[] args) {
JFrame frame = new JFrame("Chutes and Ladders 2D");
Game game = new ChutesAndLadders2d().new Game();
game.setPreferredSize(new Dimension(400, 400));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(game);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#SuppressWarnings("serial")
class Game extends JPanel{
private final Font defaultFont = new Font("Arial", Font.PLAIN, 16);
private final BasicStroke stroke = new BasicStroke(4f);
private static final int SCALE = 64;
// board and pawns
private final Board board = new Board(6);
private final List<Pawn> pawns = new ArrayList<>();
public Game(){
setFocusable(true); // receive Keyboard-Events
addKeyListener(new KeyAdapter(){
#Override
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if(c >= '1' && c <= '6'){
int steps = Integer.parseInt(Character.toString(c));
Pawn pawn = pawns.get(0);
pawn.move(steps);
Field field = board.get(pawn.fieldIndex);
if(field.targetKind() != Kind.NONE){
pawn.move(field.getTarget().index - field.index);
}
repaint();
}
}
});
board.connect(5, 12); // Ladder 5 -> 12
board.connect(8, 4); // Shute 8 -> 4
board.connect(15, 32); // Ladder 15 -> 32
board.connect(35, 17); // Shute 35 -> 17
board.connect(23, 30); // Ladder 23 -> 30
pawns.add(new Pawn(Color.BLUE, board.size() - 1));
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
setFont(defaultFont);
for(Field field : board){
Point p = field.getLocation();
g2d.drawRect(p.x * SCALE, p.y * SCALE, SCALE, SCALE);
g2d.drawString(field.text, p.x * SCALE + 24, p.y * SCALE + 40);
}
for(Field field : board){
if(field.targetKind() != Kind.NONE){
g2d.setColor(field.targetKind() == Kind.LADDER ? Color.GREEN : Color.RED);
g2d.setStroke(stroke);
Point source = field.getLocation();
Point target = field.getTarget().getLocation();
g2d.drawLine(source.x * SCALE + 40, source.y * SCALE + 24, target.x * SCALE + 40, target.y * SCALE + 24);
}
}
for(Pawn pawn : pawns){
Point loc = board.get(pawn.fieldIndex).getLocation();
g2d.setColor(pawn.color);
g2d.fillOval(loc.x * SCALE + 32, loc.y * SCALE + 32, 16, 16);
}
}
}
class Board implements Iterable<Field>{
private final List<Field> fields = new ArrayList<>();
public Board(int size){
for(int index = 0; index < size * size; index++)
fields.add(new Field(index, size));
}
public Field get(int index){
return fields.get(index);
}
public void connect(int startFieldnumber, int targetFieldnumber){
get(startFieldnumber - 1).setTarget(get(targetFieldnumber - 1));
}
#Override
public Iterator<Field> iterator() {
return fields.iterator();
}
public int size(){
return fields.size();
}
}
class Field{
final int index;
final String text;
final int size;
private Field target;
public Field(int index, int size){
this.index = index;
this.size = size;
text = "" + (index + 1);
}
public void setTarget(Field target){
if(target == this) return;
this.target = target;
}
public Field getTarget(){
return target;
}
public Kind targetKind(){
if(target == null) return Kind.NONE;
return index < target.index ? Kind.LADDER : Kind.SHUTE;
}
public Point getLocation(){
int x = index % size;
int y = index / size;
if(y % 2 != 0) x = size - x - 1;
return new Point(x, size - y - 1);
}
}
class Pawn{
int fieldIndex = 0;
int maxIndex;
Color color;
public Pawn(Color color, int maxIndex){
this.color = color;
this.maxIndex = maxIndex;
}
public void move(int steps){
fieldIndex += steps;
if(fieldIndex < 0) fieldIndex = 0;
if(fieldIndex > maxIndex) fieldIndex = maxIndex;
}
}
enum Kind{
NONE, SHUTE, LADDER
}
}
//Generator class
public class Generator {
double jump;
double sizeModifier;
int iterationRate,range;
ComplexNumber c;
public Generator(double jump) {
this.jump=jump;
this.sizeModifier=40;
this.iterationRate=10;
this.range=100;
c=new ComplexNumber();
}
public void generateSet(){
DrawSet ds = new DrawSet();
int ticker=0;
for(double i=-2*range;i<=range;i+=jump){
for(double j=-2*range;j<=range;j+=jump){
c= new ComplexNumber((i/range),(j/range));
double fz=c.square().mod()+c.mod();
//System.out.println("c mod is: "+c.mod());
//System.out.println("fz is: "+fz);
if (fz < 2) {
for(int k=0;k<=iterationRate;k++) {
//System.out.println("nc:"+nc);
ticker++;
//System.out.println("ticker:"+ticker);
if(ticker==iterationRate) {
ds.addPoint(i + 450, j + 450);
}
if(fz>=2){
break;
}
else {
fz = Math.pow(fz, 2) + 1;
}
}
}
ticker=0;
}
}
}
//Drawset class
public class DrawSet extends JPanel {
private ArrayList<Point> Points;
private ArrayList<Point> nPoints;
GraphicWindow gw;
public DrawSet(){
this.Points=new ArrayList<>();
this.nPoints=new ArrayList<>();
gw = new GraphicWindow(1000,1000);
gw.add(this);
}
public void addPoint(double x,double y){
int ix=(int)x;
int iy=(int)y;
//int iwidth=(int)width*sizeModifier;
//int iheight=(int)height*sizeModifier;
Point a=new Point(ix,iy);
Points.add(a);
//System.out.println(Points.size());
}
public void paintComponent(Graphics g) {
int pointSize = 1;
super.paintComponents(g);
System.out.println(Points.size());
for (int i = 0; i < Points.size(); i++) {
g.setColor(Color.BLACK);
g.drawOval((int) Points.get(i).getX(), (int) Points.get(i).getY(), pointSize, pointSize);
}
}
The basic problem is that fz is never <2 after just 10 iterations, so no points are drawn. Why is this? What equation should I be implementing?
I am using a complex number to generate the value. The class which I use can be seen here:
https://github.com/abdulfatir/jcomplexnumber/
(or on the stack overflow forum Does Java have a class for complex numbers? by Mr Abdul Fatir)
Okay, observationally
Generator should not be creating a new instance of DrawSet
DrawSet should not be creating a new instance of GraphicWindow
These are the responsibilities of these classes or methods. This is highly coupling your code and generating side effects.
Instead, generate should pass back the points it creates and these should then be applied in what ever way you want, Generator shouldn't care.
Because I don't have access to your full code, I've just hacked together a random series of points instead to illustrate the point.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
DrawSet drawSet = new DrawSet();
Generator generator = new Generator(100);
drawSet.setPoints(generator.generateSet());
JFrame frame = new JFrame();
frame.add(drawSet);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawSet extends JPanel {
private ArrayList<Point> points;
private ArrayList<Point> nPoints;
public DrawSet() {
this.points = new ArrayList<>();
this.nPoints = new ArrayList<>();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public void setPoints(ArrayList<Point> points) {
this.points = points;
repaint();
}
// public void addPoint(double x, double y) {
// int ix = (int) x;
// int iy = (int) y;
// //int iwidth=(int)width*sizeModifier;
// //int iheight=(int)height*sizeModifier;
// Point a = new Point(ix, iy);
// Points.add(a);
// //System.out.println(Points.size());
// }
#Override
protected void paintComponent(Graphics g) {
int pointSize = 5;
super.paintComponents(g);
for (int i = 0; i < points.size(); i++) {
g.setColor(Color.BLACK);
g.drawOval((int) points.get(i).getX(), (int) points.get(i).getY(), pointSize, pointSize);
}
}
}
public class Generator {
double jump;
double sizeModifier;
int iterationRate, range;
//ComplexNumber c;
public Generator(double jump) {
this.jump = jump;
this.sizeModifier = 40;
this.iterationRate = 10;
this.range = 100;
//c = new ComplexNumber();
}
public ArrayList<Point> generateSet() {
Random rnd = new Random();
ArrayList<Point> points = new ArrayList<>(range);
for (int index = 0; index < range; index++) {
int x = (int)(490 * rnd.nextDouble());
int y = (int)(490 * rnd.nextDouble());
points.add(new Point(x, y));
}
return points;
// DrawSet ds = new DrawSet();
// int ticker = 0;
// for (double i = -2 * range; i <= range; i += jump) {
// for (double j = -2 * range; j <= range; j += jump) {
// c = new ComplexNumber((i / range), (j / range));
// double fz = c.square().mod() + c.mod();
// //System.out.println("c mod is: "+c.mod());
// //System.out.println("fz is: "+fz);
// if (fz < 2) {
// for (int k = 0; k <= iterationRate; k++) {
// //System.out.println("nc:"+nc);
// ticker++;
// //System.out.println("ticker:"+ticker);
// if (ticker == iterationRate) {
// ds.addPoint(i + 450, j + 450);
//
// }
// if (fz >= 2) {
// break;
// } else {
// fz = Math.pow(fz, 2) + 1;
// }
// }
// }
// ticker = 0;
// }
// }
}
}
}
I've also made the pointSize bigger, so you can actually see the results, although I'd consider filling the points.
If the Generator is takes a long time to perform its calculations, you might consider using a SwingWorker to perform the operation. This will allow to offload the operation to seperate thread and not block the main UI thread. You can then use the SwingWorker to either feed back each individual point as it's calculated or all the points when the whole generation is done, back to the main UI thread in a safe manner.
See Worker Threads and SwingWorker for more details
Why is this?
Swing is lazy. It won't make repaints or updates to the UI unless it thinks it needs to. So, if you change some state the UI is depending on, you need to nudge Swing to encourage it to make a new paint pass. In the simplest terms, this means calling repaint on the component which is has changed
I'm trying to create a program to visualize bubble sort. Ideally, after bubble sort swaps two numbers in an array, AWT would redraw rectangles on the canvas to show the array updating.
I originally tried having the sorting and drawing portions in different classes, but this caused issues with passing the array between classes and conversions between static and non-static methods.
import java.awt.Canvas;
import java.awt.Graphics;
import javax.swing.JFrame;
public class VisMain extends Canvas {
/**
*
*/
private static final long serialVersionUID = 1L;
private int[] array;
public static void bubble_srt(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (array[i] > array[k]) {
swapNumbers(i, k, array);
}
}
}
}
private static void swapNumbers(int i, int j, int[] column) {
int temp;
temp = column[i];
column[i] = column[j];
column[j] = temp;
VisMain set = new VisMain();
set.arraySetter(column);
}
public void arraySetter(int[] list) {
this.array = list;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("My Drawing");
Canvas canvas = new VisMain();
canvas.setSize(400, 400);
frame.add(canvas);
frame.pack();
frame.setVisible(true);
int [] input = { 4, 2, 5, 6, 33, 15, 34, 0, 1, 99 };
VisMain obj = new VisMain();
obj.arraySetter(input);
bubble_srt(input);
}
public void paint(Graphics g) {
for(int i = 0; i <= array.length; i++) {
g.drawRect((i + 1) * 60, 100 , 50, array[i]);
}
}
}
I expected the canvas to at least display something but I got a java.lang.NullpointerException in the for() loop in the paint() method.
This line of your code...
frame.setVisible(true);
causes your paint(Graphics g) method to be invoked which causes the NullPointerException since, at this stage, member array of class VisMain is still null (according to the code you posted).
Hence you need to assign a value to array before calling frame.setVisible(true).
The below code works for me, i.e. no NullPointerException using JDK 12.0.1 on Windows 10. It is basically the code you posted. The only part I changed was in method main() but for completeness I post all of the code you posted including my changes so you can copy/paste it.
package guitests;
import java.awt.Canvas;
import java.awt.Graphics;
import javax.swing.JFrame;
public class VisMain extends Canvas {
private static final long serialVersionUID = 1L;
private int[] array;
public static void bubble_srt(int array[]) {
int n = array.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (array[i] > array[k]) {
swapNumbers(i, k, array);
}
}
}
}
private static void swapNumbers(int i, int j, int[] column) {
int temp;
temp = column[i];
column[i] = column[j];
column[j] = temp;
VisMain set = new VisMain();
set.arraySetter(column);
}
public void arraySetter(int[] list) {
this.array = list;
repaint();
}
/* Only this method is changed from original code posted by DeusDeus. */
public static void main(String[] args) {
JFrame frame = new JFrame("My Drawing");
int[] input = {4, 2, 5, 6, 33, 15, 34, 0, 1, 99};
VisMain obj = new VisMain();
obj.arraySetter(input);
obj.setSize(400, 400);
frame.add(obj);
frame.pack();
frame.setVisible(true);
bubble_srt(input);
}
public void paint(Graphics g) {
for (int i = 0; i < array.length; i++) {
g.drawRect((i + 1) * 60, 100, 50, array[i]);
}
}
}
You are getting java.lang.NullpointerException as your array is null. Please fix that and your code should work. You cannot get array.length of null.
I am editing my answer as I like the answer presented by #Abra
I'm trying to scan though an AraayList created in the main class, in the turtle class to check various criteria. I simplified the code as much as possible for you.
The main class:
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.awt.event.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class TurtleProgram
{
public ArrayList<DynamicTurtle> turtles;
public static void main(String[] args)
{
new TurtleProgram();
}
public TurtleProgram()
{
//INSTANTIATED JFRAME WITH BUTTONS/SLIDER AND CREATED LISTENER METHODS
turtles = new ArrayList<DynamicTurtle>(); //THE ARRAYLIST I AM WANTING TO USE IN ANOTHER CLASS
turtles.add(new RandomTurtleB(canvas, 400, 300, 100, 0)); //THIS ARRAYLIST BECOMES LARGER WHEN BUTTONS ON JFRAME TO ADD NEW TURTLES
gameLoop(); //LOOP FOREVER
}
private void gameLoop()
{
int deltaTime = 20;
while(true)
{
for (int i = 0; i < turtles.size(); i++)
{
(turtles.get(i)).unDrawTurtle(); //REMOVE FROM CANVAS
(turtles.get(i)).wrapPosition((turtles.get(i)).getPositionX(), (turtles.get(i)).getPositionY()); //MAKE SURE TURTLES NOT OFF SCREEN
}
for (int i = 0; i < turtles.size(); i++)
{
(turtles.get(i)).update(1000); //MAKE THE TURTLES MOVE WITH A CHANCE OF TURNING
}
for (int i = 0; i < turtles.size(); i++)
{
(turtles.get(i)).drawTurtle(); //DRAW TO CANVAS
}
for(int i = 0; i < turtles.size(); i++)
{
(turtles.get(i)).cohesian(); //THIS IS HOW I WOULD LIKE TO ADDRESS THE COHESIAN METHOD
}
Utils.pause(deltaTime/2);
}
}
}
Then I would like to check the current turtle against other turtles to see if it's close in the cohesion() method to perform actions:
class Turtle
{
protected Canvas canvas; // private field reference to a canvas private
private CartesianCoordinate myLocation, oldLocation;
private boolean penDown = true;
private double angle, maxX, maxY, nowPosX, nowPosY, maximumX, maximumY, x, y;
public double d, e, first, second;
private int speed;
public Turtle(Canvas canvas, CartesianCoordinate initLocation)
{
this.canvas = canvas;
this.myLocation = new CartesianCoordinate(0,0);
penDown = true;
myLocation = initLocation.copy();
}
public void cohesian()
{
double flockingDistanceLimit = 200;
double numberOfFlockers = 0;
double combinedX = 0;
double combinedY = 0;
double averageCombinedX, averageCombinedY, averageCombinedY, moveToFlock, turnToFlock, distanceToPotentialFlock;
for (DynamicTurtle t : turtles) //CANNOT USE THE ARRAYLIST TO SCAN THROUGH ITS ELEMENTS
{
if(this.getPositionX() != t.getPositionX() && this.getPositionY() != t.getPositionY()) //MAKE SURE TURTLE ISNT SCANNING ITS SELF
{
distanceToPotentialFlock = Math.sqrt(Math.pow((this.getPositionX()-t.getPositionX()),2 ) + Math.pow((this.getPositionY()-this.getPositionY()),2)); //FIND DISTANCE BETWEEN CURRENT AND SCANNED TURTLE
if(distanceToPotentialFlock < flockingDistanceLimit) //MAKE SURE THE FOUND TURTLE IS WITHIN RANGE USING THE DISTANCE BETWEEN POINTS METHOD
{
combinedX = combinedX + t.getPositionX(); //FIND SUMMATION OF X POSITIONS
combinedY = combinedY + t.getPositionY(); //FIND SUMMATION OF Y POSITIONS
numberOfFlockers++; //AS A FLOCKER HAS BEEN FOUND INCREMENT THE NUMBER OF FLOCKERS
}
}
if(numberOfFlockers > 0)
{
averageCombinedX = (combinedX / numberOfFlockers); //FIND AVERAGE X POSITION
averageCombinedY = (combinedY / numberOfFlockers); //FIND AVERAGE Y POSITION
moveToFlock = Math.sqrt(Math.pow(averageCombinedX,2 ) + Math.pow(averageCombinedY, 2)); //CALCULATE DISTANCE TO CENTER OF FLOCKING
turnToFlock = Math.atan(averageCombinedY / averageCombinedX);
if(turnToFlock < 0)
{
turnToFlock = 360 - (-turnToFlock); //ADJUSTING FOR NEGATIVES
}
}
}
}
public void wrapPosition(double x, double y)
{
this.maxX = x;
this.maxY = y;
if(maxX < 0)
{
this.setPositionX(800);
}
else if(maxX > 800)
{
this.setPositionX(0);
}
if(maxY < 0)
{
this.setPositionY(600);
}
else if(maxY > 600)
{
this.setPositionY(0);
}
}
}
If I could have any help with using the ArrayList in the Turtle Class, in the cohesian() method, it would be greatly appreciated. Thank you in advance.
Either pass the arrayList as parameter to cohesian, or declare it as a static field
I have a game to code in java with Swing. The classes of the game work but I'm having troubles with the GUI class. The printing methods use an object Graphics as parameter but I don't know how to use this. Here is the portion of the code :
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
Piece piece = joueur.getPosition();
int positionClick = numberPiece(e.getX(), width) + numberPiece(e.getY(), height) * 10;
int positionJoueur = Scenario.pieces.get(piece) - 1;
if (positionClick==positionJoueur-1)
joueur.deplacer('O');
else if (positionClick==positionJoueur+1)
joueur.deplacer('E');
else if (positionClick==positionJoueur-10)
joueur.deplacer('N');
else if (positionClick==positionJoueur+10)
joueur.deplacer('S');
panel.updateUI();
repaint();
}
private int numberPiece(int coord, int size) {
for (int i = 1; i < 11; i++) {
int x = i * size;
if (coord < x) {
return (i - 1);
}
}
return 0;
}
});
Please help me, thank you.