Linking an array to another class in Java - java

I am working on a game of tic-tac-toe for class and in one class I create a Board object which contains a String array and then pass it to a player class. However I cannot figure out how to allow me to use this information in the new class. Can anybody here give me some pointers?
public static void main(String[] args)
{
//new tic-tac-toe board
Board board = new Board();
//two new players (computer and human)
Player computer = new Player(board, "X"); //Give computer player access to board and assign as X.
Player human = new Player(board, "O"); //Give human player access to board and assign as O.
and the class I'm trying to use it in
package outlab5;
import java.util.Scanner;
public class Player {
private String[][] currentBoard;
private String move;
Scanner input = new Scanner(System.in);
public Player(Board inBoard, String inMove){
move = inMove;
}
public void computerMove(){
boolean valid = false;
while(!valid){
int moveCols = (int)(Math.random()*4);
int moveRows = (int)(Math.random()*4);
System.out.print(currentBoard[0][0]);
}
}

I think your Board class has a field representing the String[][] array, which you are looking for.
In your player class, store the borad object properly.
public class Player {
private String[][] currentBoard;
private String move;
private Board board; //define a variable
Scanner input = new Scanner(System.in);
public Player(Board inBoard, String inMove){
board = inBoard;
move = inMove;
}
You dont show the code of Board class, so i have to guess how you may access the string[][],probably the Board class provides some get-Methods, to get access to the string array.
String[][] currentBoard = board.get....(); //this call must be placed in a method

Here is an example, of how you can do your application.
Board Class
public class Board {
// TODO : Stuff and Stuff ( Where your 3x3 Matrix may be )
}
Player Abstract Class
abstract class Player {
private final Board board;
private final String move;
public Player(Board _board, String _move) {
this.board = _board;
this.move = _move;
}
public void playerMove() {
// TODO : Default Movement Actions
}
public void playerWin() {
// TODO : Default Event on Player Win
}
}
Computer Class
public class Computer extends Player {
public Computer(Board _board, String _move) {
super(_board, _move);
}
#Override
public void playerMove() {
// TODO : Computer Related Movements ( Like AI )
super.playerMove();
}
#Override
public void playerWin() {
// TODO : Computer Related Events for Computer ( Like Increase Dif )
super.playerWin();
}
}
Human Class
public class Human extends Player {
public Human(Board _board, String _move) {
super(_board, _move);
}
#Override
public void playerMove() {
// TODO : Human Related Movements ( Like I/O )
super.playerMove();
}
#Override
public void playerWin() {
// TODO : Human Related Events on Win ( Like Score )
super.playerWin();
}
}

Related

using constructor from another class in java to create objects in separate classs

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 ?

Trying to solve a Simple RPG game

I'm trying to solve a task that's a bit too much for me. The idea is to have a simple RPG game with the parent class (AllPlayers) and a subclass PlayerOne. I'm struggling with the calling of the player profession and his inventory system. I need to print how many coins the player has in its pocket, too.
MAIN:
import java.util.Scanner;
public class Main {
public static Scanner scanner = new Scanner(System.in);
public static String username;
public static PlayerOne player;
public static void main(String[] args) {
System.out.println("Choose your name: ");
username = scanner.nextLine();
System.out.println("Choose your profession: \n" +
"Press 1 for a knight class\n" +
"Press 1 for a rider class\n" +
"Press 1 for a mage class");
player = new PlayerOne(username);
player.displayPlayerOne();
player.displayPlayerInventory();
player.displayPocketCoins();
player.displayPlayerProfession();
}
}
As you can see, I set the getters and setters but that's the farthest I have gone so far. Can you provide me with some clues on how to
call the profession in the main?
call the inventory in the main?
I guess I'll figure out how to call coins in the main later, it will be quite the same as with profession and inventory.
Thank you!
AllPlayers (SUPERCLASS)
public class AllPlayers {
protected String name;
private int level;
private int health;
private int damage;
public AllPlayers(String name, int level, int health, int damage) {
this.name = name;
this.level = level;
this.health = health;
this.damage = damage;
}
}
And here is the player class:
public class PlayerOne extends AllPlayers{
private String [] inventory;
private int coins;
private String [] professions;
public PlayerOne(String name) {
super(name, 1, 20,5);
this.professions = getProfessions();
}
public void setProfessions(String[] professions) {
this.professions = professions;
}
public String[] getProfessions() {
return this.professions;
}
public void setCoins() {
this.coins = coins;
}
public int getCoins() {
return coins;
}
public void setInventory() {
this.inventory = inventory;
}
public String[] getInventory() {
return inventory;
}
public void displayPlayerOne() {
System.out.println("Your name is " + super.name);
}
public void displayPlayerInventory() {
inventory[0] = "knife";
inventory[1] = "sword";
inventory[2] = "spear";
inventory[3] = "potion";
}
public void displayPocketCoins() {
coins = 50;
}
public void displayPlayerProfession() {
professions[0] = "knight";
professions[1] = "rider";
professions[2] = "mage";
}
}
call the profession in the main?
Well, you already have the type declaration PlayerOne player; so just call player.getProfessions() and use the array.
call the inventory in the main?
Just the same: player.getInventory().
However, note that your design is somewhat flawed (although since you're a beginner don't bother too much). The class name PlayerOne indicates any other player (e.g. PlayerTwo) would be different, but that's probably not the case. Also, AllPlayers doesn't actually indicate a class, but it looks more like a collection.
You might think about changing your class names, e.g. assuming AllPlayers will be used for NPCs as well, you could name it Character while the class for players is called Player. Doing this you could have multiple players if needed: Player playerOne, Player playerTwo etc.

Objects' variables changed by method in another class [duplicate]

This question already has answers here:
How to make a method in a class, manipulate variables in another class?
(2 answers)
Closed 5 years ago.
I created a simple method in my CardGames class that replicates a card game to play around with conditional statements. I call the method from a separate Player class because the player earns/loses points based on the card. I want the method to be able to change the player objects points variable.
What I want to have happen is when the playSimpleCardGame gets called by the Player object, the method changes the Player object's points.
But when I run it the points do not change. I've tried extending/implementing both classes (i.e. shooting in the dark). I also created an instance variable points in the CardGames class but then the Player object does not have points as a variable. What am I missing?
public class Player
{
private int points;
public static void main(String[] args)
{
CardGames steve = new CardGames();
System.out.println(steve.playSimpleCardGame("red"));
System.out.println(steve.playSimpleCardGame("red"));
System.out.println(steve.playSimpleCardGame("black"));
System.out.println(steve.playSimpleCardGame("black"));
System.out.println(steve.points);
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color)
{
if (color.equalsIgnoreCase("red"))
return points = points + 1;
else
return points = points - 2;
}
}
public class Player
{
private int points;
public Player(){
points=0;
}
public static void main(String[] args)
{
CardGames game = new CardGames();
Player steve = new Player();
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(steve.points);
}
public int getPoints() {
return points;
}
public void addPoints(int p) {
this.points = points + p;
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color, Player player)
{
if (color.equalsIgnoreCase("red"))
{
player.addPoints(1);
return player.getPoints();
}
else
{
player.addPoints(-2);
return player.getPoints();
}
}
}
Firstly, there is no need to extend CardGames class by the Player class. Secondly, even if you wish to do it, it will be a bad design. I won't go into the design part. The following code should answer your problem :
public class Player
{
public Integer points;
public Player(){
points=0;
}
public static void main(String[] args)
{
CardGames game = new CardGames();
Player steve = new Player();
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("red", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(game.playSimpleCardGame("black", steve));
System.out.println(steve.points);
}
}
public class CardGames
{
/*
* Rules of this game:
* If you draw a red card, you get a point.
* If you draw a black card, you lose two points.
*/
public int playSimpleCardGame(String color, Player player)
{
if (color.equalsIgnoreCase("red"))
return player.points = player.points + 1;
else
return player.points = player.points - 2;
}
}

Changing data in an Object Array

I have been trying to make a game for a friend, but I'm having a problem with getting my line player[i].setName(getName(pn)); in class Players to work. I want to be able to set the names of the players, or change them, in the list. but I keep getting errors at this line. This happened after i changed the public variables in class Player from static.
"Exception in thread "main" java.lang.NullPointerException
at worldhomicide.drinkinggame.PlayerInfo.Players.setPlayers(Players.java:16)
at worldhomicide.drinkinggame.main.Game.main(Game.java:25)"
Any help would be greatly appreciated! I posted all needed code below.
Game Class
public class Game{
public static void main(String[] args) {
MessageHandler.gameRules(); // Display Game Information
Players.getAmount();Players.setPlayers(); // Get player data
System.out.println("What player would you like to look up?");
int choice = Integer.parseInt(EventHandler.keyboard.next()); choice -= 1;
System.out.println(Players.player[choice].name);
}
}
Players Class
public class Players extends EventHandler {
public static int playerAmount;
public static Player[] player;
public static void setPlayers(){
player = new Player[playerAmount];
for(int i = 0; i < player.length; i++){
int pn = i+1;
player[i].setName(getName(pn));
}
}
public static void getAmount(){
MessageHandler.playerAmount();
playerAmount = Integer.parseInt(keyboard.next());
}
}
Class EventHandler
public class EventHandler {
public static Scanner keyboard = new Scanner(System.in);
public static String getName(int playerNumber){
System.out.println("What is player " + playerNumber + "'s name?");
String name = keyboard.next();
return name;
}
}
Player Class
public class Player {
public String name;
public int score;
public void setName(String name){
this.name = name;
}
}
Note that in your setPlayers() method, inside the loop, you didn't create Player object before accessing the player[i].setName() method.
for(int i = 0; i < player.length; i++){
int pn = i+1;
player[i] = new Player(); //you need to create Player object
player[i].setName(getName(pn));
}

Dealing with object's scope

I'm trying to write a game in Java with a Player class that has 2 subclasses: HumanPlayer and ComputerPlayer. I want to allow the user to choose which player to play against, and once chosen - to create the relevant object and play.
Since the object is created within an if statement, the compiler doesn't let me perform any operations outside the if scope. In other cases I would create the object within the class' scope but in this case I cant know in advance which object to create (human/computer)
Here is some code for illustration:
public class Player {
private String name;
public String getName(){
return name;
}
}
public class HumanPlayer extends Player {
public void play(){
System.out.println("Human playing");
}
}
public class ComputerPlayer extends Player {
public void play(){
System.out.println("Computer playing");
}
}
import java.util.Scanner;
public class PlayerDriver {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please type 1 for human, 2 for computer");
int selection = in.nextInt();
if (selection==1){
HumanPlayer player = new HumanPlayer();
} else if (selection==2){
ComputerPlayer player = new ComputerPlayer();
} else {
throw new IllegalArgumentException("invalid answer");
}
Player.play(); //can't do that
}
}
Harness the power of polymorphism
Player player = null; // player should never be null as you would have thrown an exception, but for the sake of completeness
if (selection == 1){
player = new HumanPlayer();
} else if (selection == 2){
player = new ComputerPlayer();
} else {
throw new IllegalArgumentException("invalid answer");
}
player.play();
assuming the Player class has a play() method. I see it doesn't. Change your class Player to have an override-able play() method which you override in the sub types.

Categories

Resources