Basically I made I class to extend the grid to 11 by 11, the constructor is being called however its not changing the grid. Any input or information on why would be greatly appreciated. I've posted my code below:
import info.gridworld.actor.*;
import info.gridworld.grid.BoundedGrid;
public class ChangeGrid extends ActorWorld{
private static final int SIZEROW = 11;
private static final int SIZECOL = 11;
public ChangeGrid()
{
super(new BoundedGrid<Actor>(SIZEROW, SIZECOL));
System.out.println("test");
}
}
import info.gridworld.actor.Bug;
public class XBug extends Bug {
/**
* A <code>BoxBug</code> traces out a square "box" of a given size. <br />
* The implementation of this class is testable on the AP CS A and AB exams.
*/
private int steps;
private int sideLength;
private int x = 0;
private static ChangeGrid object = new ChangeGrid();
/**
* Constructs a box bug that traces a square of a given side length
* #param length the side length
*/
public XBug(int length)
{
steps = 0;
sideLength = length;
}
/**
* Moves to the next location of the square.
*/
public void act()
{
if (steps < sideLength && canMove())
{
if(x==0)
{
turn();
}
move();
steps++;
x++;
}
else
{
turn();
steps = 0;
}
}
}
Your constructor is not being called when you create the world. You are calling it inside of an Actors class, then you don't even call the .show() method. You just need to change your runner class to call ChangeWorld instead of ActorWorld.
Here's an example for your code.
public class Runner
{
public static void main(String[]args)
{
ChangeWorld world = new ChangeWorld();
XBug bug = new XBug();
world.add(bug);
world.show();
}
}
Related
how can I use the constructor from another class in java to make an object through a method in separate class. For example below is a constructor in a player class
public class Player extends Entity {
public Player(int maxEnergy, int x, int y) {
this.maxEnergy = maxEnergy;
this.energy = maxEnergy;
carryingGhost = false;
xPos = x;
yPos = y;
}
Which I want to use and create objects (player) through a method called
private Player createPlayer() {
and the above method is in separate class as
public class GameEngine {
**The method must return a Player object that represents the player in the
game. it must set the maxEnergy for the player, and the
X and Y positions corresponding to a tile position in the current level.
I have tried to initialize player within method with parameters and
without parameters as**
Player player = new Player(int maxEnergy, int x, int y);
this.player.getEnergy();
this.player.getMaxEnergy();
this.player.setPosition(x, y);
return player;
}
But it give errors.Any help will be appreciated.I am quite close to assume its not possible to have created objects like this.
below I share the complete game engine which is working with other classes as well .
import java.awt.Point;
import java.util.ArrayList;
import java.util.Random;
public enum TileType {
WALL, FLOOR1, FLOOR2, BANK, BREACH, DOOR;
}
public static final int LEVEL_WIDTH = 35;
public static final int LEVEL_HEIGHT = 18;
private Random rng = new Random();
private int levelNumber = 1; //current level
private int turnNumber = 1;
private GameGUI gui;
private TileType[][] level;
private ArrayList<Point> spawnLocations;
private Player player;
private Ghost[] ghosts;
public GameEngine(GameGUI gui) {
this.gui = gui;
}
private TileType[][] generateLevel() {
//YOUR CODE HERE
return null; //change this to return the 2D arrayof TileType
//values that you create above
}
private ArrayList<Point> getSpawns() {
ArrayList<Point> s = new ArrayList<Point>();
// YOUR CODE HERE
return s;
}
private Ghost[] addGhosts() {
//YOUR CODE HERE
return null; //change this to return an array of ghost objects
}
**/**
* Creates a Player object in the game. The method instantiates
* the Player class and assigns values for the energy and position.
* The first version of this method should use fixed a fixed position
for the player to start, by setting fixed X and Y values when calling
the constructor in the Player class. The second version of this method
should use the spawns ArrayLis to select a suitable location to spawn
the player and removes the Point from the spawns ArrayList. This will
prevent the Player from being added to the game inside a wall, bank or
breach for example.
#return A Player object representing the player in the game
*/**
private Player createPlayer() {
//YOUR CODE HERE
return null; //change this to return a Player object
}
public void movePlayerLeft() {
}
public void movePlayerRight() {
}
public void movePlayerUp() {
}
public void movePlayerDown() {
}
private void hitGhost(Ghost g) {
}
private void moveGhosts() {
}
private void moveGhost(Ghost g) {
}
private void cleanDefeatedGhosts() {
}
private void nextLevel() {
}
private void placePlayer() {
}
public void doTurn() {
cleanDefeatedGhosts();
moveGhosts();
gui.updateDisplay(level, player, ghosts);
}
public void startGame() {
level = generateLevel();
spawnLocations = getSpawns();
ghosts = addGhosts();
player = createPlayer();
gui.updateDisplay(level, player, ghosts);
}
}
I have used below method and its not showing error so far.
private Player createPlayer() {
int energy=player.getEnergy();
int maxEnergy=player.getMaxEnergy();
int xPos=player.xPos;
int yPos=player.yPos;
return new Player(maxEnergy,xPos,yPos);
}
The following should do it:
private Player createPlayer() {
int defaultMaxEnergy = 10; // Whatever value it should have
int initialX = 1; // Whatever value it should have
int initialY = 1; // Whatever value it should have
return new Player(defaultMaxEnergy, initialX, initialY);
}
Since the values are not in your descriptions I just selected a random number but you can pick whatever integers you want and that makes sense.
Does something like this work for your case?
public class GameEngine {
private Player createPlayer() {
return new Player(1,2,3);
}
}
Add a default no-args constructor in the player class. Once you create a constructor with Arg, java will not auto provide default one.
You have already declared Player
private Player player;
So you must not try to reinitialize using same variable name, rather
private Player createPlayer() {
Player newPlayer = new Player();
// set the different props of the Player obj
return newPlayer ;
}
What is the error which you are facing ? Can you share that ?
I'm super new to programming so excuse me if my code is hard to understand. I was assigned to program a game to deal a card to the user and being it is the top card. I already have my card class made. I just need to know if I'm doing this correctly. It says build successful, but doesn't show anything. Please help!
package deck;
import java.util.*;
/**
*
* #author useradmin
*/
// Write a description of class Deck here.
public class Deck {
private Card[] theCards;
private int deal;
public Deck() {
theCards = new Card[52];
deal = 52;
this.fill();
//fill();
}
public int deal() {
return deal;
}
public Card getCard() {
Card a = null;
a = theCards[deal-1];
deal--;
return a;
}
public String toString()
{
String deckString = "New deck shuffled\n";
for(int i = 1; i <= 1; i++)
{
deckString += theCards[i].toString() + "\n";
}
return deckString;
}
public void shuffleCards() {
Random random = new Random();
Card temp;
int topCard;
for(int i = 0; i<30; i++){
topCard = random.nextInt(deal);
}
}
private void fill() {
int i, j;
int index = 0;
for(i = 0; i <4; i++) {
for(j = 1; j < 14; j++){
theCards[index] = new Card(i, j);
index++;
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
{
}
}
The public static void main(String[] args) method is the entry point for your program. When you run your program, this is the first method that gets called. Yours is empty, so nothing will happen.
Solution
Make a new class and call it Application.
Cut the public static void main(String[] args){} method from your Deck class and paste it into your new Application class.
Inside the main() you will need to put some code! I suggest creating a Deck object and then printing the contents of the deck using your toString() method, just so that you can see that everything is working.
Your new class should look like this:
public class Application {
//Main method (Entry point for program)
public static void main(String[] args) {
Deck myDeck = new Deck(); //Create Deck
System.out.println(myDeck.toString()); //Print contents of Deck
}
}
Make sure that you have removed the main() method from your Deck class .
Hope that helps you out. :)
I'm trying to understand Java by trying several things out. I'm using two classes in the same package. One is called Box, the other one is called TestBox. I want to calculate the area of the company box using calculateArea(). This function is in another class TestBox. However the function calculateArea in Box does not respond to the function in TestBox. I'm missing a link between these two classes. This seems like a simple problem, but I have not found the solution yet. Can someone please help me out?
package box;
public class Box {
int length;
int width;
public static void main(String[] args) {
Box company = new Box();
company.length = 3;
company.width = 4;
int area = company.calculateArea();
}
}
package box;
public class TestBox {
int length;
int width;
int calculateArea(){
int area = length * width;
System.out.println("Area= " + area);
return area;
}
}
I think you have to clarify a bit what is your design, I mean what the classes Box and TestBox should do, moreover I advice use to use an IDE such as Eclipse or Intellij Idea helping you with syntax highlight and founding possible errors.
What you are dealing with is the encapsulation, that is
packing of data and functions into a single component.
so it is feasible that the area of the box is calculated by the Box class itself.
About your code, a possible solution could be:
package com.foo;
public class Main {
public static void main(String[] args) {
Box box = new Box(3, 4);
int area = box.calculateArea();
System.out.println("Box area is: " + area);
}
}
class Box {
private int l;
private int w;
Box(int length, int width) {
l = length;
w = width;
}
int calculateArea() {
return l * w;
}
}
Another possible approach could be
package com.foo;
public class Main {
public static void main(String[] args) {
Box box = new Box(3, 4);
TestBox testBox = new TestBox();
int area = testBox.calculateArea(box);
System.out.println("Box area is: " + area);
}
}
class Box {
private int l;
private int w;
Box(int length, int width) {
l = length;
w = width;
}
public int getLength() {
return l;
}
public int getWidth() {
return w;
}
}
class TestBox {
int calculateArea(Box box) {
return box.getLength() * box.getWidth();
}
If you want to have a separate class doing the job, but it is something I do not like, the function computing the area is related to the box and works on box variables, I prefer the first one, but it should be better to have more details in case.
I hope it helps.
As per the below approach, you need to make parameterized constructor where you can pass the value of length and width at the time of creating TestBox object. You also need to create a default constructor for future save in case if later you only want to create default TestBox object like new TestBox();
You can calculate area in you TestBox class and than return the value in the Box class. You don't need to create separate length and width variable in Box class and no need to create a object of Box.
package box;
public class Box {
public static void main(String[] args) {
TestBox company = new TestBox (3,4);
int area = company.calculateArea();
}
}
package box;
public class TestBox {
private int length;
private int width;
TestBox()
{
}
TestBox(int l, int w)
{
this.length = l;
this.width = w;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
int calculateArea(){
int area = length * width;
System.out.println("Area= " + area);
return area;
}
}
public static void main(String[] args) {
TestBox company = new TestBox();
company.length = 3;
company.width = 4;
int area = company.calculateArea();
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have got some code and it all seems to work apart from one error that appears. This stops the whole program running. Please could you have a look at the code and see what the issue is. This is a space invaders game and this is the class that contains the public static void main.
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25;
public static int ALIEN_WIDTH = 15;
private int leftPosition = 0;
private int heightPosition = 0;
private boolean hitState = false;//Whether this alien has already been shot
private Image alienImage = null;
SpaceInvaders spaceInvaders = null;
/**
*
*/
public Alien(Image ai, SpaceInvaders si) {
alienImage = ai;
spaceInvaders = si;
}
/**
* Returns whether ythe alien had been hit
*/
public boolean hasBeenHit() {
return hitState;
}
/**
* Check if a shot fired hit an alien
*/
public boolean hitAlien(int x, int y) {
//Is the alien currently alive?
if (hitState) {
//If it's alreay been shot then return false;
return false;
}
//First lets check the X range
if ((x >= leftPosition) && (x <= (leftPosition+ALIEN_WIDTH))) {
//X is ok, now lets check the Y range
if ((y >= heightPosition) && (y <= (heightPosition+ALIEN_HEIGHT))) {
//We shot an alien!
hitState = true;
return true;
}
}
return false;
}
/**
* Set the position of the alien on the screen
*/
public void setPosition(int x, int y) {
leftPosition = x;
heightPosition = y;
}
/**
* Returns the current x position of the alien
*/
public int getXPos() {
return leftPosition;
}
/**
* Returns the current x position of the alien
*/
public int getYPos() {
return heightPosition;
}
/**
* Draw the image of the Alien
*/
public void drawAlien(Graphics g) {
if (!hitState) {
g.setColor(Color.red);
g.fillRect(leftPosition, heightPosition, ALIEN_WIDTH, ALIEN_HEIGHT);
}
}
}
}
}
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert "}" to complete MethodBody
at Alien.main(Alien.java:3)
You seem to be mis-understanding the basics of Java syntax. Specifically, you cannot define your class's members and methods inside main() the way you are attempting to do:
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25; // you can't put this here
public static int ALIEN_WIDTH = 15; // you can't put this here
private int leftPosition = 0; // you can't put this here
private int heightPosition = 0; // you can't put this here
//etc
To get this to compile, you need to close main() and delete all the extra } you have at the end of your code:
import java.awt.*;
public class Alien {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* The Alien class.
*/
public static int ALIEN_HEIGHT = 25;
public static int ALIEN_WIDTH = 15;
//etc
You'll also need to add some code to main() before your program actually does anything.
I would suggest that before you continue your current program you read some of the excellent tutorials online. A good place to start is The Java™ Tutorials on the oracle website.
Look at the Trails Covering the Basics section and work your way through Getting Started and Learning the Java Language before doing anything else.
So what im trying to do is to call an external method upon an object, its a bit trickier than I expected and am having problems properly implementing it.
The method is:
attack(Player victim)
The method needs to call a hit() method on an object; then if the hit() method was successful (test this through a boolean?):
use an if statement to call a damage() method upon the object to determine the damage
call takeDamage() upon (PlayerVictim) to inflict the damage.
Here's the player class that ive coded so far; the attack() method is at the bottom.
My main question is how to use an external method(s) damage() on the currentWeapon and takeDamage() on Player Victim
public class Player
{
private String myPlayerName;
private Weapon myWeapon;
private int myCurrentHealth;
private int myMaxHealth;
private int myNumPotions;
/**
* Constructor initializing class Player
* Parameters of the player should be:
* player name, players initial health, the players weapon.
*/
public Player(String myPlayer, int initialHealth, Weapon currentWeapon) {
myPlayerName = myPlayer;
this.myWeapon = currentWeapon;
myMaxHealth = 30;
myCurrentHealth = initialHealth;
myNumPotions = 0;
}
/**
* Attack method which attacks opposing player
* with current equipped weapon.
*/
public void attack(Player victim) {
currentWeapon.hit();
if (boolean currentWeapon.hit() = true) {
currentWeapon.damage(int dam);
return dam;
}
Player victim.takeDamage(int damage);
}
}
and the weapon class:
import java.util.Random;
public class Weapon
{
private int myHitProb;
private int myMaxDamage;
private Random myRNG;
/**
* Create a new weapon with a hit probability and damage
*/
public Weapon(int hitProb, int damage) {
myHitProb = hitProb;
myMaxDamage = damage;
myRNG = new Random();
}
public boolean hit() {
int r = myRNG.nextInt(100);
if (r < myHitProb) {
return true;
}
else {
return false;
}
}
public int damage() {
int dam = myRNG.nextInt(myMaxDamage) + 1;
return dam;
}
}
Your attack() method may be many things, but compilable java it is not.
Perhaps this is what you meant:
public void attack(Player victim) {
if (currentWeapon.hit()) {
victim.takeDamage(currentWeapon.damage());
}
}
Try to remember this guideline: If it seems hard, you're probably doing it the wrong way (unless you're working on the Mars Lander program :) )