Java: Super class won't override function - java

I have been working on a game for a while and I would like to have a different class for each type of Creature that there is. Right now, all of the different creatures' AI is run in a long switch and I would like a superclass to ovveride that function with that AI for that creature. I have this set up but it won't override.
Am I forgetting something?
Bunny.java:
package creature;
import org.newdawn.slick.opengl.Texture;
import creature.Creature;
import creature.CreatureType;
import data.Tile;
public class Bunny extends Creature{
public Bunny(CreatureType type, float x, float y, float speed1) {
super(type, x, y, speed1);
}
public void AI(int type) {
System.out.println("test");
}
}
Creature.java:
public Creature(CreatureType type, float x, float y, float speed1) {
this.texture = drawImg(type.textureName);
this.textureHamster = drawImg("creatures/HamsterFace");
this.healthBackground = drawImg("health_background");
this.healthForeground = drawImg("health_foreground");
this.healthBorder = drawImg("health_border");
this.startTile = startTile;
this.x = x;
this.y = y;
this.intX = (int) x;
this.intY = (int) y;
this.width = texture.getImageWidth();
this.height = texture.getImageHeight();
this.speed1 = speed1;
this.speed = speed;
this.intspeed = speed;
this.grid = grid;
this.health = type.health;
this.inithealth = type.health;
this.hiddenHealth = health;
this.startHealth = health;
this.dir = false;
this.dchosen = false;
this.setx = 0;
this.hurt = 0;
this.panick = 0;
this.deathWish = 0;
this.pdir = -1;
this.myX = x;
this.myY = HEIGHT / 2;
this.right = false;
this.left = false;
this.fade = 0;
this.fir = true;
this.aiType = type.aiType;
this.yOffset = 0;
}
.....
public void AI(int type) {
if(panic > 0)
panic--;
hurt();
speed = speed1;
switch(type) {
case 1:
if(panic > 0) {
if(pickRandom(150, 300) < 10) {
direction = !direction;
}
if(direction) {
if(!right) {
x += speed;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed;
} else {
if(falling < 2)
gravity = 8;
}
}
} else {
if(getRange(WIDTH / 2, myX) > 200) {
directionCoolDown++;
if(directionCoolDown > pickRandom(150, 3000)) {
direction = !direction;
directionCoolDown = 0;
}
if(direction) {
if(!right) {
x += speed / 3.2;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed / 3.2;
} else {
if(falling < 2)
gravity = 8;
}
}
} else {
if(myX < WIDTH / 2) {
direction = true;
} else {
direction = false;
}
}
}
break;
case 2:
yOffset = -25;
if(!angry) {
pdir = 0;
if(getRange(Player.getX(), myX) < 300) {
hamsterFace = true;
} else {
hamsterFace = false;
}
if(!hamsterFace) {
directionCoolDown++;
if(directionCoolDown > pickRandom(150, 3000)) {
direction = !direction;
directionCoolDown = 0;
}
if(direction) {
if(!right) {
x += speed / 3.2;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed / 3.2;
} else {
if(falling < 2)
gravity = 8;
}
}
}
} else {
pdir++;
hamsterFace = false;
if(myX < Player.getX()) {
direction = true;
} else {
direction = false;
}
if(direction) {
if(!right) {
x += speed / 1;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed / 1;
} else {
if(falling < 2)
gravity = 8;
}
}
if(getRange(myX, Player.getX()) < 5 && getRange(myY, Player.getY()) < 5) {
hurtPlayer(-2);
direction = !direction;
if(direction) {
if(!right) {
x += speed * 10;
} else {
if(falling < 2)
gravity = 8;
}
} else {
if(!left) {
x -= speed * 10;
} else {
if(falling < 2)
gravity = 8;
}
}
}
}
if(panic > 1) {
angry = true;
} else {
if(pdir > pickRandom(1000,2000)) {
angry = false;
}
}
break;
}
}
.....
(Both classes are in the same package)
EDIT: I fixed the typo....

you have in the Bunny class:
public void AI() {
System.out.println("test");
}
in the Creature class:
public void AI(int type) {
if(panic > 0)
....
so
void AI(int type) and void AI() are NOT the same method (check the signature and how they take different parameters!)
therefore the Bunny class is not overriding anything from the parent class
--
edit:
now that your classes have a method void AI(int type) then we can say that
Bunny override the Creature AI method and everytime you call bunny.AI(f) your bunny method will be called!

Related

How do I make resizing images while displaying my screen not be inefficient in processing.core (PApplet)

I am new to coding and don't really know what I am doing. I know that there my code is pretty inefficient and I could probably fix it later (i.e. collision and movement), but I have what I think is an efficient map setup. It only renders what is either around the camera or is around the player based on the camera type (freeRoam vs placerCentered). This works and runs fine until I start to resize pictures when I zoom in and out my map. I think that every time I draw a resized image my computer resizes it and then draws it for every instance of it rather than resizing it once and drawing it. Would I have to make images for every instance of zooming in or out or is there an optimized resizing tool that I am missing?
Google Drive link with images if anyone is interested: https://drive.google.com/drive/folders/1s5_9YPX7_6QWaxZPexN7pWk8zgmaT0w5?usp=sharing
(All images are 20 x 20 I think besides warrior1 and stoneTile1 which are both 32 x 32)
import processing.core.*;
import processing.event.MouseEvent;
import java.util.*;
public class Dungeon1 extends PApplet implements MyLibrary {
static gameState currentState;
static cameraState currentCameraState = cameraState.playerCentered;
enum gameState {
Over, Running
}
enum cameraState {
freeRoam, playerCentered
}
int cameraScaling = 20;
PImage testBoots;
PImage clown;
PImage testSquare;
PImage stoneTile1;
PImage resizedTile;
PImage warrior1;
float enemyX = 10;
float enemyY = 10;
float redSquare;
int currentXPos = 10;
int currentYPos = 10;
int tileType;
int mapWidth = 500;
int mapHeight = 500;
int[][] squareType = new int[mapHeight][mapWidth];
boolean movingUp, movingDown, movingLeft, movingRight;
int squareX;
int squareY;
boolean canMoveUp, canMoveDown, canMoveLeft, canMoveRight = true;
int cameraX = currentXPos;
int cameraY = currentYPos;
int lastCameraX;
int lastCameraY;
boolean centerCamera = false;
int pastMouseXPosition;
int pastMouseYPosition;
int squareWidth;
int squareHeight;
boolean mouseDragging = true, freeRoam, playerCentered;
public static void main(String[] args) {
PApplet.main("Dungeon1");
}
public void settings() {
fullScreen();
}
public void setup() {
playerStartPos();
createMap();
currentState = gameState.Running;
testBoots = loadImage("Images/TestBoots.png");
clown = loadImage("Images/clown.png");
testSquare = loadImage("Images/testSquare.png");
stoneTile1 = loadImage("Images/stoneTile1.png");
resizedTile = loadImage("Images/resizedTile.png");
warrior1 = loadImage("Images/warrior1.png");
}
public void draw() {
background(0, 0, 0);
drawMap();
isMoving();
}
public void keyPressed() {
if (key == 'w') {
movingUp = true;
}
if (key == 's') {
movingDown = true;
}
if (key == 'a') {
movingLeft = true;
}
if (key == 'd') {
movingRight = true;
}
if (key == 'k') {
Test = true;
}
if (key == 'c') {
currentCameraState = cameraState.playerCentered;
centerCamera = true;
}
if (key == 'v') {
currentCameraState = cameraState.freeRoam;
}
if (key == 'b') {
currentCameraState = cameraState.playerCentered;
}
}
public void keyReleased() {
if (key == 'w') {
movingUp = false;
}
if (key == 's') {
movingDown = false;
}
if (key == 'a') {
movingLeft = false;
}
if (key == 'd') {
movingRight = false;
}
if (key == 'k') {
Test = false;
}
}
public void mouseDragged(MouseEvent e) {
if (pastMouseXPosition < mouseX) {
lastCameraX--;
}
if (pastMouseXPosition > mouseX) {
lastCameraX++;
}
if (pastMouseYPosition < mouseY) {
lastCameraY--;
}
if (pastMouseYPosition > mouseY) {
lastCameraY++;
}
pastMouseXPosition = mouseX;
pastMouseYPosition = mouseY;
}
public void mousePressed() {
currentCameraState = cameraState.freeRoam;
mouseDragging = true;
pastMouseXPosition = mouseX;
pastMouseYPosition = mouseY;
}
public void mouseReleased() {
mouseDragging = false;
}
public void mouseWheel(MouseEvent e) {
if (e.getAmount() < 0) {
cameraScaling--;
} else {
cameraScaling++;
}
}
public void isMoving() {
if (movingUp) {
if (canMoveUp) {
currentYPos--;
cameraY--;
}
if (squareType[currentXPos][currentYPos] == 2) {
currentYPos++;
canMoveUp = false;
cameraY++;
}
}
if (movingDown) {
if (canMoveDown) {
currentYPos++;
cameraY++;
}
if (squareType[currentXPos][currentYPos] == 2) {
currentYPos--;
canMoveDown = false;
cameraY--;
}
}
if (movingRight) {
if (canMoveRight) {
currentXPos++;
cameraX++;
}
if (squareType[currentXPos][currentYPos] == 2) {
currentXPos--;
canMoveRight = false;
cameraX--;
}
}
if (movingLeft) {
if (canMoveLeft) {
currentXPos--;
cameraX--;
}
if (squareType[currentXPos][currentYPos] == 2) {
currentXPos++;
canMoveLeft = false;
cameraX++;
}
}
if (squareType[currentXPos][currentYPos] != 2) {
drawPlayer();
canMoveUp = true;
canMoveLeft = true;
canMoveDown = true;
canMoveRight = true;
}
}
public void playerStartPos() {
currentXPos = 96/2;
currentYPos = 54/2;
}
public void drawPlayer() {
if (currentCameraState == cameraState.playerCentered) {
image(testSquare, (currentXPos * cameraScaling - cameraX * cameraScaling), (currentYPos * cameraScaling - cameraY * cameraScaling), cameraScaling, cameraScaling);
} else if (currentCameraState == cameraState.freeRoam) {
image(testSquare, (currentXPos * cameraScaling - lastCameraX * cameraScaling), (currentYPos * cameraScaling - lastCameraY * cameraScaling), cameraScaling, cameraScaling);
}
}
public void createMap() {
//First creates the plane to navigate
for (int r = 0; r < mapHeight; r++) {
for (int c = 0; c < mapWidth; c++) {
redSquare = generator.nextInt(100);
if (redSquare > 90) {
tileType = 2;
} else {
tileType = 0;
}
squareType[r][c] = tileType;
}
}
}
public void drawMap() {
//TODO: Either figure out how to make actual scaled images not run poorly or make a bunch of images that only are displayed a scaled resolution
if (cameraScaling < 15) {
cameraScaling = 15;
}
if (cameraScaling > 50) {
cameraScaling = 50;
}
if (centerCamera) {
cameraX = currentXPos - 47*20/ cameraScaling;
cameraY = currentYPos - 23*20/ cameraScaling;
}
squareWidth = 20+ cameraScaling;
squareHeight = 20+ cameraScaling;
centerCamera = false;
if (currentCameraState == cameraState.freeRoam) {
cameraX = lastCameraX;
cameraY = lastCameraY;
for (int r = lastCameraX; r < lastCameraX + 96*20/ cameraScaling + 2 ; r++) {
for (int c = lastCameraY; c < lastCameraY + 54*20/ cameraScaling + 2; c++) {
squareX = r * cameraScaling - lastCameraX * cameraScaling;
squareY = c * cameraScaling - lastCameraY * cameraScaling;
if (r > 0 && c > 0 && r < mapWidth && c < mapHeight) {
if (squareType[r][c] == 0) {
image(resizedTile, squareX, squareY, cameraScaling, cameraScaling);
} else {
colorTiles(r, c);
rect(squareX, squareY, cameraScaling, cameraScaling);
}
}
}
}
} else if (currentCameraState == cameraState.playerCentered) {
lastCameraX = cameraX;
lastCameraY = cameraY;
for (int r = cameraX; r < cameraX + 96*20/ cameraScaling + 2; r++) {
for (int c = cameraY; c < cameraY + 54*20/ cameraScaling + 2; c++) {
squareX = r * cameraScaling - cameraX * cameraScaling;
squareY = c * cameraScaling - cameraY * cameraScaling;
if (r > 0 && c > 0 && r < mapWidth && c < mapHeight) {
if (squareType[r][c] == 0) {
image(resizedTile, squareX, squareY, cameraScaling, cameraScaling);
} else {
colorTiles(r, c);
rect(squareX, squareY, cameraScaling, cameraScaling);
}
}
}
}
}
}
public void colorTiles(int r, int c) {
if (squareType[r][c] == 2) {
fill(255, 0, 0);
}
}
}```

Trying to convert open processing code into pj.5s

I have no clue how to change this into p5.js. Just trying to work on conversions. Please help me get this code to work in p5.js.
I know that this is old code and p5.js have different rules. Maybe the array isn't working. I have no clue.
Myself myself;
ArrayList<Enemy> enemies;
`enter code here`ArrayList<Enemy> enemies;
ArrayList<Bullet> myBullets;
ArrayList<Bullet> eneBullets;
void setup(){
size(640, 640);
rectMode(CENTER);
myself = new Myself();
enemies = new ArrayList<Enemy>();
myBullets = new ArrayList<Bullet>();
eneBullets = new ArrayList<Bullet>();
}
void draw(){
background(0);
myself.display();
for(Enemy enemy: enemies){
enemy.display();
}
for(Bullet bullet: myBullets){
bullet.display();
}
for(Bullet bullet: eneBullets){
bullet.display();
}
myself.update();
ArrayList<Enemy> nextEnemies = new ArrayList<Enemy>();
for(Enemy enemy: enemies){
enemy.update();
if(!enemy.isDead){
nextEnemies.add(enemy);
}
}
enemies = nextEnemies;
ArrayList<Bullet> nextMyBullets = new ArrayList<Bullet>();
for(Bullet bullet: myBullets){
bullet.update();
if(!bullet.isDead){
nextMyBullets.add(bullet);
}
}
myBullets = nextMyBullets;
ArrayList<Bullet> nextEneBullets = new ArrayList<Bullet>();
for(Bullet bullet: eneBullets){
bullet.update();
if(!bullet.isDead){
nextEneBullets.add(bullet);
}
}
eneBullets = nextEneBullets;
if(random(1) < 0.02){
enemies.add(new Enemy());
}
}
class Myself{
PVector loc;
float size;
int coolingTime;
boolean isDead;
Myself(){
size = 25;
loc = new PVector(width / 2, height - size / 2 - 10);
coolingTime = 0;
isDead = false;
}
void display(){
if(isDead){
fill(255, 255, 0);
stroke(0, 255, 0);
} else {
noFill();
stroke(0, 255, 0);
}
rect(loc.x, loc.y, size, size);
}
void update(){
isDead = false;
float dmx = mouseX - loc.x;
dmx = constrain(dmx, -5, 5);
loc.x += dmx;
coolingTime++;
if(mousePressed && coolingTime >= 10){
myBullets.add(new Bullet());
coolingTime = 0;
}
for(Bullet b: eneBullets){
if((loc.x - size / 2 <= b.loc.x && b.loc.x <= loc.x + size / 2)
&& (loc.y - size / 2 <= b.loc.y && b.loc.y <= loc.y + size / 2)){
isDead = true;
b.isDead = true;
break;
}
}
for(Enemy e: enemies){
if(abs(loc.x - e.loc.x) < size / 2 + e.size / 2 && abs(loc.y - e.loc.y) < size / 2 + e.size / 2){
isDead = true;
e.isDead = true;
break;
}
}
}
}
class Bullet{
PVector loc;
float vel;
boolean isMine;
boolean isDead;
Bullet(){
loc = new PVector(myself.loc.x, myself.loc.y);
vel = -10;
isMine = true;
}
Bullet(Enemy enemy){
loc = new PVector(enemy.loc.x, enemy.loc.y);
vel = 5;
isMine = false;
}
void display(){
if(isMine){
stroke(0, 255, 0);
} else {
stroke(255, 0, 0);
}
line(loc.x, loc.y, loc.x, loc.y + vel);
}
void update(){
loc.y += vel;
if((vel > 0 && loc.y > height) || (vel < 0 && loc.y < 0)){
isDead = true;
}
}
}
class Enemy{
PVector loc;
float vel;
float size;
int coolingTime;
boolean isDead;
Enemy(){
size = 25;
loc = new PVector(random(size / 2, width - size / 2), -size / 2);
vel = 3;
coolingTime = int(random(60));
isDead = false;
}
void display(){
noFill();
stroke(255, 0, 0);
rect(loc.x, loc.y, size, size);
}
void update(){
loc.y += vel;
if(loc.y > height){
isDead = true;
}
coolingTime++;
if(coolingTime >= 60){
eneBullets.add(new Bullet(this));
coolingTime = 0;
}
for(Bullet b: myBullets){
if((loc.x - size / 2 <= b.loc.x && b.loc.x <= loc.x + size / 2)
&& (loc.y - size / 2 <= b.loc.y && b.loc.y <= loc.y + size / 2)){
isDead = true;
b.isDead = true;
break;
}
}
}
}
If you could just tell me what parts i need to change or fix it it would help me a lot thankyou.
You shouldn't try to translate code line-by-line. Instead, you need to take a step back and understand what the program does, and then you implement that in the target language.
They syntax for Processing (which is based on Java) is very different from the syntax for p5.js (which is based on JavaScript).
Instead of trying to "convert" the code, you need to think in terms of what the code actually does. And then start with a new program in p5.js and do that using p5.js. It's not always going to be a line-by-line conversion.
here's your code:
class myself{
constructor()
{
this.x = 0;
this.y = height-35;
this.size = 25;
this.health = 25;
this.cooldown = 0;
this.plrBullets = [];
}update(){this.cooldown++;
if (mouseIsPressed && this.cooldown>10)
{
this.cooldown = 0;
this.plrBullets.push(new Bullet(true,this.x,this.y));
}
let nextPlrBullets = [];
for (let i = 0; i<this.plrBullets.length; i++)
{
this.plrBullets[i].update();
if (this.plrBullets[i].alive)
{
nextPlrBullets.push(this.plrBullets[i]);
}
}
this.plrBullets = nextPlrBullets;
this.x += constrain(mouseX - this.x, -10, 10);
for (let i = 0; i<eneBullets.length; i++)
{
let c = eneBullets[i];
if (c.x > this.x && c.x < this.x + 25 && c.y > this.y && c.y < this.y + 25)
{
this.health--;
c.alive = false;
if (this.health<=0)
{
print("you lost")
}
}
}
noFill();
stroke(0,255,0);
rect(this.x,this.y,this.size,this.size);
}
}
class enemy{
constructor()
{
this.x = random(15,width-15);
this.y = random(-100,0);
this.size = 25;
this.cooldown = 0;
this.alive = true;
}
update()
{
this.y+=2.5;
this.cooldown++;
if (this.cooldown>20)
{
this.cooldown = 0;
eneBullets.push(new Bullet(false,this.x,this.y));
}
let nextEneBullets = [];
for (let i = 0; i<eneBullets.length; i++)
{
eneBullets[i].update();
if (eneBullets[i].alive)
{
nextEneBullets.push(eneBullets[i]);
}
}
eneBullets = nextEneBullets;
for (let i = 0; i<my_self.plrBullets.length; i++)
{
let c = my_self.plrBullets[i];
if (c.x > this.x && c.x < this.x + 25 && c.y > this.y && c.y < this.y + 25)
{
this.alive = false
c.alive = false;
}
}
if (this.y>height+35)
{
this.y = random(-100,0);
}
noFill();
stroke(255,0,0);
rect(this.x,this.y,this.size,this.size);
}
}
class Bullet{
constructor(dir,x,y)
{
this.x = x;
this.speed = 5;
this.dir = dir;
this.alive = true;
this.y = y;
}
update()
{
if (this.dir)
{
this.y -= this.speed;
}else{
this.y += this.speed;
}
if (this.y<-20)
{
this.alive = false;
}//this.y = -25;
if(this.dir)
{
stroke(0,255,0);
}else{
stroke(255,0,0);
}
line(this.x,this.y,this.x,this.y+25);
}
}
let my_self;
let eneBullets = [];
let enemies = [];
function setup()
{
createCanvas(640,640);
rectMode(CENTER);
my_self = new myself();
for (let i = 0; i<10; i++)
{
enemies.push(new enemy());
}
}
function draw()
{
background(0);
if(random(1) < 0.02 && enemies.length<15){
enemies.push(new enemy());
}
my_self.update();
let newEnimies = [];
for (let i = 0; i<enemies.length; i++)
{
enemies[i].update();
if (enemies[i].alive)
{
newEnimies.push(enemies[i]);
}
s}
enemies = newEnimies;
if (enemies.length == 0)
{
print("you win");
}
}
Sorry that the collisions are a bit wacky but when converting processing to p5 here are some tips:
1: don’t use array lists use arrays with push instead of add
2: no data types only LET
3: print not println
4: class constructors are declared as “constructor” instead of class name
5: use “function” before function declaration instead of void
6: pvector is vector
7: google is your friend
8: the p5 documentation

My maze does not block character movement once it gets past the first tile

I currently have a maze project that is built of four tiles that form a loop when moving around to create an endless universe. Initially when inputting character blocking abilities, my second maze tile (the tile directly to the left of the character starting tile) displayed the blocking program one block off. The further you would move to the left onto the initial tile and back to the second tile, the more the character would be blocked off from the original tile. I assumed the problem lied within the tile placement, as the character would switch tiles, they would be one off. I altered my tile coordinates and size which somehow created a new problem. Now, the initial starting tile blocks appropriately, but once the character enters another tile, the blocking no longer works at all and the character is able to just proceed in an infinite loop around the maze. Attached is two classes: InTheDark (the class that calls the AppWindow) and AppWindow (the class consisting of the methods that develop the maze and the flashlight capabilities - they were commented out for the purpose of better access to the game). Some segments of code are commented out for the reason that they are functioning, but have no affect on the background. Could someone please help me on figuring out where the error is coming from?
This code contains InTheDark and AppWindow.
import java.text.DecimalFormat;
import java.applet.*;
import java.util.Random;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.Graphics2D.*;
import java.awt.event.*;
import java.util.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioInputStream;
public class InTheDark
{
public static void main(String args[])
{ //launches the frame and timer events
int winWid = 500;
int winHei = 500;
AppWindow runner = new AppWindow(winWid,winHei);
runner.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{System.exit(0);}});
runner.setSize(winWid,winHei);
runner.show();
}
}
class AppWindow extends Frame implements KeyListener
{
int wid=0; //size of display window wid
int hei=0; //size of display window height
Image virtualMem;
Graphics gBuffer;
Image mazeBackgroundCenter;
Image mazeBackgroundElse;
Image character;
Graphics2D g2D;
int cx, cy;
int bx1, by1;
int bx2, by2;
int bx3, by3;
int bx4, by4;
int[][] maze11 = {{1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,0,0,0,0,0,0},
{1,0,1,0,1,0,1,1,1,1,1},
{1,0,1,0,0,0,1,0,0,1,1},
{1,0,1,1,0,1,1,1,0,1,1},
{0,0,0,1,0,0,0,0,0,1,1},
{1,1,0,1,1,1,1,1,1,1,1},
{1,1,0,0,0,0,1,1,1,1,1},
{1,1,0,1,1,0,0,0,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1}};
int[][] maze22 = {{1,1,1,0,1,1,1,1,1,1,1},
{0,0,0,0,0,0,1,1,1,1,1},
{1,1,0,1,1,0,1,1,0,1,1},
{1,0,0,1,1,0,0,0,0,1,1},
{1,1,0,1,1,1,1,0,1,1,1},
{1,1,0,0,0,0,1,0,0,0,0},
{1,1,1,1,1,0,1,1,0,1,1},
{1,0,0,0,0,0,1,1,1,1,1},
{1,1,1,0,1,0,0,0,0,1,1},
{1,1,1,1,1,1,1,1,0,1,1}};
int[][] maze33 = {{1,1,1,1,1,1,1,1,1,1,1},
{0,0,1,0,1,1,0,1,1,1,1},
{1,0,0,0,1,1,0,0,1,1,1},
{1,0,1,1,1,1,0,1,1,1,1},
{1,0,0,0,1,1,0,1,1,1,1},
{1,0,1,0,0,0,0,1,1,1,1},
{1,0,1,1,1,1,1,0,0,0,0},
{1,0,1,0,0,0,1,0,1,1,1},
{1,0,0,0,1,0,0,0,1,1,1},
{1,1,1,1,1,1,1,1,1,1,1}};
int[][] maze44 = {{1,1,1,1,1,1,1,0,1,1,1},
{1,0,1,1,1,1,0,0,0,0,0},
{1,0,0,0,1,1,1,1,0,1,1},
{1,1,1,0,0,0,1,1,0,1,1},
{1,1,1,1,1,0,1,0,0,1,1},
{1,1,0,0,0,0,1,0,1,1,1},
{0,0,0,1,1,0,0,0,1,1,1},
{1,0,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,1,1,1,1,1},
{1,1,1,0,1,1,1,1,1,1,1}};
int[] charpos;
String line = null;
int batterywidth;
boolean flashlight;
boolean left,right,up,down;
public AppWindow(int width, int height)
{
virtualMem = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
gBuffer = virtualMem.getGraphics();
wid = width;
hei = height;
batterywidth = 40;
g2D = (Graphics2D)gBuffer;
flashlight = false;
charpos = new int[3];
charpos[0] = 1;
charpos[1] = 4;
charpos[2] = 4;
cx = 225;
cy = 225;
bx1 = 0;
by1 = 0;
bx2 = -500;
by2 = 0;
bx3 = 0;
by3 = -500;
bx4 = -500;
by4 = -500;
left = true;
right = true;
up = true;
down = true;
addKeyListener(this);
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
updateBackground();
placeCharacter();
if(charpos[0] == 1)
{
canMoveLeft(maze11);
canMoveRight(maze11);
canMoveUp(maze11);
canMoveDown(maze11);
}
if(charpos[0] == 2)
{
canMoveLeft(maze22);
canMoveRight(maze22);
canMoveUp(maze22);
canMoveDown(maze22);
}
if(charpos[0] == 3)
{
canMoveLeft(maze33);
canMoveRight(maze33);
canMoveUp(maze33);
canMoveDown(maze33);
}
if(charpos[0] == 4)
{
canMoveLeft(maze44);
canMoveRight(maze44);
canMoveUp(maze44);
canMoveDown(maze44);
}
/*if(batterywidth >= 1)
{
theLights();
if(batterywidth == 15)
{
gBuffer.setColor(Color.white);
gBuffer.drawString("Looks like you are getting close to running out of batteries.",50,470);
gBuffer.drawString("Look around and see if you can find any around the maze.",50,480);
}
battery();
}
if(batterywidth < 1)
{
flashlight = false;
theLights();
gBuffer.setColor(Color.white);
gBuffer.drawString("You are out of batteries. Try finding some around the maze.",50,470);
gBuffer.drawString("They will be the only things you can see in the dark.",50,480);
battery();
}
extraBatteries();*/
g.drawImage(virtualMem, 0, 0, this);
repaint();
}
public void extraBatteries()
{
}
public void theLights()
{
/*Color blck = new Color(0,0,0,240);
Rectangle2D.Double darkness = new Rectangle2D.Double(0,0,500,500);
Area glow = new Area(darkness);
if(flashlight)
{
Ellipse2D.Double light = new Ellipse2D.Double(cx-100,cy-100, 200, 200);
Area shiny = new Area(light);
glow.subtract(shiny);
Color yllw = new Color(189,183,107,200);
g2D.setPaint(yllw);
g2D.fill(shiny);
}
g2D.setPaint(blck);
g2D.fill(glow);*/
}
public void battery()
{
if(flashlight)
{
long time = System.currentTimeMillis();
if(time % 500 == 0)
{
batterywidth --;
}
}
Color drkgrn = new Color(0,128,0,200);
Color lghtgrn = new Color(154,205,50,200);
Color yellow = new Color(255,215,0,200);
Color red = new Color(255,0,0,200);
if(batterywidth <= 40)
{
g2D.setPaint(drkgrn);
if(batterywidth <= 30)
{
g2D.setPaint(lghtgrn);
if(batterywidth <= 20)
{
g2D.setPaint(yellow);
if(batterywidth <= 10)
{
g2D.setPaint(red);
}
}
}
}
Rectangle2D.Double grn = new Rectangle2D.Double(420,440,batterywidth,20);
Area battery = new Area(grn);
g2D.fill(battery);
}
public void canMoveLeft(int[][] maze00)
{
if(charpos[2]-1 > -1 && charpos[1] > 0 && charpos[1] < 11 && charpos[2] < 11)
{
if(maze00[charpos[1]][charpos[2]-1] == 0)
{
left = true;
}
else
{
left = false;
}
}
else
{
if(charpos[2]-1 < 0)
{
charpos[2] = 11;
if(charpos[0] == 1)
{
charpos[0] = 2;
}
else
{
charpos[0] = 1;
}
}
if(charpos[2] >= 10)
{
charpos[2] = 1;
if(charpos[0] == 1)
{
charpos[0] = 2;
}
else
{
charpos[0] = 1;
}
}
}
}
public void canMoveRight(int[][] maze00)
{
if(charpos[2]+1 < 12 && charpos[1] > 0 && charpos[1] < 11 && charpos[2] > 0)
{
if(maze00[charpos[1]][charpos[2]+1] == 0)
{
right = true;
}
else
{
right = false;
}
}
else
{
if(charpos[2]-1 < 0)
{
charpos[2] = 11;
if(charpos[0] == 1)
{
charpos[0] = 2;
}
else
{
charpos[0] = 1;
}
}
if(charpos[2] >= 10)
{
charpos[2] = 1;
if(charpos[0] == 1)
{
charpos[0] = 2;
}
else
{
charpos[0] = 1;
}
}
}
}
public void canMoveUp(int[][] maze00)
{
if(charpos[1]-1 > -1 && charpos[2] > 0 && charpos[2] < 11 && charpos[1] < 11)
{
if(maze00[charpos[1]-1][charpos[2]] == 0)
{
up = true;
}
else
{
up = false;
}
}
else
{
if(charpos[1]-1 < 0)
{
charpos[1] = 11;
if(charpos[0] == 1)
{
charpos[0] = 3;
}
else
{
charpos[0] = 1;
}
}
if(charpos[1] >= 10)
{
charpos[1] = 1;
if(charpos[0] == 1)
{
charpos[0] = 3;
}
else
{
charpos[0] = 1;
}
}
}
}
public void canMoveDown(int[][] maze00)
{
if(charpos[1]+1 < 12 && charpos[2] > 0 && charpos[2] < 11 && charpos[1] > 0)
{
if(maze00[charpos[1]+1][charpos[2]] == 0)
{
down = true;
}
else
{
down = false;
}
}
else
{
if(charpos[1]-1 < 0)
{
charpos[1] = 11;
if(charpos[0] == 1)
{
charpos[0] = 3;
}
else
{
charpos[0] = 1;
}
}
if(charpos[1] >= 10)
{
charpos[1] = 1;
if(charpos[0] == 1)
{
charpos[0] = 3;
}
else
{
charpos[0] = 1;
}
}
}
}
public void updateBackground()
{
if(bx1 > 500)
{
bx1 = -500;
bx3 = -500;
}
if(bx2 > 500)
{
bx2 = -500;
bx4 = -500;
}
if(bx1 < -500)
{
bx1 = 500;
bx3 = 500;
}
if(bx2 < -500)
{
bx2 = 500;
bx4 = 500;
}
if(by1 > 500)
{
by1 = -500;
by2 = -500;
}
if(by3 > 500)
{
by3 = -500;
by4 = -500;
}
if(by1 < -500)
{
by1 = 500;
by2 = 500;
}
if(by3 < -500)
{
by3 = 500;
by4 = 500;
}
drawFile(bx1,by1,maze11);
drawFile(bx2,by2,maze22);
drawFile(bx3,by3,maze33);
drawFile(bx4,by4,maze44);
}
public void drawFile(int x, int y, int[][] maze00)
{
for(int i = 0; i < maze00.length; i ++)
{
for(int ii = 0; ii < maze00[i].length; ii++)
{
if(maze00[i][ii] == 1)
{
gBuffer.setColor(Grfx.black);
}
if(maze00[i][ii] == 0)
{
gBuffer.setColor(Grfx.white);
}
gBuffer.fillRect(x + ii*50, y + i*50, 50, 50);
}
}
}
public void placeCharacter()
{
gBuffer.setColor(Grfx.red);
gBuffer.fillOval(cx-10,cy-10,20,20);
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{
int buff1 = bx1;
if(left)
{
bx1+=50;
bx2+=50;
bx3+=50;
bx4+=50;
charpos[2]--;
}
}
if (key == KeyEvent.VK_RIGHT)
{
int buff1 = bx1;
if(right)
{
bx1-=50;
bx2-=50;
bx3-=50;
bx4-=50;
charpos[2]++;
}
}
if (key == KeyEvent.VK_DOWN)
{
if(down)
{
by1-=50;
by2-=50;
by3-=50;
by4-=50;
charpos[1] ++;
}
}
if (key == KeyEvent.VK_UP)
{
if(up)
{
by1+=50;
by2+=50;
by3+=50;
by4+=50;
charpos[1] --;
}
}
if (key == KeyEvent.VK_SPACE)
{
if(flashlight)
{
flashlight = false;
}
else
{
flashlight = true;
}
}
if (key == KeyEvent.VK_ESCAPE)
{
}
}
}

java game development restricted number randomly objects

Im creating a game. I need to create objects randomly but i want them to come in a certain number. Here is my main class code for randomly created object
private void randomTiles() {
int randomXtile = new Random().nextInt(9500) + 20;
int randomYtile = new Random().nextInt(12) + 0;
Tile t = new Tile(randomXtile, randomYtile, 3);
tilearray.add(t);
}
private void updateTiles() {
randomTiles();
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
t.update();
}
}
private void paintTiles(Graphics g) {
for (int i = 0; i < tilearray.size(); i++) {
Tile t = (Tile) tilearray.get(i);
g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);
}
}
tile constructor is
public Tile(int x, int y, int typeInt) {
tileX = x * 40;
tileY = y * 40;
type = typeInt;
r = new Rectangle();
if (type == 5) {
tileImage = StartingClass.tiledirt;
} else if (type == 8) {
tileImage = StartingClass.tilegrassTop;
} else if (type == 4) {
tileImage = StartingClass.tilegrassLeft;
} else if (type == 6) {
tileImage = StartingClass.tilegrassRight;
} else if (type == 2) {
tileImage = StartingClass.tilegrassBot;
} else if (type == 3) {
tileImage = StartingClass.ice;
hp = 2;
} else {
type = 0;
}
}
and somewhere in my game object should come at certain coordinates. Can you help me about this ?

2d array of objects

im really new in Java. I just need to explain how to declare 2D array of objects, i have something like:
package breakout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
public class Breakout extends JPanel {
public class Ball {
private
int x = 400;
int y = 300;
int speed = 2;
int dirx = 1;
int diry = -1;
public
void bounce(int px, int py, int lx, int ly) {
if ((x + 10 >= 800 && dirx == 1) || (x <= 0 && dirx == -1))
dirx *= -1;
if (y <= 0 && diry == -1)
diry *= -1;
if (y + 10 >= py && y <= py + ly && diry == 1 && x + 10 >= px && x <= px + lx)
diry *= -1;
}
int getX() {
return x;
}
int getY() {
return y;
}
void setDirx(){
dirx *= -1;
}
void setDiry(){
diry *= -1;
}
void move() {
x += speed*dirx;
y += speed*diry;
}
void paint(Graphics2D g) {
g.fillOval(x,y,10,10);
}
}
public class Paddle {
private
int x = 400;
int y = 520;
int width = 100;
int height = 6;
int speed = 6;
int dirL = 0;
int dirR = 0;
public
void move() {
x -= speed*dirL;
x += speed*dirR;
}
void stop() {
if (x <= 0)
x = 0;
if (x + width >= 800)
x = 800 - width;
}
int getX() {
return x;
}
int getY() {
return y;
}
int getWidth() {
return width;
}
int getHeight() {
return height;
}
void paint(Graphics2D g) {
g.fillRect(x,y,width,height);
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
dirL = 0;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
dirR = 0;
else {
dirL = 0;
dirR = 0;
}
}
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
dirL = 1;
break;
case KeyEvent.VK_RIGHT:
dirR = 1;
break;
}
}
}
public class Brick {
private
int x;
int y;
int width;
int height;
boolean alive;
boolean inX = false,inY = false;
public
void setUpBrick(int px, int py, int w, int h, boolean al) {
x = px;
y = py;
width = w;
height = h;
alive = al;
}
void setAlive(boolean alive) {
this.alive = alive;
}
void paint(Graphics2D g) {
if (alive)
g.fillRect(x,y,width,height);
}
boolean collision(int bx, int by) {
if (alive) {
if (bx + 10 >= x && bx <= x + width && by + 10 >= y && by <= y + height) {
setAlive(false);
return true;
} else return false;
}
else return false;
}
void inAreaX(int bx) {
if (bx + 10 >= x && bx <= x + width) {
System.out.println("inAreaX");
inX = true;
} else {
inX = false;
}
}
void inAreaY(int by) {
if (by + 10 >= y && by <= y + height) {
System.out.println("inAreaY");
inY = true;
} else {
inY = false;
}
}
boolean isInAreaX () {
if (inX)
return true;
else return false;
}
boolean isInAreaY () {
if (inY)
return true;
else return false;
}
}
Ball ball = new Ball();
Paddle paddle = new Paddle();
Brick[][] brick = new Brick[8][4];
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 4; j++) {
brick[i][j].setUpBrick(j * 101, i * 51, 100, 50, true);
}
}
void bounce() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 4; j++) {
brick[i][j].inAreaX(ball.getX());
brick[i][j].inAreaY(ball.getY());
if (brick[i][j].collision(ball.getX(), ball.getY())) {
if (brick[i][j].isInAreaX()) {
ball.setDiry();
} else if (brick[i][j].isInAreaY()) {
ball.setDirx();
}
}
}
}
}
void move() {
ball.bounce(paddle.getX(), paddle.getY(), paddle.getWidth(),paddle.getHeight());
ball.move();
paddle.move();
paddle.stop();
bounce();
}
public Breakout() {
addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
paddle.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
paddle.keyPressed(e);
}
});
setFocusable(true);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
ball.paint(g2d);
g2d.setColor(Color.BLACK);
paddle.paint(g2d);
g2d.setColor(Color.ORANGE);
for (int i = 0; i < 8; i++)
for (int j = 0; j < 4; j++)
brick[i][j].paint(g2d);
}
public static void main(String[] args) throws InterruptedException {
JFrame window = new JFrame("Tennis");
Breakout game = new Breakout();
window.add(game);
window.setSize(800,600);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(10);
}
}
i need to inicialize 2d array of brick, but it says that first for is unexpected token. How to write it? Thank you.
Unless if I have miscounted your opening and closing braces, your for loop is not inside any method, it's directly in your class body. That's why you're getting unexpected token. You will probably want to move it into the Breakout constructor.
In order to create a 2D array in Java, you can create such an array like this:
Object testArray = new Object[10][10];
This array is now a 10*10 array with memory allocated for 100 Object references.
You can create pointers two Objects with a double for-loop:
for (int i = 0; i < testArray.length(); i++) {
for (int j = 0; j < testArray.length; j++) {
testArray[i][j] = Object; //here you input the objects that you want to point to
}
}
Move the logic from setUpBrick to a constructor.
public class Brick {
private int x;
private int y;
private int width;
private int height;
private boolean alive;
private boolean inX = false,inY = false;
public Brick(int px, int py, int w, int h, boolean al) {
x = px;
y = py;
width = w;
height = h;
alive = al;
}
...
}
Then change
brick[i][j].setUpBrick(j * 101, i * 51, 100, 50, true);
to
brick[i][j] = new Brick(j*101, i*51, 100, 50, true);
Also note that access modifiers don't apply to a whole section of your class. In your example,
private
int x;
int y;
int width;
int height;
boolean alive;
boolean inX = false,inY = false;
means that only x is going to be private. The rest of the members will get the default access modifier.
One more tip. A couple of your methods can be simplified.
boolean isInAreaY () {
if (inY)
return true;
else return false;
}
can be written as:
boolean isInAreaY() {
return inY;
}

Categories

Resources