How to pick specific parts of a Shape3D shape (processing) - java

I am attempting to make a voxel-ish world builder, and I need to be able to stack the different blocks. How can I pick the separate sides of the block with the shapes3d library. Whenever I pick the shape, it renders it as the entire shape, and I am unsure of how to select only the part that I would like, so that I can build upon it.
import peasy.*;
import shapes3d.*;
import shapes3d.utils.*;
Shape3D picked = null;
boolean clicked = true;
PeasyCam cam;
float[] xArr,yArr,zArr;
float x,y,z;
Box[] boxArr;
color[] colArr;
CameraState defaultState;
void setup(){
size(1200,800,P3D);
cam = new PeasyCam(this,width/2,height/2,0,500);
cam.setMinimumDistance(200);
cam.setMaximumDistance(2000);
cam.setWheelScale(.05);
cam.setDistance(1000);
cam.rotateZ(PI/4);
cam.rotateX(-PI/3);
cam.setResetOnDoubleClick(false);
defaultState = cam.getState();
x=width/2;
y=height/2;
z=0;
xArr = new float[200];
yArr = new float[200];
zArr = new float[200];
colArr = new color[200];
boxArr= new Box[200];
for(int i=0;i<boxArr.length;i++){
boxArr[i]=null;
}
xArr[0]=x;
yArr[0]=y;
zArr[0]=z;
boxArr[0]=new Box(this);
colArr[0]=color(255,255,255);
}
final float xrot=-PI/8,yrot=PI/4,zrot=0;
color col = color(255,255,255);
void mouseClicked(){
clicked=true;
}
void draw(){
pushMatrix();
if (keyPressed&&key=='r'){
cam.setState(defaultState);
cam.setDistance(1000);
}
background(213, 243, 245);
ambientLight(200,200,200);
fill(col);
lights();
directionalLight(100,100,100,50,-50,0);
int actuallength=0;
for (int i=0;i<boxArr.length;i++){
if(boxArr[i]!=null){
actuallength++;
}
}
for(int i = 0; i<actuallength; i++){
boxArr[i].fill(colArr[i]);
boxArr[i].strokeWeight(1.75);
boxArr[i].stroke(155);
boxArr[i].moveTo(xArr[i],yArr[i],zArr[i]);
boxArr[i].drawMode(Shape3D.SOLID|Shape3D.WIRE);
boxArr[i].draw();
}
if (clicked){
clicked=false;
picked = Shape3D.pickShape(this, mouseX, mouseY);
int pos=0;
for(int i=0;i<boxArr.length;i++){
if(boxArr[i]==picked){
pos=i;
}
}
if(picked!=null){
println();
boxArr[actuallength]=new Box(this);
xArr[actuallength]=xArr[pos]+(100);
yArr[actuallength]=yArr[pos];
zArr[actuallength]=zArr[pos];
colArr[actuallength]=color(255,255,255);
}
}
popMatrix();
}

Related

chess placing algorithm in java wont work

I'm making a chess program for a school project using swing. this is my first time using swing however I've had a lot of experience with tkinter in python which feels similar. I've gotten the pieces loaded onto board and can load in FEN strings.
The basic board when loaded in
Now I've been trying to move on to allowing the player to capture other pieces. currently I'm not worried about the rules of how pieces can move and I'm just trying to allow them to capture anything.
A little bit of extra knowledge that may be useful is that I have two 2d arrays for the board. one contains a 2d array of 64 buttons (one for each square). the other contains a 2d int array and contains the numerical value of each piece in each square.
the following code is my code for attempting to capture pieces. My thinking behind this implementation is to first find when we select a piece that we want to move. when we click on this piece we store it in selected and set isSelecting equal to true. then the next piece we click on we should capture. The way I've been trying to tackle this is by finding the square we want to capture and changing the piece icon to the icon of the piece we stored in selected. then setting the selected pieces icon to a empty icon. then doing the same for the int array.
public boolean isSelecting;
public JButton selected;
public int[] findSpot(JButton but){
for (int i = 0 ; i < board.length; i++)
for (int j = 0 ; j < board.length; j++)
{
if ( board[i][j] == but)
{
return new int[]{i,j};
}
}
return new int[]{-1,-1};
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println(1);
System.out.println(isSelecting);
if (!isSelecting) {
System.out.println(2);
selected = (JButton) e.getSource();
System.out.println(e.getSource());
} else {
System.out.println(3);
int[] temp = findSpot(selected);
ImageIcon i = new ImageIcon(pieceFiles.get(intBoard[temp[0]][temp[1]]));
Image img = i.getImage() ;
Image newimg = img.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH ) ;
i = new ImageIcon( newimg );
((JButton) e.getSource()).setIcon(i);
int[]temp2 = findSpot(((JButton) e.getSource()));
intBoard[temp[0]][temp[1]] = intBoard[temp2[0]][temp2[1]];
selected.setIcon(new ImageIcon());
intBoard[temp[0]][temp[1]] = none;
selected = null;
}
isSelecting = !isSelecting;
}
This code, however, isn't working and I can't figure out why. The specific problem is the isSelecting variable on becomes false when you click the same piece twice. Clicking two separate pieces does nothing however clicking the same piece twice removes said piece.
The output after clicking the first three pawns
The output after clicking those three pawns for a second time
I'm going to leave my full code here. I'm not sure if I should since it's long but I hope it can give you a better scope of the project.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Hashtable;
import javax.swing.*;
public class Chess implements MouseListener {
static int none = 0;
static int king = 1;
static int pawn = 2;
static int knight = 3;
static int bishop = 4;
static int rook = 5;
static int queen = 6;
static int black = 8;
static int white = 16;
public boolean isSelecting;
public JButton selected;
static JButton[][] board = new JButton[8][8];
static int[][] intBoard = new int[8][8];
static JFrame frame = new JFrame("Big Willy's Chess");
static Hashtable<Integer, String> pieceFiles = new Hashtable<>();
public static void cTable() {
String folder = "C:\\Users\\bookr\\IdeaProjects\\CSA\\src\\pieces";
pieceFiles.put(king + black, folder + "\\Chess_kdt60.png");
pieceFiles.put(king + white, folder + "\\Chess_klt60.png");
pieceFiles.put(pawn + black, folder + "\\Chess_pdt60.png");
pieceFiles.put(pawn + white, folder + "\\Chess_plt60.png");
pieceFiles.put(knight + black, folder + "\\Chess_ndt60.png");
pieceFiles.put(knight + white, folder + "\\Chess_nlt60.png");
pieceFiles.put(bishop + black, folder + "\\Chess_bdt60.png");
pieceFiles.put(bishop + white, folder + "\\Chess_blt60.png");
pieceFiles.put(rook + black, folder + "\\Chess_rdt60.png");
pieceFiles.put(rook + white, folder + "\\Chess_rlt60.png");
pieceFiles.put(queen + black, folder + "\\Chess_qdt60.png");
pieceFiles.put(queen + white, folder + "\\Chess_qlt60.png");
}
public static boolean isNumeric(String str) {
try {
Double.parseDouble(str);
return true;
} catch(NumberFormatException e) {
return false;
}
}
public static void loadFenPos(String fen){
Hashtable<String, Integer> pieceNumbs = new Hashtable<>();
pieceNumbs.put("k", king);
pieceNumbs.put("p", pawn);
pieceNumbs.put("n", knight);
pieceNumbs.put("b", bishop);
pieceNumbs.put("r", rook);
pieceNumbs.put("q", queen);
int rank = 0;
int file = 0;
for (String symbol:fen.split("")) {
if (symbol.equals("/")) {
file = 0;
rank++;
}
else {
if (!isNumeric(symbol)) {
int pieceColor = Character.isUpperCase(symbol.charAt(0)) ? white : black;
int pieceType = pieceNumbs.get(symbol.toLowerCase());
ImageIcon i = new ImageIcon(pieceFiles.get(pieceType+pieceColor));
Image img = i.getImage();
Image newimg = img.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH);
i = new ImageIcon(newimg);
intBoard[rank][file] = pieceType+pieceColor;
board[rank][file].setIcon(i);
file++;
} else {
file += Integer.parseInt(symbol);
}
}
}
}
public void start (){
cTable();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 8));
Color lightSquareColor = new Color(240, 240, 240);
Color darkSquareColor = new Color(128, 128, 128);
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
JButton button = new JButton();
button.setOpaque(true);
button.setBorderPainted(false);
button.setFocusPainted(false);
if ((row + col) % 2 == 0) {
button.setBackground(lightSquareColor);
} else {
button.setBackground(darkSquareColor);
}
button.addMouseListener(new Chess());
panel.add(button);
board[row][col] = button;
}
}
// ImageIcon i = new ImageIcon("C:\\Users\\bookr\\IdeaProjects\\CSA\\src\\pawn.png");
//
//
// Image img = i.getImage() ;
// Image newimg = img.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH ) ;
// i = new ImageIcon( newimg );
// board[6][7].setIcon(i);
loadFenPos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR");
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(600, 600);
frame.setVisible(true);
}
public static void main(String[] args) {
Chess game = new Chess();
game.start();
}
public int[] findSpot(JButton but) {
for (int i = 0 ; i < board.length; i++)
for(int j = 0 ; j < board.length; j++)
{
if ( board[i][j] == but)
{
return new int[]{i,j};
}
}
return new int[]{-1,-1};
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println(1);
System.out.println(isSelecting);
if (!isSelecting) {
System.out.println(2);
selected = (JButton) e.getSource();
} else {
System.out.println(3);
int[] temp = findSpot(selected);
ImageIcon i = new ImageIcon(pieceFiles.get(intBoard[temp[0]][temp[1]]));
Image img = i.getImage() ;
Image newimg = img.getScaledInstance(75, 75, java.awt.Image.SCALE_SMOOTH ) ;
i = new ImageIcon( newimg );
((JButton) e.getSource()).setIcon(i);
int[]temp2 = findSpot(((JButton) e.getSource()));
intBoard[temp[0]][temp[1]] = intBoard[temp2[0]][temp2[1]];
selected.setIcon(new ImageIcon());
intBoard[temp[0]][temp[1]] = none;
selected = null;
}
isSelecting = !isSelecting;
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
I've tried messing changing around the isSelecting variable, how I assign the selected variable, and how I update the 2d arrays.

Java Asteroids game how to be able to fire multiple shots without having the first shot disappear?

So for my final in Java class, we are making an Asteroid game (except a simpler version that the official one, because not enough time).
The problem is when our ship fires a shot (SPACE bar) we add(shot, x, y), but then when we click SPACE bar again it just takes that shot and puts it back to original x, y. So right now we can only fire off one shot at a time to be on the screen. We would like to be able to be able to fire off multiple shots and have them all be visible and stuff.
Not sure how to do that though. Any help is welcome thank you.
P.S. if needed i will add our code.
P.S.S. sorry for posting this again i thought i could edit the post later, thats why i didn't include the code but apparently not.
package week7Homework;
import acm.program.GraphicsProgram;
import java.util.*;
import java.awt.event.*;
import acm.graphics.*;
import java.awt.Color;
import java.awt.Image;
public class space8bit extends GraphicsProgram
{
/* Initialize everything that is needed */
final int WIN_HEIGHT = 800;
final int WIN_WIDTH = 1900;
GImage space = new GImage("/College/IT219/Week7/src/week7Homework/outerspace.png");
GImage ship = new GImage("/College/IT219/Week7/src/week7Homework/ship.png");
GImage explosion = new GImage("/College/IT219/Week7/src/week7Homework/explosion.png");
GImage [] ast = new GImage[6];
Random rand = new Random();
pewpew shots = new pewpew();
int shipx;
int shipy;
public void init()
{
setSize(WIN_WIDTH, WIN_HEIGHT);
add(space);
ship.setLocation(50,330);
ship.scale(.8);
add(ship);
addKeyListeners( );
//scale explosion
explosion.scale(.5);
}
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode( );
if (key == KeyEvent.VK_UP)
{ ship.move(0, -15); }
/*else if (key == KeyEvent.VK_SPACE)
{ xMove = MV_AMT; }*/
else if (key == KeyEvent.VK_DOWN)
{ ship.move(0, 15); }
else if (key == KeyEvent.VK_SPACE)
{shipx = (int)ship.getX()+195;
shipy = (int)ship.getY() + 80;
add(shots,shipx,shipy);
}
}
public void asteriods()
{
GImage ast1 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1300,100);
GImage ast2 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1750,250);
GImage ast3 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1650,350);
GImage ast4 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1550,650);
GImage ast5 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1450,600);
GImage ast6 = new GImage("/College/IT219/Week7/src/week7Homework/asteriod.png",1350,750);
ast [0] = ast1;
ast [1] = ast2;
ast [2] = ast3;
ast [3] = ast4;
ast [4] = ast5;
ast [5] = ast6;
add(ast[0]);
add(ast[1]);
add(ast[2]);
add(ast[3]);
add(ast[4]);
add(ast[5]);
}
public void run()
{
asteriods();
while(true)
{
pause(120);
int random1x = rand.nextInt(-1+1+6)-9;
int random2x = rand.nextInt(-1+1+6)-15;
int random3x = rand.nextInt(-1+1+6)-25;
int random4x = rand.nextInt(-1+1+6)-16;
int random5x = rand.nextInt(-1+1+6)-8;
int random6x = rand.nextInt(-1+1+6)-13;
ast[0].move(random1x, 0);
ast[1].move(random2x, 0);
ast[2].move(random3x, 0);
ast[3].move(random4x, 0);
ast[4].move(random5x, 0);
ast[5].move(random6x, 0);
shots.move(50, 0);
for (int i = 0; i < ast.length; i++)
{
//integer that gets bounds of all rectangles and ovals in the arrays.
GRectangle asteroidBounds = ast[i].getBounds();
//check for collision with other objects
if (shots.getBounds().intersects(asteroidBounds))
{
int shotX = (int)shots.getX();
int shotY = (int)shots.getY();
pause(10);
remove(ast[i]);
add(explosion, shotX-100, shotY - 50);
remove(shots);
pause(25);
remove(explosion);
}
else if (ship.getY() <= 0)
{
ship.move(0, 15);
}
else if (ship.getY() >= WIN_HEIGHT - 168)
{
ship.move(0, -15);
}
}
}
}
}
ALSO HERE IS A SAMPLE CODE, much shorter but does the same thing. Just press SPACEBAR and you will see what im talking about.
package week7Homework;
import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import java.awt.event.*;
public class collisionTry extends GraphicsProgram
{
final int WIN_WIDTH = 500;
final int WIN_HEIGHT = 500;
GOval ship = new GOval(100, 250, 50, 50);
GImage bullet = new GImage("/College/IT219/Week7/src/week7Homework/bullet.gif", 50, 50);
GImage bullet2;
boolean bulletFired;
public void init()
{
setSize(WIN_WIDTH, WIN_HEIGHT);
addKeyListeners();
}
public void run()
{
GRect rect = new GRect(400, 200, 50, 150);
add(rect);
rect.setColor(Color.BLACK);
rect.setFilled(true);
add(ship);
ship.setColor(Color.BLACK);
ship.setFilled(true);
while (true)
{
pause(50);
rect.move(-1, 0);
//bullet.move(5, 0);
if (bulletFired == true)
{
bullet.move(5, 0);
}
if (bullet.getBounds().intersects(rect.getBounds()))
{
remove(rect);
remove(bullet);
}
}
}//run
public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(key == KeyEvent.VK_SPACE)
{
int shipX = (int)ship.getX();
int shipY = (int)ship.getY();
add(bullet, shipX+50, shipY+25);
bulletFired = true;
}
else if (key == KeyEvent.VK_UP){
ship.move(0, -5);
}
}
}
It's 'cause you only have 1 bullet in the entire game
if (bulletFired == true) {
bullet.move(5, 0);
}
You're telling that one bullet to go back to (5, 0)
You need to find some way of making a new bullet object each time you press space:
if (key == KeyEvent.VK_SPACE) {
int shipX = (int)ship.getX();
int shipY = (int)ship.getY();
Bullet firedBullet = new Bullet(/* params if any, x? y? */);
add(firedBullet, shipX+50, shipY+25);
bulletFired = true;
}
Though this is my vision of how I'd do things, which probably won't work with your game (I don't know what classes you have, their roles etc). But hopefully you can see what I'm getting at and adapt it.
Now because you have multiple bullets, you also have to take care of their lifetimes. You fired 1000 bullets at the start of the game, they go off-screen. You don't want to waste time drawing them for the rest of the game. So whatever list/array you're using to keep track of objects to draw, you gotta periodically find and remove the ones that have gone off-screen.

Java Object values not consistent

I couldn't find any other solutions to my problem because I'm unsure of how to describe it in few enough words.
When I assign activeList, which is a field of currentActiveList a randomly generated Rectangle in the ActiveList class it receives the value just fine.
public class ActiveList {
Rectangle[] activeList = new Rectangle[10];
public ActiveList() {
for(int i = 0; i < activeList.length; i++)
activeList[i] = null;
}
public void addToList(Rectangle x) {
for(int i = 0; i < this.activeList.length; i++) {
if(this.activeList[i] == null) {
this.activeList[i] = x;
i = this.activeList.length+1;
}
else
this.activeList[activeList.length-1] = x;
}
}
public Rectangle[] getActiveList() {
return this.activeList;
}
public int getLength() {
//System.out.print(this.activeList.length);
return this.activeList.length;
}
public void deleteFromList(int x) {
this.activeList[x] = null;
}
public Rectangle getFromList(int x) {
Rectangle retVal = this.activeList[x];
//System.out.println("Returning getFromList(int x): " +retVal);
return retVal;
}
public void genRandomRectangle() {
Random randomNumberGenerator = new Random();
double[] pointVal = new double[4];
double randomInt = randomNumberGenerator.nextInt(400-10);
pointVal[0] = randomInt;
randomInt = randomNumberGenerator.nextInt(400-10);
pointVal[1] = randomInt;
randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[0]));
if(randomInt < 5) {
randomInt = randomInt+pointVal[0]+5;
}
else
pointVal[2] = randomInt+pointVal[0];
randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[1]));
if(randomInt < 5) {
randomInt = randomInt+pointVal[1]+5;
}
else
pointVal[3] = randomInt+pointVal[1];
Rectangle newRandom = new Rectangle(pointVal[0], pointVal[1], pointVal[2], pointVal[3]);
//System.out.println(pointVal[0]);
//System.out.println(pointVal[1]);
//System.out.println(pointVal[2]);
//System.out.println(pointVal[3]);
System.out.println("New Random: " +newRandom);
addToList(newRandom);
}
}
However, when I try to use those values in my main class GraphicGen, the currentActiveList returns null values for all of its indexes.
public class GraphicGen extends JPanel {
ActiveList currentActiveList = new ActiveList();
public static int gridSpaceX = 400;
public static int gridSpaceY = 400;
static JFrame mainFrame = new JFrame();
protected void paintComponent(Graphics g) {
//super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//int w = getWidth();
//int h = getHeight();
// Draw ordinate.
//g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
// Draw abcissa.
//g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
//double xInc = (double)(w - 2*PAD)/(data.length-1);
//double scale = (double)(h - 2*PAD)/maxValue();
// Mark data points.
//g2.setPaint(Color.red);
double[] coords = new double[4];
//g2.fill(new Ellipse2D.Double(coords[0], coords[1], 4, 4));
//g2.fill(new Ellipse2D.Double(coords[2], coords[3], 4, 4));
//g2.fill(new Ellipse2D.Double(100, 100, 4, 4));
System.out.println("Graphic Gen Active List Obj: " +currentActiveList);
System.out.println("Ya drew a new Main GUI!");
System.out.println("currentActiveList.getActiveList(): " +currentActiveList.getActiveList());
for(int i = 0; i < currentActiveList.getLength(); i++) {
//System.out.println("currentActiveList.getFromList(i): "+currentActiveList.getFromList(i));
//System.out.println("Graphic Gen Active List Obj: " +currentActiveList);
//System.out.println(activeList.getFromList(i).getTopLeftX());
if(currentActiveList.getFromList(i) != null) {
coords[0] = currentActiveList.getFromList(i).getTopLeftX();
System.out.println(coords[0]);
coords[1] = currentActiveList.getFromList(i).getTopLeftY();
System.out.println(coords[1]);
coords[2] = currentActiveList.getFromList(i).getBottomRightX();
System.out.println(coords[2]);
coords[3] = currentActiveList.getFromList(i).getBottomRightY();
System.out.println(coords[3]);
g2.draw(new Line2D.Double(coords[0], coords[1], coords[2], coords[1]));
g2.draw(new Line2D.Double(coords[0], coords[1], coords[0], coords[3]));
g2.draw(new Line2D.Double(coords[2], coords[1], coords[2], coords[3]));
g2.draw(new Line2D.Double(coords[0], coords[3], coords[2], coords[3]));
}
}
/*double x = 50;
double y = 50;
g2.fill(new Ellipse2D.Double(x, y, 4, 4));*/
/*for(int i = 0; i < data.length; i++) {
double x = PAD + i*xInc;
double y = h - PAD - scale*data[i];
g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
}*/
}
/*private int maxValue() {
int max = data[0];
for(int i = 0; i < data.length; i++) {
if(data[i] > max)
max = data[i];
}
return max;
}*/
public void callRepaintOnMain() {
mainFrame.repaint();
}
public void callGenRandom() {
currentActiveList.genRandomRectangle();
}
public static void main(String[] args) {
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new GraphicGen());
mainFrame.setSize(gridSpaceX, gridSpaceY);
ButtonPrompt buttonPrompter = new ButtonPrompt();
mainFrame.setLocation(200,200);
mainFrame.setVisible(true);
}
}
The random generator method is called by the action listener.
public class ButtonPrompt extends GraphicGen {
ActionListener actionListenerRandom = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//currentActiveList.genRandomRectangle();
callGenRandom();
callRepaintOnMain();
}
};
JButton randomBtn = new JButton("Add Random Rectangle");
JButton inputCoordinates = new JButton("Input Rectangle Coordinates");
public ButtonPrompt() {
JFrame f = new JFrame("Add Rectangles");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoxLayout boxLayout = new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS);
f.setLayout(boxLayout);
randomBtn.addActionListener(actionListenerRandom);
f.setSize(200, 200);
f.setLocation(600, 200);
f.setVisible(true);
f.add(randomBtn);
f.add(inputCoordinates);
f.pack();
}
}
Is this a scoping or referencing problem? I'm really at a loss here.
Here:
public static void main(String[] args) {
...
mainFrame.add(new GraphicGen());
...
ButtonPrompt buttonPrompter = new ButtonPrompt();
}
ButtonPrompt extends GraphicGen, which is a JPanel. In ButtonPrompt's constructor, you created a JFrame and added two JButtons to it.
So when your app starts, there will be two JFrames on the screen, one is mainFrame which contains a GraphicGen, the other is buttonPrompter which contains two buttons.
When you click on the button, the actionPerformed() is called and it's actually calling the callGenRandom() of the buttonPrompter -- if the random generation logic is correct, the generated Rectangles are added to buttonPrompter. But you didn't add this buttonPrompter to any one of the JFrames, you won't see it.
What you may want:
ButtonPrompt doesn't extend GraphicGen, instead, give ButtonPrompt a reference of the GraphicGen you added to the mainFrame.
public class ButtonPrompt extends GraphicGen {
JButton randomBtn = new JButton("Add Random Rectangle");
JButton inputCoordinates = new JButton("Input Rectangle Coordinates");
final GraphicGen gg;
public ButtonPrompt(GraphicGen gg) {
this.gg = gg;
......
ActionListener actionListenerRandom = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
gg.callGenRandom();
gg.callRepaintOnMain();
}
};
randomBtn.addActionListener(actionListenerRandom);
......
}
}
and in your main():
public static void main(String[] args) {
...
GraphicGen gg = new GraphicGen();
mainFrame.add(gg);
...
ButtonPrompt buttonPrompter = new ButtonPrompt(gg);
}
What's more, the code has other problems.
For example, GraphicGen is a JPanel, main class and it has a field of a JFrame which actually contains the GraphicGen instance when app runs -- this looks bad. I don't know much of Swing... Is it a must to call the containing JFrame's repaint() instead of just calling the JPanel's repaint(), if it has?
Your actual problem is quite unclear, but just reading the first two methods is enough to find what, I suppose, is a bug:
public ActiveList() {
for(int i = 0; i < activeList.length; i++)
activeList[i] = null;
}
the above code is completely useless. The default value of an element of an array of objects is null. So the loop assigns null to a variable wich is already null.
public void addToList(Rectangle x) {
for(int i = 0; i < this.activeList.length; i++) {
if(this.activeList[i] == null) {
this.activeList[i] = x;
i = this.activeList.length+1;
}
else
this.activeList[activeList.length-1] = x;
}
}
If your list only contains null, the rectangle will be stored at index 0, and the loop will stop. For all the susequent calls to this method, the loop will find that the element at index 0 is not null, and will thus store x at the last index of the array, and then at the first non-null index.
I don't know exactly what you're trying to achieve, and what the actual problem is, but you should probably forget about implementing your own list based on an array, and use an ArrayList instead.

getting nullPointerException on simple game

I am making a simple rpg game and i have been trying to add enemies to the game. It is loading in the enemy find with all it's stats, but when i try to render it, i get Exception in thread "Thread-2" java.lang.NullPointerException
at com.hosfordryan.tileRPG.entities.Enemy.render(Enemy.java:52)
at com.hosfordryan.tileRPG.Game.render(Game.java:134)
at com.hosfordryan.tileRPG.Game.run(Game.java:103)
at java.lang.Thread.run(Unknown Source)
. I have used JOptionPanes to confirm that the enemies are saving in the arrayList, so that can't be it. Code for reading in enemy is:
public static void loadEnemies() {
Scanner qwe;
try {
qwe = new Scanner(new File("enemyStats.txt"));
while (qwe.hasNextLine()) {
String name = qwe.nextLine();
String origin = qwe.nextLine();
String weapon = qwe.nextLine();
String gear = qwe.nextLine();
String spec = qwe.nextLine();
int hp = qwe.nextInt();
int att = qwe.nextInt();
int def = qwe.nextInt();
int randX = (int) (Math.random()*(20*SCALE*TILESIZE)); //Give random x coordinate
int randY = (int) (Math.random()*(20*SCALE*TILESIZE)); //Give random y coordinate
if(qwe.hasNextLine()){
qwe.nextLine();
}
enemies.add(new Enemy(randX,randY,im,name,origin,weapon,gear,spec,hp,att,def)); //adds enemy into arrayList
String temp = "";
temp+=enemies.get(enemies.size()-1).getName()+"\n"+enemies.get(enemies.size()-1).getRx(); //checking if saving into arrayList correctly
JOptionPane.showMessageDialog(null, temp);
}
for(int i = 0; i < enemies.size();i++){ //adds enemy to arrayList to be rendered
enemiestoRend.add( new Enemy(enemies.get(i).getRx(),enemies.get(i).getRy(),im,enemies.get(i).getName(),enemies.get(i).getOrigin(),enemies.get(i).getWeapon(),enemies.get(i).getGear(),enemies.get(i).getSpecialMove(),enemies.get(i).gethp()
,enemies.get(i).getAttack(),enemies.get(i).getDefense()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Code for rendering:
public void render(Graphics g){
g.drawImage(im.enemy, this.x*Game.TILESIZE * Game.SCALE, this.x*Game.TILESIZE * Game.SCALE, Game.TILESIZE * Game.SCALE,
Game.TILESIZE * Game.SCALE, null);
}
Render method in main which renders everything:
public void render(){
BufferStrategy bs = this.getBufferStrategy();
if (bs==null) {
createBufferStrategy(3);
return;
}
Graphics g= bs.getDrawGraphics();
//Render Here
else if(Player.l1){
l1.render(g);
}
for(int i = 0; i < enemies.size();i++){
enemies.get(i).render(g);
}
for(int i = 0; i < enemiestoRend.size();i++){
enemiestoRend.get(i).render(g); //problem here
}
player.render(g);
//End Render
g.dispose();
bs.show();
}

Starting and Stopping boolean() function

I'm attemping to use this code from http://www.openprocessing.org/sketch/7050 to make countries formed using the letters from the name of whatever the country is. But I want to make it so once the user presses the right arrow key, the process will start over again, but instead, created a new country and use the letters of that country. I'm a little stuck- what I have makes it so when you press the right arrow key, it begins to make the next country from where ever the previous function left off. Is there a way to make it so it just starts over instead?
PFont font;
String fontpath = "ArialMT-200.vlw";
int fontstart = 300;
int fontend = 8;
float fontsize = fontstart;
float fontsizedecrease = 0.97;
PImage bg;
PImage australia;
String country1 = "australia.jpg";
String country2 = "austria.jpg";
String letters = "Australia";
char[] chars = new char[52];
int nchars = 0;
int iterations = 500;
int c = 0;
PGraphics letter,lettersquare,drawing;
void setup(){
//initialize the sketch
size(900,600);
//background(255);
//initialize the font
//font = loadFont(fontpath);
///*
for(int i=0;i<letters.length();i++){
boolean found = false;
char lc = letters.charAt(i);
for(int j=0;j<nchars;j++){
if(chars[j]==lc){
found = true;
break;
}
}
if(!found) chars[nchars++] = lc;
}
chars = (char[]) subset(chars,0,nchars);
font = createFont("Arial",200,true,chars);
//*/
textAlign(CENTER,CENTER);
//load the image that will be filled with letters
australia = loadImage(country1);
austria = loadImage(country2);
//france = loadImage(country3);
//guatemala = loadImage(country4);
// italy = loadImage(country5);
// japan = loadImage(country6);
bg = loadImage("background.jpg");
//posterize the image
australia.filter(THRESHOLD,0.4);
australia.filter(BLUR,3);
australia.filter(THRESHOLD,0.6);
austria.filter(THRESHOLD,0.4);
austria.filter(BLUR,3);
austria.filter(THRESHOLD,0.6);
//initialize the drawing buffers
letter = createGraphics((int)fontsize,(int)fontsize,JAVA2D);
lettersquare = createGraphics((int)fontsize,(int)fontsize,P2D);
drawing = createGraphics(width,height,JAVA2D);
drawing.beginDraw();
drawing.background(255);
// THIS STUPID THING NEEDS TO GO HERE!!!!
drawing.image(bg,0,0);
drawing.endDraw();
}
void draw(){
background(255);
if(floor(fontsize)>fontend&&c<letters.length()-1){
if(!letterfit()){
fontsize *= fontsizedecrease;
}else{
c++;
if(c==11){
fontsize *= 0.75;
}
}
tint(255);
image(drawing,0,0);
if(mousePressed){
tint(255,100);
image(australia,0,0);
}
}else{
tint(255);
image(drawing,0,0);
println(c+" "+letters.length());
/*
save("mlk-"+hour()+""+minute()+""+second()+".tif");
exit();
*/
noLoop();
}
}
boolean letterfit(){
letter.beginDraw();
letter.background(255,0);
letter.fill(0);
letter.textAlign(CENTER,CENTER);
letter.translate(fontsize/2,fontsize/2);
letter.rotate(random(TWO_PI));
letter.scale(fontsize/fontstart);
letter.textFont(font);
letter.smooth();
letter.text(letters.charAt(c),0,0);
letter.endDraw();
lettersquare.beginDraw();
lettersquare.background(255);
lettersquare.image(letter,0,0);
lettersquare.filter(ERODE);
lettersquare.filter(ERODE);
lettersquare.endDraw();
for(int i=0;i<iterations;i++){
int x = floor(random(width-fontsize));
int y = floor(random(height-fontsize));
boolean fits = true;
for(int dx=0;dx<fontsize&&fits;dx++){
for(int dy=0;dy<fontsize&&fits;dy++){
if(brightness(australia.get(x+dx,y+dy))>127){
fits = false;
break;
}
if(brightness(lettersquare.get(dx,dy))<127){
if(brightness(drawing.get(x+dx,y+dy))<127){
fits = false;
}
}
}
}
if (keyCode == RIGHT) {
for(int dx=0;dx<fontsize&&fits;dx++){
for(int dy=0;dy<fontsize&&fits;dy++){
if(brightness(austria.get(x+dx,y+dy))>127){
fits = false;
break;
}
if(brightness(lettersquare.get(dx,dy))<127){
if(brightness(drawing.get(x+dx,y+dy))<127){
fits = false;
}
}
}
}
if(fits){
drawing.beginDraw();
drawing.image(letter,x,y);
drawing.endDraw();
return true;
}
}
if(fits){
drawing.beginDraw();
drawing.image(letter,x,y);
drawing.endDraw();
return true;
}
}
return false;
}

Categories

Resources