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.
Related
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.
I am a beginner in java and appologies for any wrong terminology.
I am trying to create a simple 2D game just to learn more about how java works.
For now what I would want to know is how I would go about using a 2D array and drawing it. And maybe add a simple icon(player) you can move around with the arrowkeys.
Currently I have the following classes Keybarricade:
public class Keybarricade{
public static void main(String[] args)
{
JFrame obj = new JFrame();
Playingfield playingfield = new Playingfield();
obj.setBounds(0, 0, 900, 900);
obj.setBackground(Color.GRAY);
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(playingfield);
}
and playingfield:
public class Playingfield extends JPanel{
private ImageIcon playerIcon;
private int [][] playinggrid = new int[10][10];
private int [] playerX = new int[10];
private int [] playerY = new int[10];
public Playingfield()
{
}
public void paint (Graphics g)
{
//draw border for playingfield
g.setColor(Color.white);
g.drawRect(10, 10, 876, 646);
//draw background for the playingfield
g.setColor(Color.LIGHT_GRAY);
g.fillRect(11, 11, 875, 645);
//draw player imageicon
playerIcon = new ImageIcon("src/images/playerIcon.png");
playerIcon.paintIcon(this, g, playerX[1], playerY[1] );
}
this gives the following window:window I have right now
What I would want is to use the 2D array to draw/paint a 10x10 grid, something like this: window I would like
But sadly I couldnt find a way to do this or I did but didnt understand it.
If someone could point me in the right dirrection that would be awsome!
thanks in advance.
You could use something like this in your paint function:
int boxWidth = 30;
int boxHeight = 30;
for (int currentX = 0;
currentX < playinggrid.length * boxWidth;
currentX += boxWidth) {
for (int currentY = 0;
currentY < playinggrid[0].length * boxHeight;
currentY += boxHeight) {
g.drawRect(currentX, currentY, boxWidth, boxHeight);
}
}
If you want to draw the icon in the middle of a cell you can do the following inside the two for loops:
g.drawImage(playerIcon.getImage(),
currentX + boxWidth/2 - playerIcon.getIconWidth()/2,
currentY + boxHeight/2 - playerIcon.getIconHeight()/2,
null);
BTW: I think it's better to override paintComponent instead of paint, see this post
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.
There are other questions about the topic but this one is somehow different.
Basically I have this class called "Player" that I multiply for a certain number of times. This class generates random coordinates in the canvas and the bitmaps move towards those coordinates. Now the problem is that some of them overlap with one another making it look "unrealistic".
I've tried a simple "if" statement inside the "Player" class but it doesn't work, since every instance of the class takes into count only its variables and ignores the variables of the other instances.
Here's the code:
I have this first class with another class nested:
public class MainActivity extends Activity{
Game gameView;
float k,l;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new Game(this);
setContentView(gameView);
}
public class Game extends SurfaceView implements Runnable {
Canvas canvas;
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = true;
Player[] player = new Player[3];
public Game(Context context) {
super(context);
ourHolder = getHolder();
ourThread = new Thread(this);
ourThread.start();
for(int i=0; player.length < i; i++){
player[i] = new Player(context);
}
}
public void run() {
while(isRunning) {
if(!ourHolder.getSurface().isValid())
continue;
canvas = ourHolder.lockCanvas();
canvas.drawRGB(200, 200, 200);
for ( int i = 0; player.length < i; i++){
player[i].draw(canvas);
player[i].move();
}
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
}
And here's the player class:
public class Player {
Bitmap base;
float x = (float) (Math.random()*200);
float y = (float) (Math.random()*200);
float e = (float) (Math.random()*200);
float r = (float) (Math.random()*200);
public Player(Context context) {
super();
base = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
}
public void draw(Canvas canvas) {
if(x > e-5 && x < e+5 && y > r-5 && y < r+5){
e = (float) (Math.random()*canvas.getWidth());
r = (float) (Math.random()*canvas.getHeight());
}
canvas.drawBitmap(base, x - base.getWidth()/2, y - base.getHeight()/2, null);
}
public void move () {
//Here's just the code that makes the bitmap move.
}
}
As you may have seen, the variables "e" and "r" create random values every time the bitmap's coordinates (x and y) get closer to them, and then the "x" and "y" variables increase or decrease their values in order to match the "e" and "r" coordinates.
Now what I want is for the variables "x" and "y" to interact with the variables "x" and "y" of the other instances so that they don't overlap. Is there a way to do that?
Thank you very much.
In your Player class, either make X and Y public (not recommended) or create accessors to them:
public void setX(float x) {
this.x = x;
}
and
public int getX() {
return x;
}
Now, in your run() method, you can do something like this (borrowing from code you already have):
for ( int i = 0; player.length < i; i++){
player[i].draw(canvas);
player[i].move();
}
...
for (int i = 0; i < player.length - 1; i++) {
if (player[i].getX() > player[i + 1].getX() - 5 &&
player[i].getX() < player[i + 1].getX() + 5 &&
player[i].getY() > player[i + 1].getY() - 5 &&
player[i].getY() < player[i + 1].getY() + 5) {
// Do your update here!
// You may need to create other methods...or you can just
// create random X & Y for the player.
}
This is a really simple approach. Keep in mind, if you have many players, you could move one onto another player, so you might want to test again once you move the player to ensure it is clear.
I am trying to make a program that generates 25 random ovals then draw a ball and make it bounce, I got it somewhat done, I generated the ovals and I got the ball to move but when I added the thread it kept repeating the draw oval loop, I get somewhat why this is happening but I have no idea how to fix it.
Basically my program should:
draw 25 random sized ovals on random locations within the border - completed
draw a ball and make it move - completed
make the ball bounce - not done but I know how to do it
but it keeps repeating step one.
this is my code that I have written, oh and I have to use applets right now its part of the course please don't suggest I use swing or something else:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
public class As4B extends Applet implements Runnable
{
public int x, y;
public int width = 854;
public int height = 480;
public int border = 20;
public Image offscreen;
public Graphics d;
public void init()
{
setSize(width,height);
Thread th = new Thread(this);
th.start();
offscreen = createImage(width,height);
d = offscreen.getGraphics();
}
public void run()
{
x = 100;
y = 100;
while(true)
{
x ++;
y ++;
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paint(Graphics gfx)
{
d.setColor(java.awt.Color.black);
d.fillRect(0, 0, width, height);
d.setColor(java.awt.Color.green);
d.fillRect(0 + border, 0 + border, (width - (border * 2)), (height - (border* 2)));
genOval(25, d);
d.setColor(Color.gray);
d.fillOval(x, y, 50, 50);
gfx.drawImage(offscreen, 0, 0, this);
}
public int random(int low, int high)
{
int answer =(int)((Math.random()*(high-low))+ low);
return answer;
}
public void genOval(int amount, Graphics f)
{
int ranWidth, ranHeight, ranX, ranY, red, blue, green;
int i = 0;
while(i < 25)
{
green = random(0,255);
blue = random(0,255);
red = random(0,255);
f.setColor(new Color(red,green,blue));
ranWidth = random(30,400);
ranHeight = random(30,200);
ranX = random(0 + border, ((width - border)- (ranWidth)));
ranY = random(0 + border , ((height - border)- (ranHeight)));
f.fillOval(ranX, ranY, ranWidth, ranHeight);
i++;
}
}
public void update(Graphics gfx) {
paint(gfx);
}
}
Your genOval() method has no persistent backing. Every time repaint() is called (by your thread), the paint() method is called, and this generates new locations for the random ovals. You need to create a persistent source for that information, like so:
List<Rectangle> rectangles = new ArrayList<Rectangle>();
List<Color> colors = new ArrayList<Color>();
public void init() {
...
for (int i = 0; i < 25; i++) {
int green = random(0,255);
int blue = random(0,255);
int red = random(0,255);
colors.add(new Color(red,green,blue));
ranWidth = random(30,400);
ranHeight = random(30,200);
ranX = random(0 + border, ((width - border)- (ranWidth)));
ranY = random(0 + border , ((height - border)- (ranHeight)));
rectangles.add(new Rectangle(ranX, ranY, ranWidth, ranHeight));
}
}
public void genOval(Graphics g) {
for (int i = 0; i < 25; i++) {
Color color = colors.get(i);
Rectangle rectangle = rectangle.get(i);
// Draw using color & rectangle
}
}