"Avoid Falling Blocks " the game on Processing java - java

So I am making this game in processing JAVA and the code is below so the gist is I have a ball and it avoids the falling rectangles so, for now, the ball can move sideways and the rectangles fall from above but how do I decrease my life when a rectangle hits the ball.
I made a function named Lives which was supposed to decrease lives if the circle gets hit with a rectangle but I can't come up with the code for that. Could anyone help with that?
int score;
int score1;
int miss;
int lives=10;
int ballx, bally;
class Rect
{
float x;
float y;
float speed;
float leng;
color c;
boolean valid;
final int MAX_COLOR = 255;
final int MIN_X = 50, MAX_X = 750;
final int MIN_Y = -800, MAX_Y = -100;
int MIN_SPEED = 1, MAX_SPEED = 2;
final int MIN_Leng = 50, MAX_Leng =100 ;
Rect()
{
initAll();
}
void initAll() {
valid = true;
c = color(random(255), random(255), random(255));
x = random(MIN_X, MAX_X);
y = random(MIN_Y, MAX_Y);
speed = random(MIN_SPEED, MAX_SPEED);
leng = random(MIN_Leng, MAX_Leng);
}
void update() {
if (!valid) {
initAll();
return;
}
move();
draw_rect();
}
void draw_rect()
{
fill(c);
rect (x, y, leng, leng);
}
void move()
{
if (y-leng <= height)
{
y += speed;
} else if (y-leng > height )
{
valid = false;
miss++;
}
}
void Lives()
{
}
void GameOver()
{
if (lives==0)
{
for (int i = 0; i < Obj.length; i++)
{
Obj[i] = new Rect();
}
background(0);
textSize(50 );
fill(255);
text( "You Lose ", 15, 150);
text( "Score: " + score, 15, 100);
}
}
boolean isOver(int mx, int my) {
float disX = x - mx;
float disY = y - my;
if (sqrt(sq(disX) + sq(disY)) < leng/2 ) {
return true;
} else {
return false;
}
}
}
Rect [] Obj = new Rect [10];
void setup() {
size (400, 600);
ballx=200;
bally=300;
for (int i = 0; i < Obj.length; i++)
{
Obj[i] = new Rect();
}
}
void draw() {
background(0);
textSize(50);
//fill(0);
text( "Score: " + score, 0, 100);
text("Lives: " + lives, 0, 50);
ellipse(ballx,bally,20,20);
for (int i = 0; i < Obj.length; i++) {
Obj[i].update();
//Obj[i].Lives();
Obj[i].GameOver();
}
surface.setTitle(nf(frameRate, 3, 2));
}
void keyPressed(){
for(Rect s : Obj){
if ( key =='q' ){
ballx=ballx-2;
score++;
score1++;
s.valid = false;
break;
}
if ( key =='e'){
ballx=ballx+2;
score++;
score1++;
s.valid = false;
break;
}
}
}

Easiest i think think of is -
case 1 - if you want health of ball to reduce gradually :
Define maximum_Health variable and assign it to 100.
Every time a block hits your ball, reduce the health by some weight you want to define.
case 2 - if ball life is lost for every block hit
Define remaining_Lives variable and give it some value you want the number of lives to start with.
Every time a block hits your ball, reduce the remaining_Lives by one.
I think that should give you some hint.

Related

Java game a bullet killed all object on the screen

I am trying to make a plane shooting game.
I have a plane with a number of laser(maxLaser) and a number of random enemies.
When I create a single random enemy it is fine but when I make a number of enemy I have a tiny problem.
When I shot any of enemy with the bullet(laser) kills every enemies on the screen.
I guess I have a problem with two nested loops (maxLaser and maxEnemy) but I could not figure out.
This is the code I am trying to fix that calculate distance laser and enemy
public void updatehelicopter(double dt) {
helicopterSpin = getFrame(0.2, 4);
// nested loop for kill enemies
for(int l =0; l<maxHelicopter; l++){
helicopterPositionX[l] += helicopterVelocityX[l] * dt;
helicopterPositionY[l] += helicopterVelocityY[l] * dt;
// if(helicopterActive[l]==true){
for (int i = 0; i < maxLaser; i++) {
if (laserActive[i] == true) {
if (distance(laserPositionX[i], laserPositionY[i], helicopterPositionX[l], helicopterPositionY[l]) < 20* 1.2) {
// Destroy the laser
laserActive[i] = false;
helicopterActive[l]=false;
// Create an explosion
createExplosion(helicopterPositionX[i], helicopterPositionY[l]);
// Create a new random helicopter
randomhelicopter();
}
}
}
}
}
The idea is, I want to create 10 enemies and when shot one of them the program that I want to create one more simultaneously.
Here is my Laser and Enemies classes that you can imagine.
Enemy:
Image helicopters;
Image[] helicopterF = new Image[4];
Image[] helicopterR = new Image[4];
Image[] helicopterL = new Image[4];
Image helicopterImage;
// helicopter Position
double[] helicopterPositionX;
double[] helicopterPositionY;
double[] helicopterVelocityX;
double[] helicopterVelocityY;
double[] helicopterAngle;
int helicopterSpin;
boolean helicopterLeft;
boolean helicopterRight;
boolean[] helicopterActive;
int maxHelicopter;
int numhelicopter ;
public void inithelicopter() {
maxHelicopter = 10;
numhelicopter = maxHelicopter;
helicopterPositionX = new double[maxHelicopter];
helicopterPositionY = new double[maxHelicopter];
helicopterVelocityX= new double[maxHelicopter];
helicopterVelocityY= new double[maxHelicopter];
helicopterAngle = new double[maxHelicopter];
helicopterActive = new boolean[maxHelicopter];
for(int i =0; i<maxHelicopter;i++){
helicopterActive[i]=false;
}
// Load image
// helicopterPositionX= 300;
for (int i = 0; i < 4; i++) {
helicopterF[i] = subImage(helicopters, 0 + i * 300, 0, 300, 300);
}
for (int i = 0; i < 4; i++) {
helicopterR[i] = subImage(helicopters, 0 + i * 300 + 1200, 0, 300, 300);
}
for (int i = 0; i < 4; i++) {
helicopterL[i] = subImage(helicopters, 0 + i * 300 + 2400, 0, 300, 300);
}
// helicopterPositionY= 400;
// helicopterImage = subImage(spritesheet, 480, 0, 240, 240);
}
// Randomly position helicopter
public void randomhelicopter() {
for (int i = 0; i < numhelicopter; i++) {
// Random position
// random number between lower and upper limit for direction of items
helicopterPositionX[i] = (int) (Math.random() * (600 - 500)) + 500;
helicopterPositionY[i] = rand(-500);
// Random Velocity
helicopterVelocityX[i] = -20;
helicopterVelocityY[i] = 80;
// Random Angle
helicopterAngle[i] = 40;
}
}
// Function to update 'move' the helicopter
public void updatehelicopter(double dt) {
helicopterSpin = getFrame(0.2, 4);
//
for(int l =0; l<maxHelicopter; l++){
helicopterPositionX[l] += helicopterVelocityX[l] * dt;
helicopterPositionY[l] += helicopterVelocityY[l] * dt;
// if(helicopterActive[l]==true){
for (int i = 0; i < maxLaser; i++) {
if (laserActive[i] == true) {
if (distance(laserPositionX[i], laserPositionY[i], helicopterPositionX[l], helicopterPositionY[l]) < 20* 1.2) {
// Destroy the laser
laserActive[i] = false;
helicopterActive[l]=false;
// Create an explosion
createExplosion(helicopterPositionX[i], helicopterPositionY[l]);
// Create a new random helicopter
randomhelicopter();
}
}
}
}
}
public void drawhelicopter() {
// Save the current transform
for(int i=0; i<maxHelicopter; i++){
saveCurrentTransform();
// ranslate to the position of the helicopter
translate(helicopterPositionX[i], helicopterPositionY[i]);
// Rotate the drawing context around the angle of the helicopter
rotate(helicopterAngle[i]);
// Draw the actual helicopter
//int i = getAnimationFrame(explosionTimer, explosionDuration, 30);
drawImage(helicopterF[helicopterSpin], -30, -30, 110, 110);
// Restore last transform to undo the rotate and translate transforms
restoreLastTransform();
}
}
Laser:
Image laserImage;
double[] laserPositionX;
double[] laserPositionY;
// Laser velocity
double[] laserVelocityX;
double[] laserVelocityY;
// Laser Angle
double[] laserAngle;
// Laser active
boolean[] laserActive;
// Laser Mode
int laserMode;
double rapidFireDelay;
double rapidFireTimer;
int maxLaser, numLaser;
// NOTE: try first add 5 different level and if works then you should try make
// one laser and should cahnge only image
public void laserInit() {
maxLaser = 9;
numLaser = maxLaser;
laserMode = 0;
rapidFireDelay = 0.1;
laserPositionX = new double[maxLaser];
laserPositionY = new double[maxLaser];
laserVelocityX = new double[maxLaser];
laserVelocityY = new double[maxLaser];
laserAngle = new double[maxLaser];
laserActive = new boolean[maxLaser];
for (int i = 0; i < maxLaser; i++) {
laserActive[i] = false;
}
laserImage = subImage(laser, 1536, 0, 512, 512);
}
public void fireLaser(double x, double y, double angle) {
for (int i = 0; i < numLaser; i++) {
if (laserActive[i] == false) {
laserPositionX[i] = x;
laserPositionY[i] = y;
laserVelocityX[i] = sin(angle) * 350;
laserVelocityY[i] = -cos(angle) * 350;
laserAngle[i] = angle;
// laseractive[i] == true;
laserActive[i] = true;
break;
}
}
}
public void fireLaser() {
// NOTE: check variable of laserpower
if (laserMode == 0) {
// Normal Mode
fireLaser(airplanePositionX, airplanePositionY, airplaneAngle);
} else if (laserMode == 1) {
// Scatter Shot
int inactiveLasers = 0;
// For all lasers
for (int i = 0; i < numLaser; i++) {
// Check if laser is inactive
if (laserActive[i] == false) {
// Count number of inactive lasers
inactiveLasers++;
}
}
// Check if at least 3 lasers are free
if (inactiveLasers >= 3) {
// Fire three lasers
fireLaser(airplanePositionX, airplanePositionY, airplaneAngle - 15);
fireLaser(airplanePositionX, airplanePositionY, airplaneAngle);
fireLaser(airplanePositionX, airplanePositionY, airplaneAngle + 15);
}
} else if (laserMode == 2) {
// Rapid-Fire Mode
fireLaser(airplanePositionX, airplanePositionY, airplaneAngle + rand(20.0) - 10);
}
}
public void createLaser() {
saveCurrentTransform();
for (int i = 0; i < maxLaser; i++) {
if (laserActive[i]) {
saveCurrentTransform();
translate(laserPositionX[i], laserPositionY[i]);
rotate(laserAngle[i]);
drawImage(laserImage, -30, -30, 60, 60);
restoreLastTransform();
}
}
restoreLastTransform();
}
public void laserUpdate(double dt) {
if (laserMode == 2 && space) {
// Increment Timer
rapidFireTimer += dt;
// If Timer is greater than delay
if (rapidFireTimer > rapidFireDelay) {
// Decrement delay
rapidFireTimer -= rapidFireDelay;
// Fire laser
fireLaser();
}
}
for (int i = 0; i < maxLaser; i++) {
laserPositionX[i] += laserVelocityX[i] * dt;
laserPositionY[i] += laserVelocityY[i] * dt;
if (laserPositionX[i] < 0) {
laserActive[i] = false;
}
if (laserPositionX[i] >= width()) {
laserActive[i] = false;
}
if (laserPositionY[i] < 0) {
laserActive[i] = false;
}
}
}
I am not sure how correct I am so can I get your advise?
Externally some class in code:
public double distance(double x1, double y1, double x2, double y2) {
// Calculate and return the distance
return Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));
}

Using Processing to Create Arcade of Games, after game is chosen. Won't draw, still runs. processing

Hi basically whenever I click p or b to run one of my games they run, but you can't see them as they don't draw over the main menu screen. These games do work if separated.
PImage pongImage, brickImage;
boolean mouseDown = false;
boolean [] keys = new boolean [128];
Ball ball;
Paddleb gamerPaddle;
static ArrayList<Brick> bricks = new ArrayList();
Puck puck;
Paddle one;//left
Paddle two;//right
int oneScore = 0;
int twoScore = 0;
int gameScreen = 0;
void setup() {
fullScreen();
ball = new Ball();//creating objects
gamerPaddle = new Paddleb();
puck = new Puck();//creating objects
one = new Paddle(true);
two = new Paddle(false);
}
void draw() {
menuPress();
if (gameScreen == 0) {
mainMenu();
}
if (gameScreen ==1) {
gamePong();
}
if (gameScreen == 2) {
gameBrick();
}
}
void keyReleased() {
keys[key] = false;
one.move(0);
two.move(0);
gamerPaddle.move(0);
}
void menuPress() {
if (keys['p'] == true) {
gameScreen = 1;
} else if (keys ['b'] == true) {
gameScreen =2;
} else {
gameScreen = 0;
}
}
void moves() {
if (keys['w'] == true) {
one.move(-10);
} else if (keys['s'] == true) {
one.move(10);
}
if (keys['i'] == true) {
two.move(-10);
} else if (keys['k'] == true) {
two.move(10);
}
if (keys['a'] == true) {
gamerPaddle.move(-10);
} else if (keys['d'] == true) {
gamerPaddle.move(10);
}
}
void keyPressed() {
keys[key] = true;
}
void drawBricks() {
for (int i = 0; i <= bricks.size() - 1; i++) {
fill(255);
rectMode(CORNER);
rect(bricks.get(i).x, bricks.get(i).y, bricks.get(i).s, bricks.get(i).s2);
}
}
void bricksSetup() {
rectMode(CORNER);
float s = 80;
float x = width/4;
float y = Brick.space;
while (y < height/2) {
while (x < width - width/4) {
bricks.add(new Brick(x, y, s, s));
x +=90;
}
x = width/4;
y +=90;
}
}
void mainMenu() {
float picsY = height/2;
float brickX = 2 * width/3;
float pongX = width/3 - width/4;
pongImage = loadImage("pong photo.PNG");
brickImage = loadImage("Brick breaker.PNG");
pongImage.resize(width/4, height/4);
brickImage.resize(width/4, height/4);
background(150);
fill(255);
textSize(72);
text("AhMen's Arcade", width/5 + width/7, height/3);
image(pongImage, pongX, picsY);
text("Pong", width/6, 4 * height/5 + height/50);
image(brickImage, brickX, picsY);
text("Brick Breaker", 2 * width/3 + width/100, 4 * height/5 + height/50);
}
void gamePong() {
background(0);
System.out.println("cat");
boolean gameEnding = false;
do {
background(0);
one.screen();//creates paddle
two.screen();
puck.position();
puck.sides();
puck.screen();
moves();
puck.checkHitOne(one);
puck.checkHitTwo(two);
one.refresh();//limits y movement and keeps it moving at speed of 0 to make stops and starts not noticible
two.refresh();
fill(255);
textSize(32);
text(oneScore, 20, 50);
text(twoScore, width-40, 50);
textMode(CENTER);
text("PONG", width/2-55, 50);
} while (gameEnding != true);
exit();
}
void gameBrick() {
System.out.println("ya");
background(0);
bricksSetup();
ball.position();
while (ball.y - ball.r > height || ball.p1Score >= ((bricks.size()-1)*50)) {
System.out.println('l');
background(0);
moves();
drawBricks();
ball.checkHitTwo(gamerPaddle);
ball.checkHitBrick();
gamerPaddle.screen();//creates paddle
gamerPaddle.refresh();//limits y movement and keeps it moving at speed of 0 to make stops and starts not noticible
gamerPaddle.refresh();
ball.position();
ball.sides();
ball.screen();
ball.score();
}
exit();
}
this is just the main method btw, I do have other methods for the objects. I am not sure why this doesn't work, but if someone that has an Idea what the issue may be please lmk.
The processing draw function does not run on a seperate thread. When you have a while loop, which doesn't end, the draw-function never gets executed anymore.
You have to use variables scoped to the processing file and not just a function and then modify those variables inside the functions you currently use as the game-loops.
For example, if you want a program where a ball moves to the right and returns to coordinate 0 after passing it, you would have to structure it like this:
Ball ball = new Ball();
void draw() {
playBallGame();
drawBall();
}
void playBallGame() {
if (ball.x > width) ball.x = 0;
ball.x++;
}
Not like this:
void draw() {
drawBall();
playBallGame();
}
void playBallGame() {
Ball ball = new Ball();
while (true) {
if (ball.x > width) ball.x = 0;
ball.x++;
}
}

fadeout text at a lower speed

I want to make a group of array fade out until the last array object in this group was appended. And I use millis() to make every three object fadeout at a slower speed! So I create a function called boolean timelag(int time, int number)and each time I pass the time and sequence number into it and expect it will fadeout after 2 seconds after every third object was created, but seems that nothing happened
void draw() {
background(255, 255, 255);
for (int i=0; i<zoog.length; i++) {
zoog[i].jiggle();
zoog[i].display();
if(i%3 ==0 && i>=3){
time = millis();
timelag(time,i);
}
}
if(fadeout){
zoog[thatnumber].disappear();
zoog[thatnumber-1].disappear();
zoog[thatnumber-2].disappear();
}
}
My timelag function:
boolean timelag(int time, int number){
int thattime = time;
if(millis()-thattime>2000){
thatnumber = number;
fadeout = true;
}
else
fadeout = false;
return fadeout;
}
The whole code is here
Zoog[]zoog = new Zoog[1];
float count=0;
int xpos =0;
int ypos =0;
String message="haha";
int ntextsize = 20;
int nopacity =200;
int thistime = 0;
int thiscount = 0;
int time =0;
int number =0;
boolean fadeout = false;
int thatnumber=0;
//Zoog zoog;
void setup() {
size(400, 400);
xpos = int(random(width/2-200, width/2+40));
ypos = int(random(height/2, height/2-40));
zoog[0] = new Zoog(xpos, ypos, message, nopacity);
}
void draw() {
background(255, 255, 255);
for (int i=0; i<zoog.length; i++) {
zoog[i].jiggle();
zoog[i].display();
if(i%3 ==0 && i>=3){
time = millis();
timelag(time,i);
}
}
if(fadeout){
zoog[thatnumber].disappear();
zoog[thatnumber-1].disappear();
zoog[thatnumber-2].disappear();
}
}
void mousePressed() {
count = count + 1;
// int thiscount = 0;
if (count%3 ==0) {
xpos=int(random(30, width-30));
ypos=int(random(10, height-10));
}
else {
ypos = ypos+50;
}
nopacity = int(random(100, 255));
// text(message, xpos, ypos);
Zoog b = new Zoog(xpos, ypos, message, nopacity);
zoog =(Zoog[]) append(zoog, b);
}
boolean timelag(int time, int number){
int thattime = time;
if(millis()-thattime>2000){
thatnumber = number;
fadeout = true;
}
else
fadeout = false;
return fadeout;
}
class Zoog {
int x;
int y;
String thatmessage;
int opaci =0;
Zoog(int xpo, int ypo, String thismessage, int opa) {
x = xpo;
y = ypo;
thatmessage = thismessage;
opaci = opa;
}
void jiggle() {
x = x+int(random(-2, 2));
y = y+int(random(-2, 2));
}
void display() {
fill(0, opaci);
text(thatmessage, x, y);
print("x position is "+ x);
print("y position is "+y);
}
void disappear() {
for (int j=0; j<255; j++) {
opaci = opaci -j;
}
}
}
I assume that when you wrote...
if(fadeout) { ... }
you meant...
if(timelag()) { ... }
in your timelag function it's much more readable and faster(if even minutely) to just return true or false from the function rather than returning a variable, unless that variable is needed throughout your project over and over, which it doesn't seem like it is and if it is the function that changes it usually isn't needed to return a value unless you're checking the boolean of whether or not the change happened.
boolean timelag(int time, int number){
//int thattime = time; //You also don't need to create this you
//can simply use the time you're getting in the boolean statement
if(millis()-time>2000){
thatnumber = number;
return true;
}
else {
return false;
}
}
also, if you're trying to fix how long it takes for each zoog to fade out you need to give them all a number and then decrease that number each time the disappear function is called. Take the for loop out of the disappear and just have it subtract a unit from it each call in the draw loop.
void disappear() {
opacity -= somenumber //somenumber is usually something small and you can tweak it.
if (opacity == 0) {
dead = true;
}
}
You can think of the draw loop as your for loop. If you embed too many singular for loops it'll slow down the flow of your program. Right now, you probably don't even see them fading out and you probably don't get rid of them with the way the code is written right now.
And when you're testing it you can tweak that number until you find the sweet spot. If you want an amazing overview of all these concepts you can take a look here. Shiffman really goes deep into each aspect we're talking about here and it's short and fun to read.
First time i read the other post I misunderstood your goal. Anyway i've made a little tweak in your code that might help you understanding the way to go. BUT i did not moved it to an ArrayList, so this code below, kind of sucks... It can only, maybe, help you get things clear...
Zoog[]zoog = new Zoog[1];
float count=0;
int xpos =0;
int ypos =0;
String message="haha";
int ntextsize = 20;
int nopacity =200;
int thistime = 0;
int thiscount = 0;
//Zoog zoog;
void setup() {
size(400, 400);
xpos = int(random(width/2-200, width/2+40));
ypos = int(random(height/2, height/2-40));
zoog[0] = new Zoog(xpos, ypos, message, nopacity);
}
void draw() {
background(255);
for (int i=0; i<zoog.length; i++) {
zoog[i].jiggle();
zoog[i].display(); }
}
void mousePressed() {
count = count + 1;
// int thiscount = 0;
if (count%3 ==0) {
xpos=int(random(30, width-30));
ypos=int(random(10, height-10));
}
else {
ypos = ypos+50;
// thiscount = thiscount +1;
// thistime = millis();
// }
}
nopacity = int(random(100, 255));
text(message, xpos, ypos);
Zoog b = new Zoog(mouseX, mouseY, message, nopacity);
zoog = (Zoog[]) append(zoog, b);
zoog[zoog.length -2].disappear = true;
}
class Zoog {
int x;
int y;
String thatmessage;
boolean disappear;
int opaci =0;
Zoog(int xpo, int ypo, String thismessage, int opa) {
x = xpo;
y = ypo;
thatmessage = thismessage;
opaci = opa;
}
void jiggle() {
x = x+int(random(-2, 2));
y = y+int(random(-2, 2));
}
void display() {
if(disappear)
disappear();
fill(0, opaci);
text(thatmessage, x, y);
}
void disappear() {
opaci-=0.5;
}
}

Restarting millis in processing error

Having a massive problem with this piece of code. I'm working with Java in processing.
I've created a game where users must guide a character away from objects.
All the objects, health system and score system are based on mills().
Once the game ends we need to reset millis(), resetting the objects, score and health system.
I have searched implemented advice from friends and previously asked questions on here but the advice differs very slightly. I'm assuming it's something that I can't see.
I would really appreciate your help with this, I only ever use this site as a last resort not just when I'm feeling lazy.
//these are used to set the times which the games increases difficulty
//int timeDelay = 30000;
int delayOne = 2000;
int delayTwo = 5000;
int delayThree = 80000;
int delayFour = 90000;
int display = 2000;
//for collisions
float[] xpos = new float[6];
float[] ypos = new float[6];
//timer counts how many millis() each game lasts for
int timeStamp = 5000;
int timer;
int timer2 = millis() - timer;
//always at zero
//outputting score at the end of a game
int score;
int start;
//trying to get lives working
boolean lost = false;
//variable to store & output gale force when giving score
int Gale = 0;
//Changing length rectangle
float rX = 350.0;
float x1 = 20;
float y1 = 20;
float w1 = 100;
float h1 = 30;
//DECLARE OBJECTS JELLY CLASS
Jelly myObject;
Jelly myObject1;
Jelly myObject2;
Jelly myObject3;
//GENTLEMAN CLASS
gentleMan mygentleMan;
//LOLLY CLASS
Lolly myCow;
Lolly myCow1;
//PImages
PImage loader;
PImage bg;
PImage uh;
PImage bg1;
PImage bolt;
PImage over;
void setup()
{
bg=loadImage("backy1.png");
bg1 = loadImage("backy.png");
over = loadImage("over.png");
PFont L = loadFont("Lobster1.3-48.vlw");
textFont( L, 16);
size(400, 600);
smooth();
//begin = millis();
imageMode(CENTER);
//INITIALISE
myObject = new Jelly(320, 500);
myObject1 = new Jelly(150, 200);
// myObject2 = new Jelly(550, 500);
//myObject3 = new Jelly(300, 100);
mygentleMan = new gentleMan(200, 300);
//myObject.run();
//myObject1.run();
//myObject2.run();
myCow = new Lolly(400, 250);
myCow1 = new Lolly(150, 350);
timer = millis();
}
void draw()
{
start = 0;
//because we have image mode set to center for collisions
//we have to divide the height & width of the screen by 2 for hte image to fit
image(bg, 200, 300);
if (millis() >= start + delayOne)
{
image(bg1, 200, 300);
}
//CALL FUNCTIONALITY
myObject.run();
myObject.put_in_array(0);
myObject1.run(); // this one is going top to bottom
myObject1.put_in_array(1);
// myObject2.run();
//myObject2.put_in_array(2);
// myObject3.run();
//myObject3.put_in_array(3);
myCow.run();
myCow.put_in_array(4);
myCow1.run();
myCow1.put_in_array(5);
mygentleMan.run();
//health bar
fill(161, 221, 16);
noStroke();
rect(10, 24, rX, 10);
if(rX <= 100)
{
fill(221, 59, 16);
rect(10, 24, rX, 10);
}
else
if(rX <= 200)
{
fill(221, 137, 16);
rect(10, 24, rX, 10);
}
if(rX == 5.0)
{
lost = true;
noLoop();
// lives = lives - 1;
image(over, width/2, height/3);
fill(255);
text("Your Score Is: " + timer, width/2.7, height/2);
text("Gale Force Is; " + Gale, width/2.7, height/1.8);
score = timer;
}
//For Loop detecting collisions between mygentleMan & objects
for (int i=0; i < 6; i++) {
if (xpos[i] > 150 && xpos[i] < 250 && ypos[i] > (mygentleMan.y-58) && ypos[i] < (mygentleMan.y+58))
{
// text("collision", 200, 300);
bolt = loadImage("bolt.png");
image(bolt, xpos[i], ypos[i]);
rX = rX - 1;
}
//outputting score on screen # at all times
fill(255);
text("Score: " + timer, 320, 20);
}
//timer which will be score counter essentially
timer = millis();
//text(timer, 20, 20);
//moving the man up the screen if button is pressed, if not he levitates downward
if (keyPressed)
{
mygentleMan.y -= mygentleMan.moveY;
mygentleMan.moveY += 0.4;
}
else
{
mygentleMan.y += mygentleMan.moveY;
mygentleMan.moveY += 0.2;
}
fill(255);
text("Health", 20, 20);
if(mousePressed)
{
if(timer2 > timeStamp)
{
println("tit");
mygentleMan.y = height/2;
loop();
}
}
}
//class for first objects that move into the screen
class Jelly
{
//GLOBAL VARIABLES
float x = 0;
float y = 0;
float speedX = 1.8;
float speedY = 1.8;
float speedX2 = 2.1;
float speedY2 = 2.1;
float speedX3 = 2.2;
float speedY3 = 2.2;
PImage jelly = loadImage("jelly.png");
PImage hat = loadImage("hat.png");
PImage gale = loadImage("g1.png");
PImage force = loadImage("force.png");
PImage news = loadImage("news.png");
//CONSTRUCTOR
Jelly(float _x, float _y)
{
x = _x;
y = _y;
}
//FUNCTIONS
void run()
{
display();
move();
bounce();
image(force, 330, 550);
if (millis() >= start + delayOne)
{
display();
moveFast();
bounceFast();
image(gale, 280, 560);
Gale = 1;
if (start + delayOne + display >= millis())
{
image(news, 200, 300);
}
}
if (millis() >= start +delayTwo)
{
display();
moveFaster();
bounceFaster();
image(gale, 310, 560);
Gale = 2;
if (start + delayTwo + display >= millis())
{
image(news, 200, 300);
}
}
}
void bounce()
{
if ( x > width)
{
speedX = speedX * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX = speedX * -1;
}
if ( y > height)
{
speedY = speedY * -1;
}
if ( y < 0)
{
speedY = speedY * -1;
}
}
void bounceFast()
{
if ( x > width)
{
speedX2 = speedX2 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX2 = speedX2 * -1;
}
if ( y > height)
{
speedY2 = speedY2 * -1;
}
if ( y < 0)
{
speedY2 = speedY2 * -1;
}
}
void bounceFaster()
{
if ( x > width)
{
speedX3 = speedX3 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX3 = speedX3 * -1;
}
if ( y > height)
{
speedY3 = speedY3 * -1;
}
if ( y < 0)
{
speedY3 = speedY3 * -1;
}
}
void move()
{
x = x + speedX;
y = y + speedY;
}
void moveFast()
{
x = x + speedX2;
y = y + speedY2;
}
void moveFaster()
{
x = x + speedX3;
y = y + speedY3;
}
void put_in_array(int a)
{
xpos[a] = x;
ypos[a] = y;
}
void display()
{
image(hat, x, y);
}
}
//class for gentleman that floats
class gentleMan
{
//GLOBAL VARIABLES
float y = 400;
float x = 400;
float moveY;
//PImage umbrella;
PImage umbrella = loadImage("dafuq.png");
PImage over = loadImage("over.png");
//CONSTRCUTOR --- PIECES OF INFO PROVDE TO BUILD CLASS -- INTIIALIZE VARIBALE
gentleMan(float _x, float _y)
{
y = _y;
x = _x;
moveY = 2;
}
//FUNCTIONS
void run()
{
display();
keyReleased();
bounce();
// collision();
}
void display()
{
image(umbrella, x, y);
}
void keyReleased()
{
mygentleMan.moveY = 4;
}
void bounce()
{
if ( y < 0)
{
y = 0;
}
if (y > height)
{
//score = millis();
lost = true;
noLoop();
// lives = lives - 1;
image(over, width/2, height/3);
text("Your Score Is: " + timer, width/2.7, height/2);
text("Gale Force Is; " + Gale, width/2.7, height/1.8);
}
}
}
class Lolly
{
//GLOBAL VARIABLES
float x = 0;
float y = 0;
float speedX = 2;
float speedY = 2;
float speedX1 = 2.1;
float speedY1 = 2.1;
float speedX2 = 2.3;
float speedY2 = 2.3;
PImage cow = loadImage("cow.png");
//CONSTRUCTOR
Lolly(float _x, float _y)
{
x = _x;
y = _y;
}
//FUNCTIONS
void run()
{
// display();
//move();
//bounce();
if (millis() >= start + delayThree)
{
display();
moveFast();
bounceFast();
}
if (millis() >= start +delayFour)
{
display();
moveFaster();
bounceFaster();
}
}
void put_in_array(int a)
{
xpos[a] = x;
ypos[a] = y;
}
void bounce()
{
if ( x > width)
{
speedX = speedX * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX = speedX * -1;
}
if ( y > height)
{
speedY = speedY * -1;
}
if ( y < 0)
{
speedY = speedY * -1;
}
}
void bounceFast()
{
if ( x > width)
{
speedX1 = speedX1 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX1 = speedX1 * -1;
}
if ( y > height)
{
speedY1 = speedY1 * -1;
}
if ( y < 0)
{
speedY1 = speedY1 * -1;
}
}
void bounceFaster()
{
if ( x > width)
{
speedX2 = speedX2 * -1; //multiply by -1 to make it bounce
}
if ( x < 0)
{
speedX2 = speedX2 * -1;
}
if ( y > height)
{
speedY2 = speedY2 * -1;
}
if ( y < 0)
{
speedY2 = speedY2 * -1;
}
}
void move()
{
x = x + speedX;
y = y + speedY;
}
void moveFast()
{
x = x + speedX1;
y = y + speedY1;
}
void moveFaster()
{
x = x + speedX2;
y = y + speedY2;
}
void display()
{
image(cow, x, y);
}
}//end of cow class
void mousePressed()
{
}
Your question is not at all clear, but it sounds like you should be able to wrap System.currentTimeMillis() in an object that maintains a starting point and returns the offset. Something like
public class Millis
{
long start;
public Millis() { this.reset(); }
public void reset() { this.start = System.currentTimeMillis(); }
public long getMillis() { return System.currentTimeMillis() - start; }
}
You create an instance of this class at startup
Millis timer = new Millis();
then call reset() to set it back to zero at the beginning of each game. Everywhere in your code you currently have millis() you would have timer.getMillis()
Use a custom timer class
class Timer {
int savedTime; // When Timer started
int totalTime; // How long Timer should last
Timer(int tempTotalTime) {
totalTime = tempTotalTime;
}
// Starting the timer
void start() {
// When the timer starts it stores the current time in milliseconds.
savedTime = millis();
}
// The function isFinished() returns true if 5,000 ms have passed.
// The work of the timer is farmed out to this method.
boolean isFinished() {
// Check how much time has passed
int passedTime = millis()- savedTime;
if (passedTime > totalTime) {
return true;
} else {
return false;
}
}
}//end class
Then to call
firstTimer = new Timer(50000);
And then in the draw to check
if (firstTimer.isFinished()) {
//do sopemthing
//then restart timer
firstTimer.start();
}
else
{
// do soemthing else for the rest of the time....
}

Detect mouseclick on object Slick2d

I've made this code that successfully creates a 16x12 grid by 50x50 squares on a 800x600px board.
As you can see, the player moves to the coordinates of the players mouseclick.
Each square of the grid has an object of Felt (field) on it, which can be laast (locked). If a fields lock attribute is set to 1, the player should not be moved to that position.
How do i detect the field a player tries to move on to achieve this?
public class SimpleGame extends BasicGame{
private Image plane;
private float planeX;
private float planeY;
public SimpleGame()
{
super("SpilTest");
}
#Override
public void init(GameContainer gc) throws SlickException {
plane = new Image("figur.png");
}
#Override
public void update(GameContainer gc, int delta) throws SlickException {
Input input = gc.getInput();
if (input.isMousePressed(input.MOUSE_LEFT_BUTTON)) {
this.planeX = input.getMouseX() - 30;
this.planeY = input.getMouseY() - 50;
}
}
public void render(GameContainer gc, Graphics g) throws SlickException {
Felt board[][] = nytGrid();
int distancex = 0;
int distancey = 0;
int counter = 0;
for (int i=0; i < board.length ; i++) {
for (int j=0; j < board[i].length ; j++) {
if (board[i][j].getLaast() == 1) {
g.setColor(Color.red);
g.fillRect(distancex, distancey, 50, 50);
}
distancex += 50;
counter++;
if (counter == 16) {
distancey += 50;
distancex = 0;
counter = 0;
}
}
}
g.drawImage(plane, planeX, planeY);
}
public static void main(String[] args) throws SlickException {
AppGameContainer app = new AppGameContainer(new SimpleGame());
app.setDisplayMode(800, 600, false);
app.setTargetFrameRate(60);
app.start();
}
public Felt[][] nytGrid() {
Felt [][] board = new Felt[16][12];
for (int i=0; i < board.length ; i++) {
for (int j=0; j < board[i].length ; j++) {
int x = i;
int y = j;
board[i][j] = new Felt(x, y);
if (i == 5 && j == 5) {
board[i][j].setLaast(1);
}
}
}
return board;
}
}
First off, you should probably initialize the board in the init() method instead of render, so it doesn't have to do it every frame, and move the declaration for the grid next to the plane, planeX and planeY declarations in the class.
Now to disable movement into a locked square, first add a method to check if a square at certain coordinates is locked, so something along the lines of:
private boolean isLocked(int x, int y) {
int square = board[x/50][y/50];
if (square == 1) return true;
else return false;
}
Next modify the part of your update() method where you update the plane coordinates, so vaguely something like:
if (input.isMousePressed(input.MOUSE_LEFT_BUTTON)) {
int destX = input.getMouseX() - 30;
int destY = input.getMouseY() - 50;
if (!isLocked(destX, destY)) {
this.planeX = destX;
this.planeY = destY;
}
}
It's easy!
int mx = Mouse.getX();
int my = Mouse.getY();
But, it gives you the world cordinates, and you have to translate it to pixels:
int mx = Mouse.getX();
int my = Mouse.getY() * -1 + (Window.WIDTH / 2) + 71;

Categories

Resources