How to separate program into classes after making it in one tab - java

I have created a simple game in processing using java language however I created the game all in one tab and I now need to put everything into its own class so it looks organized and is easier to read however although I have created classes before I am struggling to put my code into separate classes and getting them to work. Below is an example of one of my classes
int pixelsize = 5; // size of pixels on screen
int gridsize = pixelsize * 8 + 5;
Player player;
ArrayList enemies = new ArrayList();
ArrayList bullets = new ArrayList();
int direction = 1; // where the wave moves to
boolean incy = false;
void setup() {
background(0);
fill(255);
size(800, 800);
}
void draw() {
background(0);
player.draw();
for (int i = 0; i < bullets.size(); i++) {
Bullet bullet = (Bullet) bullets.get(i);
bullet.draw();
}
void createEnemies() {
for (int i = 0; i < width/gridsize/2; i++) {
for (int j = 0; j <= 4; j++) {
enemies.add(new Enemy(i*gridsize, j*gridsize + 20 ));
}
}
}

Step 1: Click this button:
Step 2: Click the New Tab option. Give your tab a name that matches the name of the class you want in that tab. I'll use Ball:
Step 3: Write the code for your class in that tab:
class Ball {
float x;
float y;
void setPosition(float x, float y) {
this.x = x;
this.y = y;
}
void drawBall() {
fill(ballColor);
ellipse(x, y, 25, 25);
}
}
Step 4: Write the code for the sketch in the first tab:
Ball ball = new Ball();
color ballColor = #00ff00;
void setup(){
size(500, 500);
}
void draw(){
background(0);
ball.setPosition(mouseX, mouseY);
ball.drawBall();
}
Notice that this sketch can use the class in the other tab, and the class can use functions or variables defined in the sketch tab.
More info can be found in the Processing reference.

Related

Cannot find a class or type named “Circle”

I'm not sure why "Circle" isn't being recognized in my code. The error that shows up in Processing says "Cannot find a class or type named “Circle”"
I am trying to take values that are taken from a sensor (through Arduino) & visualize them in Processing. From what I saw, I thought adding "import java.util.*" would fix the problem, but it didn't.
I'm not sure if the term "Circle" is just too broad, & if I have to make it "MCircle" or "PCircle" or something like that.
Here is the Processing code:
import processing.serial.*;
import java.util.*;
Serial myPort;
int val;
int amt = 10;
Circle [] circles;
void setup() {
size(500, 500);
rectMode(CENTER);
circles = new Circle[amt];
for (int i=0; i<10; i++) {
circles[i] = new Circle();
}
String portName = Serial.list()[2];
myPort = new Serial(this, portName, 9600);
// println(Serial.list());
//println(val);
}
void draw() {
//if your port is available, get the val
if ( myPort.available() > 2) {
val = myPort.read();
}
background(0);
for (int i = 0; i<10; i++) {
circles[i].display();
}
class Circle
{
float xPos;
float yPos;
Circle() {
xPos = random(width);
yPos = random(height);
}
}
}
void display() {
// ellipse(random(width), random(height), val, val);
ellipse(xPos, yPos, val, val);
}
Circle is declared in scope of draw. You have to declare it in global scope:
void draw() {
//if your port is available, get the val
if ( myPort.available() > 2) {
val = myPort.read();
}
background(0);
for (int i = 0; i<10; i++) {
circles[i].display();
}
/* DELETE
class Circle
{
float xPos;
float yPos;
Circle() {
xPos = random(width);
yPos = random(height);
}
}*/
}
// INSERT
class Circle {
float xPos;
float yPos;
Circle() {
xPos = random(width);
yPos = random(height);
}
}
A few things:
I would recommend putting the class declaration of Circle in its own file. One class to a file, generally. File named the same as the class, and import it into your processing class.
Similar to #1, your processing code should probably be in a class.
Good security practice is to avoid accessing xPos and yPos directly from outside the Circle class - it's better to use getter methods and make the class attributes private.

Moving objects in a series of set directions

I am new to coding and struggling with a project. I do not know Java well.
My aim is as follows: monitoring and optimization of a concrete delivery service for construction sites by the company operator (concrete plant and truck suppliers).
I should have a concrete plant, two trucks and several sites that are created thanks to the user's click. The operator can have at any time the vision of the trucks of his company that deliver concrete to the worksites located in a given geographical area. And the number of sites evolves (= click of the user hard the screen).
Variables:
Concrete plant -> Coordinates (xCoord, yCoord) + size;
Site(arraylist) -> Coordinates (site.x, site.y or destination.x, destination.y in the lorry class) + size;
Lorry (x2) -> Coordinates (location.x, location.y); size; origin; destination.
Actions of a lorry:
move to a site (1)
wait about 3 seconds when it reaches the site
go to the next site of the list (2) (+wait 3secs)
go back to the concrete plant after it reaches 2 sites (wait 3 secs)
go to the next site (3), then (4), go back to concrete plant etc...
(basically it does 2 sites and comes back, 2 site and comes back etc... And it cannot go to a site that has already been delivered).
It would be good also to have the logo of the site change once it has been reached by a lorry.
Choice of the lorry: I got 2 lorries and the choice on which lorry to go needs to be made by:
if its free (not already on route to a site);
if it is full (has done 0 or 1 site, or hasn't done 2 sites);
the closest one ( measure the distance).
Interaction with HTML:
I was thinking if possible to somehow measure the distance made by each lorries and display it on the HTML screen (and save the data with a keypress if possible).
So I started by looking if I can maybe add a lorry (don't know if its the right part to start on, maybe the actions would be better). And i tried telling it that if the siteNumber is under 2 it goes through the list of sites, but if not the new destination is the concrete plant. But it doesn't work.
So that's my script so far (I have replaced the images of the concrete, site and lorries by ellipses and rectangles so you can run it):
/*preload = "factory_12.png";*/
/*preload = "sign.png";*/
/*preload = "simple_truck.png";*/
Lorry lorry;
//PImage concretePlant;
//PFont aFont;
int xCoord;
int yCoord;
ArrayList<Site> sites;
int siteSize = 30;
void setup() // What is called once at the beginning
{
size (500, 500);
//concretePlant = loadImage("factory_12.png");
//aFont = createFont("IndustrialRevolution-Regular", 12);
//textFont(aFont);
xCoord = int(width/2);
yCoord = int(height/2);
//Creating empty Array List where store sites objects
sites = new ArrayList<Site>();
//Adding first site
sites.add(new Site(random(width), random(height), siteSize));
//storing lorries
lorry = new Lorry(xCoord, yCoord);
}
void draw() // Draw the background and concrete plant
{
background (235, 247, 255); //light blue background, not in draw as it wouldn't allow the site image to stay
//image(concretePlant, xCoord, yCoord, 60, 60);
ellipse(xCoord, yCoord, 60, 60);
//fill(1);
//text("Concrete Plant", xCoord-20, yCoord+70);
//Calling the sites
for (int i = sites.size () - 1; i>=0; i--) {
Site site = sites.get(i);
site.displaySites();
}
//calling the lorry functions
lorry.updateLorry();
}
void mousePressed() {
sites.add(new Site(mouseX, mouseY, siteSize));
}
class Site
{
float x,y;
float size;
//PImage picture;
Site (float xin, float yin, float sin)
{
x = xin;
y = yin;
size = sin;
//picture = loadImage("sign.png");
}
void displaySites()
{
//image(picture, x, y, 60, 60);
rect(x, y, 60, 60);
}
}
class Lorry
{
PVector location1;
PVector location2;
PVector concretePlant;
//PVector velocity;
//PImage mixer;
boolean changeDirection;
int siteNumber = 0;
Site destination;
Lorry(float xCoord, float yCoord)
{
concretePlant = new PVector(xCoord, yCoord); //Initial start point
location1 = new PVector(xCoord, yCoord); //Initial start point
location2 = new PVector(xCoord, yCoord); //Initial start point
//velocity = new PVector(2, 2);
//mixer = loadImage("simple_truck.png");
destination = sites.get(siteNumber);
changeDirection = false;
}
void displayLorry()
{
//image(mixer, location1.x, location1.y, 30, 30);
//image(mixer, location2.x, location2.y, 30, 30);
ellipse(location1.x, location1.y, 30, 30);
ellipse(location2.x, location2.y, 30, 30);
}
void Move()
{
float xdir1 = destination.x - location1.x;
float ydir1 = destination.y - location1.y;
PVector dir1 = new PVector (xdir1, ydir1);
dir1.normalize();
location1.add(dir1);
print("1going");
float xdir2 = destination.x - location2.x;
float ydir2 = destination.y - location2.y;
PVector dir2 = new PVector (xdir2, ydir2);
dir2.normalize();
location2.add(dir2);
print("2going");
}
void checkProgress()
{
for (int siteNumber = 0; siteNumber < 2; siteNumber = siteNumber++);
if (dist(destination.x, destination.y, location1.x, location1.y) < 1) {
if (siteNumber <sites.size() -1) {
siteNumber++; // siteNumber = siteNumber + 1;
destination = sites.get(siteNumber);
changeDirection = true;
println("1reached final site");
} else {
destination.x = concretePlant.x;
destination.y = concretePlant.y;
println ("1back to home");
}
println("1progress checked ");
}
if (dist(destination.x, destination.y, location2.x, location2.y) < 1) {
if (siteNumber <sites.size() -1) {
siteNumber++; // siteNumber = siteNumber + 1;
destination = sites.get(siteNumber);
changeDirection = true;
println("2reached final site");
} else {
destination.x = concretePlant.x;
destination.y = concretePlant.y;
println ("2back to home");
}
println("2progress checked ");
}
}
void updateLorry()
{
displayLorry();
Move();
checkProgress();
}
}

Java beginning if statement in for loop being skipped while others work

Back again with another problem that has stumped me completely and cannot for the life of me fix.
So I had previously posted a question about my Java game I am making for a class that with the help of #MadProgrammer was fixed...mostly. Now there is a new problem that needs a post all to it's own
Previous Post:
Rows and columns with multidimensional array java
Problem:
In the code below I have it set up to loop through the variables x and y to make rows and columns on a jPanel. Each time it loops through it should randomly mark the "x,y" location with one of the "terrains" so that later it can "paint" that location with the appropriate colored 20x20 square.
The code runs great except for one thing, it looks like it skips the very first "if statement" that marks the "terran[0]" which is "floor". When the code is ran it "paints" the other three "terrains" and not a single "floor" "terrain".
I have looked for a solution on these posts but no success:
Java if statement is skipped
If statement being skipped during execution
Java - for loops being skipped
Java if-statement being skipped
Here is a working piece of code that results in the problem at hand:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class gamePanel extends JPanel
{
public gamePanel()
{
setBounds(115,93,480,480);
}
private Random generator = new Random();
int floor = 0; //initializes the variable floor to zero for later use
int dirt = 1;
int stone = 2;
int water = 3;
int width = 24;
int height = 24;
int x, y; // my x & y variables for coordinates
int[][] coords = new int[width][height]; //my array that I want to store the coordinates for later use in painting
int[] terrain = {floor, dirt, stone, water}; //my terrain that will determine the color of the paint
public void mapGen() //what should mark/generate the JPanel
{
for(x = 0; x < width; x++)
{
for(y = 0; y < height; y++)
{
int z = generator.nextInt(20);// part of the randomization
if(z <= 10)
{
coords[x][y] = terrain[0]; //should mark the coordinates as floor
}
if(z == 11)
{
coords[x][y] = terrain[3];//should mark the coordinates as water
}
if(z >= 12 && z <= 16)
{
coords[x][y] = terrain[2];//should mark the coordinates as stone
}
if(z >= 17 && z <= 19)
{
coords[x][y] = terrain[1];//should mark the coordinates as dirt
}
coords[0][0] = terrain[0]; // sets coordinate 0,0 to floor //need to have these always be floor
coords[23][23] = terrain[0]; // sets coordinate 24,24 to floor //^^^^^^^^^^
}
}
}
#Override
public void paintComponent(Graphics g)//what will paint each 20x20 square on the grid what it is assigned
{
super.paintComponent(g);
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
mapGen();
if(coords[x][y] == terrain[floor])//should paint the floor color at marked coordinates
{
g.setColor(Color.white);
g.fillRect((x*20), (y*20), 20, 20);
}
if(coords[x][y] == terrain[dirt]);//should paint the dirt color at marked coordinates
{
g.setColor(new Color(135,102,31));
g.fillRect((x*20), (y*20), 20, 20);
}
if(coords[x][y] == terrain[stone])//should paint the stone color at marked coordinates
{
g.setColor(new Color(196,196,196));
g.fillRect((x*20),(y*20),20,20);
}
if(coords[x][y] == terrain[water])//should paint the water color at marked coordinates
{
g.setColor(new Color(85,199,237));
g.fillRect((x*20),(y*20),20,20);
}
}
}
}//end paintComponent
public static void main(String[] args)
{
gamePanel panel = new gamePanel();
JFrame frame = new JFrame();
frame.setSize(500,550);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.setVisible(true);
}//end main
}// end gamePanel
Please keep in mind that I am a novice programmer and I am still learning. So anything that is not considered "basic" code please explain in detail.

Connecting Pvector points into a Mesh in Processing from an L-System?

I've built this L-System in Processing using toxiclib and I want to connect each point which is specified to each intersection in the branching of the tree. I've written a separate sketch in which I'm trying to create a triangle mesh by connecting the three closest points, I've been able to connect three points but I want it to be able to go through all the Vertices in an arraylist and then connect three closest points until I have a mesh out of all the vertices in the array. I also need to be able to convert this whole sketch into a function where by I can feed it into my L-System and then it will return the whole system with all the points connected in order to create a mesh. Essentially this is so I can then texture and maybe possibly apply Shaders to it if possible. I think that I might be attempting a harder way of approaching this for I believe toxiclibs or HEMESH libraries could do all of this for me, but I've been unable to figure it out. Any help would be much appreciated.
Here's the code for the sketch I wrote to try and connect all the points into a mesh.
import peasy.*;
float min = 1000;
ArrayList <PVector> loc = new ArrayList <PVector> ();
ArrayList <PVector> locSort = new ArrayList <PVector> ();
float [] minDists;
int [] minIdxs;
PeasyCam cam;
void setup() {
size(600, 600, OPENGL);
cam = new PeasyCam(this, 100);
for (int i=0; i<50; i++) {
loc.add(new PVector(random(-50, 50), random(-50, 50), random(-50, 50)));
}
minDists = new float[3];
minIdxs = new int[3];
for (int i = 0; i < 3; i ++)minDists[i] = 1000;
for (int i=0; i<loc.size(); i++) {
for (int j=0; j<loc.size (); j++) {
PVector vi= loc.get(i);
// loc.remove(i);
PVector vj= loc.get(j);
// loc.remove(j);
float c = vi.dist(vj);
for (int k = 0; k < 3; k++) {
if (c < minDists[k] && c > 0) {
if (k == 0) {
minDists[2] = minDists[1];
minDists[1] = minDists[0];
} else if (k == 1) {
minDists[2] = minDists[1];
}
println(k, c);
minDists[k] = c;
minIdxs[k] = j;
break;
}
}
}
}
}
void draw() {
background(255);
for (PVector v : loc) {
pushMatrix();
translate(v.x, v.y, v.z);
fill(0);
noStroke();
sphere(1);
popMatrix();
}
for (int i = 0; i < 3; i ++) {
PVector p1 = loc.get(minIdxs[i]);
PVector p2 = loc.get(minIdxs[(i+1)%3]);
stroke(255, 0, 0);
line(p1.x, p1.y, p1.z, p2.x, p2.y, p2.z);
}
}
Also the L-System was created by following this tutorial: https://www.youtube.com/watch?v=qF8LGLVrwfo

Processing class giving NullPointException (Beginner)

Im trying to make a basic frogger game. All I am trying to do it make a class for my frog image, and then I want it have it shown under void draw(); Except I keep getting NullPointException, can anyone help me figure out why?
This is the code I've been playing with to try and figure out the issue.
PImage img; // frog image
Frog froggy;
Car[] c1;
class Car {
float xpos;
int ypos;
int sizel;
int sizew;
float yspeed;
color c;
Car(){
xpos = 0;
ypos = (int)random(120,480);
sizel = (int)random(20,30);
sizew = 15;
yspeed = (float)random(1,3);
c= color(random(255), random(255), random(255));
}
void carShape() {
rectMode(CENTER);
fill(c);
rect(xpos,ypos,sizel,sizew);
fill(0);
rect(xpos-5, ypos-8, 8,5);
rect(xpos+5, ypos-8, 8,5);
rect(xpos-5, ypos+8, 8,5);
rect(xpos+5, ypos+8, 8,5);
}
void moveCar () {
xpos = xpos + yspeed;
if (xpos > width) {
xpos = 0;
ypos = (int)random(120,480);
}
}
}
class Frog {
int frogx;
int frogy;
Frog(){
frogx = width/2-20;
frogy = 527;
}
void drawFrog() {
image(img,frogx,frogy);
}
}
void setup() {
size(800,600);
img = loadImage("frog.png");
c1 = new Car[20];
for(int i=0; i<20; i++) {
c1[i] = new Car();
}
}
void draw() {
background(100);
froggy.drawFrog();
for(int i=0; i<20; i++) {
c1[i].carShape();
c1[i].moveCar();
}
}
Heres the error
Exception in thread "Animation Thread" java.lang.NullPointerException
at snowflakecarexample.draw(snowflakecarexample.java:97)
at processing.core.PApplet.handleDraw(PApplet.java:2120)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:197)
at processing.core.PApplet.run(PApplet.java:1998)
at java.lang.Thread.run(Thread.java:680)
you din't initialize Frog object.
try
Frog froggy = new Frog();
froggy.drawfrog();
Whatever froggy should be, it must be initialized:
Frog froggy;
... (Froggy is null)
froggy.drawFrog();
perhaps you want to call a constructor somewhere? Like:
Frog froggy = new Frog();
In the moveCar() function you are checking if (xpos > width), but I don't see width declared anywhere. Unless it is declared and not in the snippet you have posted, this could be the issue.
You also use width in the Frog() function.

Categories