I've been working on a tower defense game using eclipse and I cannot manage to print out the picture of my tower. Here is some code from the main tower class :
public class MainTower {
public String TextureFile = "";
public Image texture;
//tower array that holds up to 150 towers
public static final MainTower[] towerList = new MainTower[150];
//Connecting the Lightning tower to the Main tower class
public static final MainTower towerOfLight = new LightningTower(0).getTextureFile("Lightning");
public MainTower(int id) {
if(towerList[id] != null){
System.out.println("[Tower Initialization] Two towers with the same id" + id);
} else {
towerList[id] = this;
this.id = id;
}
}
public MainTower getTextureFile(String str) {
this.TextureFile = str;
this.texture = new ImageIcon("/res/tower/" + this.TextureFile + "png").getImage();
return null;
}
}
The location is correct the image is a 25x25 png image called Lightning. Here is some code from the layout class :
for(int x = 0; x<15; x++) {
for(int y = 0; y<2; y++) {
if(MainTower.towerList[x *2 +y] != null)
GUI.drawImage(MainTower.towerList[x * 2 + y].texture, (int) (12 + 12 + 250 + 40 + 12 +(x * towerWidth)), (12*50) + 20 + (y * (int)towerHeight), null);
GUI.drawRect((int) (12 + 12 + 250 + 40 + 12 +(x * towerWidth)), (int) ((12*50) + 20 + ((y * towerHeight))), (int)towerWidth,(int)towerHeight);
}
}
}
I've created a grid (boxes) at the bottom of the screen where I wish to place my towers so the player can choose. So I was wondering where am i going wrong so the picture doesn't print out.
Here is the LightningTower class:
//Creating a class for Lightning towers
public class LightningTower extends MainTower{
//Setting up Lightning tower id
public LightningTower(int id){
super(id);
}
}
Related
so for an assignment I've had to create a building class i was given the bare bones of the code and I've got this far the part I'm struggling on is setting the size of the x and y coordinate which needs to be in setBuilding().
This is the desired output of the class:
Building size 11×11
Room from (0,0) to (5, 5) door at (3, 5)
Room from (6,0) to (10, 10) door at (6, 6)
Room from (0,5) to (5, 10) door at (2, 5)
The program displays everything apart from the "Building size 11×11", I'm not looking for someone to do the work for me just want to be pointed in the right direction.
Thanks for any help
import java.util.*;
public class Building {
private int xSize = 10; // size of building in x
private int ySize = 10; // and y
private ArrayList<Room> allRooms; // array of rooms
Building (String first) {
allRooms = new ArrayList<Room>();
setBuilding(first);
}
public void setBuilding(String bS) {
String[] Space;
allRooms.clear();
Space = bS.split(";");
allRooms.add(new Room(Space[1]));
allRooms.add(new Room(Space[2]));
allRooms.add(new Room(Space[3]));
}
public String toString() {
String s;
s = " ";
for (Room r : allRooms) {
s = s + r.toString();
}
return s;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Buidling test\n");
Building b = new Building("11 11;0 0 5 5 3 5;6 0 10 10 6 6;0 5 5 10 2 5"); // Create
System.out.println("built building\n");
System.out.println(b.toString()); // And print
}
}
you didn't add any declaration to your toString for showing the building dimensions. I assume you want to use the xSize and ySize of the building. Also note that you're not extracting the building dimensions from the buidlString you pass to setBuilding.
Change your toString to the code below.
public String toString() {
String s = "Building size" + xSize + ", " + ySize;
for (Room r : allRooms) {
s += r.toString();
}
return s;
}
for defining your building size:
public void setBuilding(String bS) {
String[] Space;
allRooms.clear();
Space = bS.split(";");
//Here we'll update the requested building size
String[] buildingSize = Space[0].split(" "); //split the two integers
xSize = Integer.ParseInt(buildingSize[0]); //transform the string to int
ySize = Integer.ParseInt(buildingSize[1]); //transform the string to int
allRooms.add(new Room(Space[1]));
allRooms.add(new Room(Space[2]));
allRooms.add(new Room(Space[3]));
}
I am trying to have a mouse go through rooms to a target room. I am using a graph-like system with an x and y axis. I have a problem where the computer doesn't seem to want to add or subtract from an already existing variable.
Console:
The mouse is in room (5,4)
The mouse is in room (5,6)
The mouse is in room (6,5)
The mouse is in room (5,4)
The mouse is in room (5,6)
The mouse is in room (5,6)
Code for mouse:
package mouse_maze;
public class Mouse {
private int xCord = 5;
private int yCord = 5;
//position of the mouse when it starts
public int getXCord() {
return this.xCord;
}
public int getYCord() {
return this.yCord;
}
public void move() {
//method for the movement of the mouse
boolean verticalMove = Math.random() < .5;
boolean horizontalMove;
if (verticalMove == true)
horizontalMove = false;
else
horizontalMove = true;
int moveBy = 1;
if (Math.random() < .5)
moveBy = -1;
if (verticalMove) {
int test = this.yCord + moveBy;
if(test < 1 || test > 9) return;
this.yCord += moveBy;
}
if (horizontalMove) {
int test = this.xCord + moveBy;
if(test < 1 || test > 9) return;
this.xCord += moveBy;
}
System.out.println("The mouse is in room (" + xCord + "," + yCord + ")");
}
}
Code for maze:
package mouse_maze;
public class Maze {
private boolean onGoing = false;
private int tarX;
private int tarY;
//creates the target for the mouse.
public static void main(String[] args) {
new Maze(6, 8).init();
}
public Maze(int tarX, int tarY) {
this.tarX = tarX;
this.tarY = tarY;
}
public void init() {
this.onGoing = true;
while(this.onGoing)
this.iterate();
}
public void iterate() {
Mouse m = new Mouse();
m.move();
if (m.getXCord() == tarX && m.getYCord() == tarY) {
this.onGoing = false;
System.out.println("The mouse has beat the maze!");
//checks if the mouse has gotten to the target room.
}
}
}
First, learn to use a debugger, or at least learn to debug by whatever means. It is meaningless to always "assume" the problem without actually proving it.
Your whole problem has nothing to do with random etc.
In your iterate() method, you are creating a new mouse every time, instead of having the same mouse keep on moving.
This is a program from OpenCV ColorBlobDetectionActivity.java sample, and I tried to modify it so that it would detect yellow objects when the screen is touched, but it always detects black object only even though I specified the color Scalar to be yellow. I have put comments of "NOTICE" in the places where I think would be relevant.
package com.example.road_guiding;
import java.util.List;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class ColorBlobDetectionActivity extends Activity implements View.OnTouchListener, CameraBridgeViewBase.CvCameraViewListener2 {
// private static final String TAG = "OCVSample::Activity";
private Scalar CONTOUR_COLOR;
private Scalar mBlobColorHsv;
private Scalar mBlobColorRgba;
//NOTICE
private Scalar temp;
private ColorBlobDetector mDetector;
private boolean mIsColorSelected = false;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
public void onManagerConnected(int paramAnonymousInt) {
switch (paramAnonymousInt) {
default:
super.onManagerConnected(paramAnonymousInt);
// Log.i("OCVSample::Activity", "OpenCV loaded successfully");
ColorBlobDetectionActivity.this.mOpenCvCameraView.enableView();
ColorBlobDetectionActivity.this.mOpenCvCameraView.setOnTouchListener(ColorBlobDetectionActivity.this);
return;
}
}
};
private CameraBridgeViewBase mOpenCvCameraView;
private Mat mRgba;
// private Size SPECTRUM_SIZE;
// private Mat mSpectrum;
public ColorBlobDetectionActivity() {
Log.i("OCVSample::Activity", "Instantiated new " + getClass());
}
private Scalar converScalarHsv2Rgba(Scalar paramScalar) {
Mat localMat = new Mat();
Imgproc.cvtColor(new Mat(1, 1, CvType.CV_8UC3, paramScalar), localMat, 71, 4);
return new Scalar(localMat.get(0, 0));
}
public Mat onCameraFrame( CameraBridgeViewBase.CvCameraViewFrame paramCvCameraViewFrame) {
this.mRgba = paramCvCameraViewFrame.rgba(); // mRbga = input frame with color
if (this.mIsColorSelected) {
this.mDetector.process(this.mRgba);
//contour info is ready in detector
List colorContour = this.mDetector.getContours();
// Log.e("OCVSample::Activity", "Contours count: " + localList.size());
Imgproc.drawContours(this.mRgba, colorContour, -1, this.CONTOUR_COLOR); //draw contour around detected area
this.mRgba.submat(4, 68, 4, 68).setTo(this.mBlobColorRgba);
// Producing spectrum
// Mat localMat = this.mRgba.submat(4, 4 + this.mSpectrum.rows(), 70, 70 + this.mSpectrum.cols());
// this.mSpectrum.copyTo(localMat);
}
return this.mRgba;
}
public void onCameraViewStarted(int paramInt1, int paramInt2) {
this.mRgba = new Mat(paramInt2, paramInt1, CvType.CV_8UC4); //width - - the width of the frames that will be delivered
this.mDetector = new ColorBlobDetector();
this.mBlobColorRgba = new Scalar(255.0);
this.mBlobColorHsv = new Scalar(255.0);
this.CONTOUR_COLOR = new Scalar(255.0, 0.0, 0.0, 255.0); //Specfiy the color of contour
//NOTICE
this.temp = new Scalar (237.0, 169.0, 50.0, 255.0);
//yellow to be used:
// this.mBlobColorRgba.val[0] = 237;
// this.mBlobColorRgba.val[1] = 169;
// this.mBlobColorRgba.val[2] = 50;
// this.mBlobColorRgba.val[3] = 255;
// this.mSpectrum = new Mat();
// this.SPECTRUM_SIZE = new Size(200.0, 64.0);
}
public void onCreate(Bundle paramBundle) {
// Log.i("OCVSample::Activity", "called onCreate");
super.onCreate(paramBundle);
// requestWindowFeature(1); // do not show app title
// getWindow().addFlags(128);
setContentView(R.layout.activity_color_blob_detection);
this.mOpenCvCameraView = ((CameraBridgeViewBase) findViewById(R.id.HelloOpenCvView));
this.mOpenCvCameraView.setCvCameraViewListener(this);
}
public boolean onTouch(View paramView, MotionEvent paramMotionEvent)
{
int cameraViewWidth = this.mRgba.cols(); // cameraViewWidth = i
int cameraViewHeight = this.mRgba.rows(); // cameraViewHeight = j
int xOffset = (this.mOpenCvCameraView.getWidth() - cameraViewWidth) / 2;
int yOffset = (this.mOpenCvCameraView.getHeight() - cameraViewHeight) / 2;
int touchX = (int)paramMotionEvent.getX() - xOffset;
int touchY = (int)paramMotionEvent.getY() - yOffset;
// Log.i("OCVSample::Activity", "Touch image coordinates: (" + n = touchX + ", " + i1=touchY + ")");
if ((touchX < 0) || (touchY < 0) || (touchX > cameraViewWidth) || (touchY > cameraViewHeight)) {
return false;
}
Rect touchedRect = new Rect();
if (touchX > 4) {
touchedRect.x = touchX - 4;
touchedRect.y = touchY - 4;
touchedRect.width = touchX + 4 - touchedRect.x;
}
for (int i5 = touchY + 4 - touchedRect.y;; i5 = cameraViewHeight - touchedRect.y) {
touchedRect.height = i5;
// Mat touchedRegionRgba = this.mRgba.submat(touchedRect);
Mat touchedRegionRgba = new Mat();
//NOTICE
Imgproc.cvtColor(new Mat(1, 1, CvType.CV_8UC3, temp), touchedRegionRgba, 71, 0);
Mat touchedRegionHsv = new Mat();
Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL); //67
this.mBlobColorHsv = Core.sumElems(touchedRegionHsv); //calculate average color of touched region
int pixelCount = touchedRect.width * touchedRect.height;
for (int i = 0; i < this.mBlobColorHsv.val.length; i++) {
double[] arrayOfDouble = this.mBlobColorHsv.val;
arrayOfDouble[i] /= pixelCount;
}
touchedRegionRgba.release();
touchedRegionHsv.release();
break;
}
this.mBlobColorRgba = converScalarHsv2Rgba(this.mBlobColorHsv);
// Log.i("OCVSample::Activity", "Touched rgba color: (" + this.mBlobColorRgba.val[0] + ", " + this.mBlobColorRgba.val[1] + ", " + this.mBlobColorRgba.val[2] + ", " + this.mBlobColorRgba.val[3] + ")");
this.mDetector.setHsvColor(this.mBlobColorHsv);
// Imgproc.resize(this.mDetector.getSpectrum(), this.mSpectrum, this.SPECTRUM_SIZE);
this.mIsColorSelected = true;
return false;
}
public void onDestroy() {
super.onDestroy();
if (this.mOpenCvCameraView != null) {
this.mOpenCvCameraView.disableView();
}
}
public void onPause() {
super.onPause();
if (this.mOpenCvCameraView != null) {
this.mOpenCvCameraView.disableView();
}
}
public void onResume() {
super.onResume();
OpenCVLoader.initAsync("2.4.3", this, this.mLoaderCallback);
}
public void onCameraViewStopped() {
this.mRgba.release();
}
}
Any help would be appreciated, thanks!
Sorry i don't know Java but i can suggest the general logic to detect "Yellow" color. You should convert the RGB image into YUV image and then equalize the Y-channel. As Y-channel is for luminance, so you reduce the effects of illumination changes by doing so.
-Then convert back your image to RGB from YUV
-Convert the image to HSV now.
-Now try to calculate only those pixels which possibly represent "Yellow" color. For that, use the following conditions:
The pixel should have S>0 (or some other value near to 0) to eliminate the white pixels which create problem in the caculation.
The pixel should have V>0 to remove the "Black pixels" which have V=0
If the H> 22 && H<37 then increase the yellowPixelCount by 1.
-So, by following the above mentioned procedure, you can count the "yellow" pixels in the image. And, if the count is greater than the threshold then you can predict that it is "yellow" color.
PS: Don't forget to count the total number of pixel which fullfill the criteria 1 & 2 so that you can use that value to find the percentage of yellow component to predict whether the image has yellow color or not.
if (condition 1 & 2 satisfied)
{
totalPixelCount++;
if(condition 3 satisfied)
{
yellowPixelCount
}
}
% of yellow componet = yellowPixelCount/totalPixelCount*100
I have a 90 frames animation and i want to display it on the minecraft hud.
Here is the code i use now:
String CType = "Target";
int CSpeed = 30;
int fast = 0;
public int CenterRoteryCounter = 0;
#ForgeSubscribe
public void CenterRotery(RenderGameOverlayEvent.Post event){
//========Resolution========
res = new ScaledResolution(mc.gameSettings, mc.displayWidth, mc.displayHeight);
int width = res.getScaledWidth();
int height = res.getScaledHeight();
//========Resolution========+
if(CenterRoteryCounter == 90){CenterRoteryCounter = 0;}
if(CenterRoteryCounter < 10){
this.mc.renderEngine.func_110577_a(new ResourceLocation("CenterRotery/"+CType+"000" + CenterRoteryCounter + ".png"));
}else{if(CenterRoteryCounter < 100){
this.mc.renderEngine.func_110577_a(new ResourceLocation("CenterRotery/"+CType+"00" + CenterRoteryCounter + ".png"));
}else{
this.mc.renderEngine.func_110577_a(new ResourceLocation("CenterRotery/"+CType+"0" + CenterRoteryCounter + ".png"));
}
}
drawTexturedModalRect((width/2)-44, (height/2)-37, 0, 0, 250, 250);
mc.func_110434_K().func_110577_a(Gui.field_110324_m);
if((fast % CSpeed)==0){CenterRoteryCounter++;}fast++;
}
but as you can see, this is creating ~30 new ResourceLocations every second..!!
How can i pre-load the textures and display them the same way?
You can simply use a private static final Hashmap from your class in a method getResourceLocation(String resourceLocation). Something like :
private static ResourceLocation getResourceLocation(String resourceLocation) {
ResourceLocation myRes = myHashMap.get(resourceLocation);
if (myRes == null) {
myRes = new ResourceLocation(resourceLocation);
myHashMap.put(resourceLocation, myRes);
}
return myRes;
}
It will cache your resources on demand. Just be sure of the necessary amount of memory needed !
I am using NETBEANS and have several JLabels that need to display a specific icon/image based on a decision/boolean. I do not want to have to add a mouse listener for every JLabel and then copy and paste the code for each one. Rather I would prefer to use the x,y as the name of the JLabel and then set icon based on the x,y. I have no problems getting the x.y but cannot seem to figure out how to do something like this (xy.setIcon(new ImageIcon(Hit)); here is my code.
/**
* Mathematical coordinates of player1Fleet.
* Used to realign ships from Ship Class
* for use on game board.
*/
public void mouseClicked(MouseEvent e) {
Launch1();
}
public void FleetP1() {
for (Ship s : player1Fleet) {
int size = s.getSize();
for (int i = 0; i < size; i++) {
player1Ships.add((((s.getXCoordinate(i) + 1) * 45) + 90) + "" + (((s.getYCoordinate(i) + 1) * 45) + 180));
}
}
// Verification of Math
System.out.println(player1Ships);
}
/**
* Determine Hit or Miss based on location of Cross-hairs
* for player 1/West on game board.
* #return
*/
//public boolean setStrike1(){
public boolean Launch1() {
w93.setIcon(null);
player1Ships.clear();
FleetP1();
boolean strike1 = false;
boolean Launch = false;
for (int i = 0; i < this.player1Ships.size(); i++) {
if (this.player1Ships.get(i).equals(LblCrossHairs.getX() + "" + LblCrossHairs.getY())) {
strike1 = true;
//break;
}
if (strike1) {
strike1 = true;
(LblCrossHairs.getX() + "" + LblCrossHairs.getY()).setIcon(new ImageIcon(Hit));
//Launch = theAttack.Strike1(strike1);
//w93.setIcon(new ImageIcon(Hit));
URL url = this.getClass().getResource("MissleHit.au");
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("HIT");
break;
} else {
strike1 = false;
(LblCrossHairs.getX() + "" + LblCrossHairs.getY()).setIcon(new ImageIcon(Hit));
//w93.setIcon(new ImageIcon(Miss));
URL url = this.getClass().getResource("MissileMiss.au");
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("MISS");
}
}
TxtClick.setText(LblCrossHairs.getX() + "" + LblCrossHairs.getY() + ".setIcon");
return strike1;
}
Thank you in advance for all your help. This has been driving me crazy for the last two days
I do not want to have to add a mouse listener for every JLabel and then copy and paste the code for each one.
You don't have to create a separate listener. You can share the same listener with every JLabel. The basic code is:
public void mouseClicked(MouseEvent e)
{
JLabel label = (JLabel)e.getSource();
label.setIcon(...);
}