Battleship game in java - java

I need help with a program I have to finish by this Saturday, it is really important, I actually have this code in spanish though. I am looking for a way to make a simple IA, here are my classes:
public class Game {
private HumanPlayer[] players;
public Game() {
this.players = new HumanPlayer[]{
new HumanPlayer(1),
new HumanPlayer(2)
};
}
public void start() {
int i = 0;
int j = 1;
int len = players.length;
HumanPlayer player = null;
this.players[i].colocaBarcos();
this.players[j].colocaBarcos2();
while(players[0].getVidasRestantes() > 0 &&
players[1].getVidasRestantes() > 0) {
players[i++ % len].dispararA(players[j++ % len]);
player = (players[0].getVidasRestantes() < players[1].getVidasRestantes()) ?
players[1] :
players[0];
}
System.out.printf("Enhorabuena Player %d, ganaste!",player.getId());
}
}
public class AguaField implements IGameField {
private boolean fieldGolpeado = false;
#Override
public char getIcon() {
return fieldGolpeado ? 'M' : '~';
}
#Override
public Resultado dispararA() {
fieldGolpeado = true;
return Resultado.NO_GOLPE;
}
}
public class Barco {
private final String nombre;
private final int tamaño;
private int vidas;
public Barco(String nombre, int tamaño) {
this.nombre = nombre;
this.tamaño = tamaño;
this.vidas = tamaño;
}
public void golpear() {
if(vidas > 0) {
System.out.printf("%nBuen golpe! El %s fue golpeado", nombre);
vidas--;
}
else {
System.out.println("El barco fue destruido");
}
}
public Resultado getEstado() {
if(vidas == 0) {
return Resultado.DESTRUIDO;
}
else if(vidas < tamaño) {
return Resultado.PARCIAL_GOLPE;
}
else {
return Resultado.NO_GOLPE;
}
}
public String getNombre() {
return nombre;
}
public int getTamaño() {
return tamaño;
}
}
public class BarcoField implements IGameField {
private final Barco ship;
public BarcoField(Barco ship) {
this.ship = ship;
}
#Override
public char getIcon() {
char icon;
Resultado barcoEstado = ship.getEstado();
switch (barcoEstado) {
case PARCIAL_GOLPE: icon = 'O';
break;
case DESTRUIDO: icon = 'O';
break;
case NO_GOLPE: icon = 'X';
break;
default: icon = ' ';
break;
}
return icon;
}
#Override
public Resultado dispararA() {
ship.golpear();
return ship.getEstado();
}
}
public class BarcoTamaño {
private BarcoTamaño() {
}
public static final int CARRIER = 6;
public static final int BATTLESHIP = 4;
public static final int CRUISER = 2;
public static final int DESTROYER = 1;
}
public class HumanPlayer implements IPlayer {
private int totalVidas = 17;
private int id;
private Tablero tablero;
private Tablero tablero2;
private Scanner scanner;
public HumanPlayer(int id) {
this.id = id;
this.tablero = new Tablero();
this.scanner = new Scanner(System.in);
}
public int getId() {
return id;
}
public Tablero getTablero() {
return tablero;
}
#Override
public void colocaBarcos() {
System.out.printf("%n======== Player %d - Coloca tus barcos ========%n", id);
tablero.colocaBarcosTablero();
}
public void colocaBarcos2() {
System.out.printf("%n======== Player %d - Coloca tus barcos ========%n", id);
tablero.colocaBarcosTablero2();
}
#Override
public void dispararA(IPlayer opponent) {
System.out.printf("%n Bien player %d - Introduce las coordenadas de tu ataque: ", id);
boolean esPuntoValido = false;
while(!esPuntoValido) {
try {
Point point = new Point(scanner.nextInt(), scanner.nextInt());
int x = (int)point.getX() - 1;
int y = (int)point.getY() - 1;
Resultado resultado = ((HumanPlayer)opponent)
.getTablero()
.getField(x, y)
.dispararA();
if(resultado == Resultado.PARCIAL_GOLPE || resultado == Resultado.DESTRUIDO) {
totalVidas--;
}
esPuntoValido = true;
}
catch(IllegalArgumentException e) {
System.out.printf(e.getMessage());
}
}
}
#Override
public int getVidasRestantes() {
return totalVidas;
}
}
public interface IGameField {
char getIcon();
Resultado dispararA();
}
public interface IPlayer {
void colocaBarcos();
void dispararA(IPlayer opponent);
int getVidasRestantes();
}
public enum Resultado {
NO_GOLPE,
PARCIAL_GOLPE,
DESTRUIDO
}
public class Tablero {
private static final char AGUA = '~';
private static final int TABLERO_SIZE = 10;
private static final char[] TABLERO_LETRAS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
private static final String HORIZONTAL = "H";
private static final String VERTICAL = "V";
private static final String HORIZONTAL2 = "h";
private static final String VERTICAL2 = "v";
private Scanner scanner;
private IGameField[][] tablero;
private static final Barco[] barcos;
static {
barcos = new Barco[]{
new Barco("Carrier", BarcoTamaño.CARRIER),
new Barco("Battleship1", BarcoTamaño.BATTLESHIP),
new Barco("Battleship2", BarcoTamaño.BATTLESHIP),
new Barco("Cruiser1", BarcoTamaño.CRUISER),
new Barco("Cruiser2", BarcoTamaño.CRUISER),
new Barco("Cruiser3", BarcoTamaño.CRUISER),
new Barco("Destroyer", BarcoTamaño.DESTROYER),
new Barco("Destroyer", BarcoTamaño.DESTROYER),
new Barco("Destroyer", BarcoTamaño.DESTROYER),
new Barco("Destroyer", BarcoTamaño.DESTROYER)
};
}
public void escogerBarco(){
System.out.println("Que barco quieres introducir? ");
String barcoEscogido = scanner.nextLine();
if (barcoEscogido == "Carrier"){
new Barco("Carrier", BarcoTamaño.CARRIER);
}
}
public Tablero() {
this.scanner = new Scanner(System.in);
this.tablero = new IGameField[TABLERO_SIZE][TABLERO_SIZE];
for(int i = 0; i < TABLERO_SIZE; i++) {
for(int j = 0; j < TABLERO_SIZE; j++) {
tablero[i][j] = new AguaField();
}
}
}
public void colocaBarcosTablero() {
for(Barco ship : barcos) {
boolean horizontal = preguntaDireccionValida();
Point puntoInicio = preguntaPuntoInicio(ship, horizontal);
colocaBarcoValido(ship, puntoInicio, horizontal);
printTablero();
}
}
public void colocaBarcosTablero2() {
for(Barco ship2 : barcos) {
boolean horizontal2 = preguntaDireccionValida2();
Point puntoInicio2 = preguntaPuntoInicio2(ship2, horizontal2);
colocaBarcoValido(ship2, puntoInicio2, horizontal2);
printTablero();
}
}
public IGameField getField(int x, int y) {
if(!dentroTablero(x, y)) {
throw new IllegalArgumentException("Fuera del trablero - intenta de nuevo: ");
}
return tablero[y][x];
}
public void printTablero() {
System.out.print("\t");
for(int i = 0; i < TABLERO_SIZE; i++) {
System.out.print(TABLERO_LETRAS[i] + "\t");
}
System.out.println();
for(int i = 0; i < TABLERO_SIZE; i++) {
System.out.print((i+1) + "\t");
for(int j = 0; j < TABLERO_SIZE; j++) {
System.out.print(tablero[i][j].getIcon() + "\t");
}
System.out.println();
}
}
private boolean preguntaDireccionValida() {
System.out.printf("%nQuieres introducir el barco horizontalmente (H) o verticalmente (V)?");
String direccion;
do {
direccion = scanner.nextLine().trim();
}while (!HORIZONTAL.equals(direccion) && !VERTICAL.equals(direccion));
return HORIZONTAL.equals(direccion);
}
private boolean preguntaDireccionValida2() {
System.out.printf("%nQuieres introducir el barco horizontalmente (H) o verticalmente (V)?");
String direccion = "HV";
Random aleatorio = new Random();
do {
direccion.charAt(aleatorio.nextInt(direccion.length()));
}while (!HORIZONTAL2.equals(direccion) && !VERTICAL2.equals(direccion));
return HORIZONTAL.equals(direccion);
}
private Point preguntaPuntoInicio(Barco ship, boolean horizontal) {
Point from;
do{
System.out.printf("%nIntroduce la posicion de %s (tamaño %d): ", ship.getNombre(), ship.getTamaño());
from = new Point(scanner.nextInt(), scanner.nextInt());
}while(!esPuntoInicioValido(from, ship.getTamaño(), horizontal));
return from;
}
private Point preguntaPuntoInicio2(Barco ship, boolean horizontal) {
Random random2 = new Random();
Point from2;
do{
from2 = new Point(random2.nextInt(10), random2.nextInt(10));
}while(!esPuntoInicioValido(from2, ship.getTamaño(), horizontal));
return from2;
}
private boolean esPuntoInicioValido(Point from, int longitud, boolean horizontal) {
int xDiff = 0;
int yDiff = 0;
if(horizontal) {
xDiff = 1;
}
else {
yDiff = 1;
}
int x = (int)from.getX() - 1;
int y = (int)from.getY() - 1;
if(!dentroTablero(x, y) || (!dentroTablero(x + longitud,y) && horizontal) || (!dentroTablero(x, y + longitud) && !horizontal)){
return false;
}
for(int i = 0; i < longitud; i++) {
if(tablero[(int)from.getY() + i *yDiff - 1]
[(int)from.getX() + i *xDiff - 1].getIcon() != AGUA){
return false;
}
}
return true;
}
private boolean dentroTablero(int x, int y){
return x <= TABLERO_SIZE && x >= 0 && y <= TABLERO_SIZE && y >= 0;}
private void colocaBarcoValido(Barco ship, Point puntoInicio, boolean horizontal) {
int xDiff = 0;
int yDiff = 0;
if(horizontal) {
xDiff = 1;
}
else {
yDiff = 1;
}
for(int i = 0; i < ship.getTamaño() ; i++) {
tablero[(int)puntoInicio.getY() + i*yDiff - 1]
[(int)puntoInicio.getX()+ i*xDiff - 1] = new BarcoField(ship);
}
}
}
The thing is that I got stuck and I don't know how to continue. Sorry for my bad English and if I placed this wrong, it is my first time using stackoverflow!

Related

Why does my super class object instance affect my inherited class object instance?

I have a super class Player, which has ArrayList<Card> cards, and ArrayList<Card> cardsOnTable. I also have a class Bot, which extends the Player class. My Card class has the used boolean property. I have a method on Player class that returns the unused cards.
My problem is, when I set my cards used in one of my Bot object instances, cards <ArrayList> also changes in other instances. Why does this happen? Did I make a mistake about inheritance?
Here are my classes:
public class Bot extends Player{
private int id;
private String name; //added to print player at the end of war (I didn't know what to write) -Gonca
private int warPoints; // war points
private int boardNum; // for connecting with board city
private int score;
private Card lastCardPlayed;
public Bot() {
super();
this.id = 0;
this.name = "Bot " + (id + 1); //if not set, then it is a Bot and it has only number
lastCardPlayed = new Card();
}
public Bot(int id) {
super();
this.id = id;
this.name = "Bot " + (this.id + 1); //if not set, then it is a Bot and it has only number
lastCardPlayed = new Card();
}
public Bot(int id, City city) {
super(id,city);
this.id = id;
this.name = "Bot " + (id + 1); //if not set, then it is a Bot and it has only number
lastCardPlayed = new Card();
System.out.println("Bot constructor with City parameter");
}
public class Player {
private int id;
private String name; //
private int warPoints; // war points
private ArrayList<Card> cards; // cards in hand
private ArrayList<Card> cardsOnTable;
private int boardNum; // for connecting with board city
private int score;
private City city;
private ArrayList<Material> resources;
int numberOfCoin;
int numberOfClay;
int numberOfOre;
int numberOfStone;
int numberOfWood;
int numberOfLoom;
int numberOfGlass;
int numberOfPapyrus;
int numberOfMilitary;
int numberOfCivilian;
int numberOfScienceRuler;
int numberOfScienceStone;
int numberOfScienceWheel;
public Player() {
this.id = 0;
this.name = "Player " + (id + 1);
this.cards = new ArrayList<>();
this.cardsOnTable = new ArrayList<>();;
this.city = new City();
this.resources = new ArrayList<>();
this.score = 0;
this.numberOfCoin = 3;
}
public Player(int id, City city) {
this.id = id;
this.city = city;
this.name = "Player " + (id + 1);
this.cards = new ArrayList<>();
this.cardsOnTable = new ArrayList<>();;
this.resources = new ArrayList<>();
this.score = 0;
this.numberOfCoin = 3;
}
public ArrayList<Card> getCards() {
ArrayList<Card> temp = new ArrayList<>();
for(int i = 0; i < cards.size(); i++)
{
if( !(cards.get(i).isUsed()))
temp.add(cards.get(i));
}
return temp;
}
public String addCardsToTable(Card c) {
if(verifySufficientResources(c)){
c.setUsed(true);
cardsOnTable.add(c);
return "";
}else{
return ("Resources not enough");
}
}
enter image description here
public class Card {
private String name; // name
private ArrayList<Material> requirements; // materials for playing this card.
private ArrayList<Material> earnings; // come from card materials
private int Id; // special card id for implementing card chain
private int nextCardId; // id of the free card from card chain.
private String color; // card color
private String photoName; // for photo directory
private int ageNumber; // age number of card.
private boolean orSituation;
private String specialFunctionName;
private boolean used;
private int cardWarPoint; // bunu sonradan ekledim aşağıdakilere göre eklemek lazım- efe
public Card(String name, ArrayList<Material> requirements, ArrayList<Material> earnings, int Id, int nextCardId, String color, String photoName, int ageNumber) {
this.name = name;
this.requirements = requirements;
this.earnings = earnings;
this.Id = Id;
this.nextCardId = nextCardId;
this.color = color;
this.photoName = photoName;
this.ageNumber = ageNumber;
this.orSituation = false;
this.specialFunctionName = "none";
this.used = false;
}
public Card(String name, ArrayList<Material> requirements, ArrayList<Material> earnings, int Id, int nextCardId, String color, String photoName, int ageNumber, boolean orSituation) {
this.name = name;
this.requirements = requirements;
this.earnings = earnings;
this.Id = Id;
this.nextCardId = nextCardId;
this.color = color;
this.photoName = photoName;
this.ageNumber = ageNumber;
this.orSituation = orSituation;
this.specialFunctionName = "none";
this.used = false;
}
public Card(String name, ArrayList<Material> requirements, ArrayList<Material> earnings, int Id, int nextCardId, String color, String photoName, int ageNumber, String specialFunctionName) {
this.name = name;
this.requirements = requirements;
this.earnings = earnings;
this.Id = Id;
this.nextCardId = nextCardId;
this.color = color;
this.photoName = photoName;
this.ageNumber = ageNumber;
this.orSituation = false;
this.specialFunctionName = specialFunctionName;
this.used = false;
}
public Card(String name, ArrayList<Material> requirements, ArrayList<Material> earnings, int Id, int nextCardId, String color, String photoName, int ageNumber, boolean orSituation, String specialFunctionName) {
this.name = name;
this.requirements = requirements;
this.earnings = earnings;
this.Id = Id;
this.nextCardId = nextCardId;
this.color = color;
this.photoName = photoName;
this.ageNumber = ageNumber;
this.orSituation = orSituation;
this.specialFunctionName = specialFunctionName;
this.used = false;
}
public Card(Card c){
this.name = c.name;
this.requirements = c.requirements;
this.earnings = c.earnings;
this.Id = c.Id;
this.nextCardId = c.nextCardId;
this.color = c.color;
this.photoName = c.photoName;
this.ageNumber = c.ageNumber;
this.orSituation = c.orSituation;
this.specialFunctionName = c.specialFunctionName;
this.used = c.used;
}
public Card() {
this.name = "";
this.requirements = new ArrayList<Material>();
this.earnings = new ArrayList<Material>();
this.Id = -1;
this.nextCardId = -1;
this.color = "";
this.photoName = "";
this.ageNumber = -1;
this.orSituation = false;
this.specialFunctionName = "";
this.used = false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Material> getRequirements() {
return requirements;
}
public void setRequirements(ArrayList<Material> requirements){
this.requirements = requirements;
}
public ArrayList<Material> getEarnings() {
return earnings;
}
public void setEarnings(ArrayList<Material> earnings) {
this.earnings = earnings;
}
public int getId(){
return Id;
}
public void setId(int Id){
this.Id = Id;
}
public int getNextCardId(){
return nextCardId;
}
public void setNextCardId(int nextCardId){
this.nextCardId = nextCardId;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getPhotoName() {
return photoName;
}
public void setPhotoName(String photoName) {
this.photoName = photoName;
}
public int getAgeNumber() {
return ageNumber;
}
public void setAgeNumber(int ageNumber) {
this.ageNumber = ageNumber;
}
public void setSpecialFunctionName(String specialFunctionName){
this.specialFunctionName = specialFunctionName;
}
public String getSpecialFunctionName(){
return this.specialFunctionName;
}
public boolean getOrSituation(){
return this.orSituation;
}
public void setOrSituation(boolean orSituation){
this.orSituation = orSituation;
}
public int getCardWarPoint() {
return cardWarPoint;
}
public int getNumberOfRequiredWood(){
for(int i = 0; i < requirements.size(); i++){
if(requirements.get(i).getName() == "Wood"){
return requirements.get(i).getCount();
}
}
return 0;
}
public int getNumberOfRequiredClay(){
for(int i = 0; i < requirements.size(); i++){
if(requirements.get(i).getName() == "Clay"){
return requirements.get(i).getCount();
}
}
return 0;
}
public int getNumberOfRequiredOre(){
for(int i = 0; i < requirements.size(); i++){
if(requirements.get(i).getName() == "Ore"){
return requirements.get(i).getCount();
}
}
return 0;
}
public int getNumberOfRequiredStone(){
for(int i = 0; i < requirements.size(); i++){
if(requirements.get(i).getName() == "Stone"){
return requirements.get(i).getCount();
}
}
return 0;
}
public int getNumberOfRequiredGlass(){
for(int i = 0; i < requirements.size(); i++){
if(requirements.get(i).getName() == "Glass"){
return requirements.get(i).getCount();
}
}
return 0;
}
public int getNumberOfRequiredLoom(){
for(int i = 0; i < requirements.size(); i++){
if(requirements.get(i).getName() == "Loom"){
return requirements.get(i).getCount();
}
}
return 0;
}
public int getNumberOfRequiredPapyrus(){
for(int i = 0; i < requirements.size(); i++){
if(requirements.get(i).getName() == "Papyrus"){
return requirements.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningWood(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "Wood"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningStone(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "Stone"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningOre(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "Ore"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningClay(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "Clay"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningGlass(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "Glass"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningLoom(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "Loom"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningPapyrus(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "Papyrus"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningCivilian(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "Civilian"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningMilitary(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "Military"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningScienceRuler(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "ScienceRuler"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningScienceWheel(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "ScienceWheel"){
return earnings.get(i).getCount();
}
}
return 0;
}
public int getNumberOfEarningScienceStone(){
for(int i = 0; i < earnings.size(); i++){
if(earnings.get(i).getName() == "ScienceStone"){
return earnings.get(i).getCount();
}
}
return 0;
}
public void setCardWarPoint(int cardWarPoint) {
this.cardWarPoint = cardWarPoint;
}
public void print(){
System.out.println("NAME: " + name + " ID:" + Id + " nextCardId: " + nextCardId + " color:" + color + " photoName: " + photoName + " ageNumber: "+ ageNumber + " orSituation: " + orSituation + " specialFunctionName: " + specialFunctionName);
System.out.print("Requirements: ");
for(int i = 0; i < requirements.size(); i++){
requirements.get(i).print();
}
System.out.println();
System.out.print("Earnings: ");
for(int i = 0; i < earnings.size(); i++){
earnings.get(i).print();
}
System.out.println();
}
#Override
public String toString() {
return "Card{" +
"name='" + name + '\'' +
", requirements=" + requirements +
", earnings=" + earnings +
", Id=" + Id +
", nextCardId=" + nextCardId +
", color='" + color + '\'' +
", photoName='" + photoName + '\'' +
", ageNumber=" + ageNumber +
", orSituation=" + orSituation +
", specialFunctionName='" + specialFunctionName + '\'' +
", cardWarPoint=" + cardWarPoint +
'}';
}
public boolean isUsed() {
return used;
}
public void setUsed(boolean used) {
this.used = used;
}
}
And here is the engine which deals with cards and players
public class PlayerEngine extends Application {
private Player player;
private ArrayList<Bot> bots;
private ArrayList<Player> allPlayers;
public PlayerEngine(int numberOfPlayers, City desiredCityOfHumanPlayer, ArrayList<City> citiesOfBots){
allPlayers = new ArrayList<>();
bots = new ArrayList<>();
player = new Player(0, desiredCityOfHumanPlayer);
allPlayers.add(player);
for(int i = 0; i < numberOfPlayers - 1; i++){
Bot bot = new Bot(i, citiesOfBots.get(i));
allPlayers.add(bot);
bots.add(bot);
}
for(int i = 0; i < bots.size(); i++){
bots.get(i).print();
}
}
public PlayerEngine(int numberOfPlayers){
allPlayers = new ArrayList<>();
bots = new ArrayList<>();
player = new Player();
allPlayers.add(player);
for(int i = 0; i < numberOfPlayers - 1; i++){
Bot bot = new Bot(i);
allPlayers.add(bot);
bots.add(bot);
}
}
public Player getHumanPlayer(){
return player;
}
public ArrayList<Bot> getBots(){
return bots;
}
public void matchPlayerWithCity(Player player, City city){
player.setCity(city);
}
#Override
public void start(Stage primaryStage) throws Exception {
System.out.println("inside start");
CityManager cityManager = new CityManager();
cityManager.createACities();
cityManager.printACities();
cityManager.createBCities();
cityManager.printBCities();
Player p = new Player();
}
public void distributeHands(ArrayList<Card> cards){
System.out.println("number of players" + allPlayers.size());
System.out.println("number of cards" + cards.size());
int count = 0;
for(int i = 0; i < 7; i++){
player.addToHandAtFirst(cards.get(count));
count++;
}
for(int i = 0; i < bots.size(); i++){
for(int j = 0; j < 7; j++){
bots.get(i).addToHandAtFirst(cards.get(count));
count++;
}
}
}
public int[] numberOfCardsOfAllPlayers(){
int [] arr = new int[allPlayers.size()];
for(int i = 0; i < arr.length; i++){
arr[i] = allPlayers.get(i).getCards().size();
}
return arr;
}
public int getHighScore(){
int max=0;
for(int i=0;i < allPlayers.size();i++){
if( allPlayers.get(i).getScore()>max){
max = allPlayers.get(i).getScore();
}
}
return max;
}
public int getPlayerPoint(Player player) {
return player.getScore();
}
public void updatePlayerPoint(Player player,int point){
player.setScore(player.getScore()+point);
}
public void increaseCoin(Player player,int coinNumber){
player.setCoin(player.getCoin()+ coinNumber);
}
public void increaseWarPoints(Player player, int warPoints){
player.setWarPoints(player.getWarPoints() + warPoints);
}
public Player getPlayer(int index){
return allPlayers.get(index);
}
public ArrayList<Card> getCardsEntity(Player player){
return player.getCards();
}
public void addToCardList(Player player,Card card)
{
player.addCardsToTable(card);
}
public void disjointCard(Player player,int cardNum){
player.getCards().remove(player.getCards().get(cardNum));
}
public void startAttack(){
// attack manager ile bağlanacak.
}
public void finishAttack(){
// attack manager ile bağlanacak.
}
public void startXOX(Boolean bool){
//xox game ile bağlanacak.
}
public ArrayList<Player> getAllPlayers(){
return allPlayers;
}
public void printPlayers(){
System.out.println();
System.out.println("LIST OF ALL PLAYERS");
System.out.println();
System.out.println("PLAYER");
player.print();
System.out.println("BOTS");
for(int i = 0; i < bots.size(); i++){
bots.get(i).print();
}
}
}
in your PlayerEngine.distributeHands(ArrayList<Card> cards)
you are adding the same instances to players and bots
they handle the same objects passing through the same references
if a modification is made, it is made on the same objects and it will be visible by any other object which has the same reference

"Can not find a symbol" inside a different class while attempting to call it from main

I am sort of new to coding, and I have a coding assignment that helps us practice with constructors and classes. I feel that I am well versed for my level, so I came here posting this because I was stumped. I get an error in Main when trying to do print getColleges(20)), a method inside CollegeGroup. CollegeGroup is supposed to be an array of College objects. Colleges 20 is supposed to sort colleges under a tuition of $20,000. However I get the error
cannot find symbol
symbol: method getColleges(int)
location: class Main
What do I change so i can correctly print getColleges(20))? Thank you for your help
College.java
package colleges;
public class College {
private int tuition;
private String name;
private String region;
private double minGPA;
public College(int aTuition, String aName, String aRegion, double minScore) {
tuition = aTuition;
name = aName;
region = aRegion;
minGPA = minScore;
}
public double getMinimumGPA() {
return minGPA;
}
public String getName() {
return name;
}
public int getTuition() {
return tuition;
}
public String getRegion() {
return region;
}
public void setTuition(int aTuition) {
tuition = aTuition;
}
public String toString() {
return ("College: " + name + "\tTuition: " + tuition
+ "\tRegion: " + region);
}
CollegeGroup.java
package colleges;
import java.util.List;
import java.util.ArrayList;
public class CollegeGroup {
private List<College> colleges = new ArrayList<College>();
public void addCollege(College aCollege) {
colleges.add(aCollege);
}
public void removeCollege(String collegeName) {
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getName().equalsIgnoreCase(collegeName)) {
colleges.remove(i);
}
}
}
public void updateTuition(String collegeName, int newTuition) {
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getName().equalsIgnoreCase(collegeName)) {
colleges.get(i).setTuition(newTuition);
}
}
}
public List<College> getColleges() {
return colleges;
}
public List<College> getColleges(String region) {
//return a list of colleges in the given region
List<College> regionCollege = new ArrayList<College>();
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getRegion().equalsIgnoreCase(region)) {
regionCollege.add(colleges.get(i));
}
}
return regionCollege;
}
public List<College> getColleges(int maxTuition) {
//return a list of colleges with tuition below maxTuition
List<College> mTut = new ArrayList<College>();
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getTuition() < maxTuition) {
mTut.add(colleges.get(i));
}
}
return mTut;
}
public List<College> getColleges(double myGPA, int maxTuition) {
//return a list of colleges with minimum GPA requirements below
//myGPA, and tuitions below maxTuition
List<College> perfCollege = new ArrayList<College>();
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getTuition() < maxTuition && colleges.get(i).getMinimumGPA() <= myGPA) {
perfCollege.add(colleges.get(i));
}
}
return perfCollege;
}
public void sortCollegesByRegion() {
//sort in the following order:
//Northeast, Southeast, MidWest, West
List<College> Northeast = new ArrayList<College>();
List<College> Southeast = new ArrayList<College>();
List<College> MidWest = new ArrayList<College>();
List<College> West = new ArrayList<College>();
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getRegion().equalsIgnoreCase("Northeast")) {
Northeast.add(colleges.get(i));
} else if (colleges.get(i).getRegion().equalsIgnoreCase("Southeast")) {
Southeast.add(colleges.get(i));
} else if (colleges.get(i).getRegion().equalsIgnoreCase("MidWest")) {
MidWest.add(colleges.get(i));
} else if (colleges.get(i).getRegion().equalsIgnoreCase("West")) {
West.add(colleges.get(i));
}
}
}
public void sortCollegesByMinimumGPA() {
//code goes here, sort from low to high.
int smallest = Integer.MAX_VALUE;
List<College> sorted = new ArrayList<College>();
while (colleges.size() != 0) {
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getMinimumGPA() < smallest) {
sorted.add(colleges.get(i));
colleges.remove(i);
}
}
}
sorted = colleges;
}
public void sortCollegesByTuition() {
//code goes here, sort from low to high.
int smallest = Integer.MAX_VALUE;
List<College> sorted = new ArrayList<College>();
while (colleges.size() != 0) {
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getTuition() < smallest) {
sorted.add(colleges.get(i));
colleges.remove(i);
}
}
}
sorted = colleges;
}
public String toString() {
String out = "";
for (int i = 0; i < colleges.size(); i++) {
out += colleges.get(i).toString(); //test whether toString is necessary on colleges.get()
out += "\n";
}
return out.substring(0, out.length() - 1);
}
Main.java
package colleges;
public class Main {
public static void main(String[] args) {
CollegeGroup collegeList = new CollegeGroup();
College colUni = new College(17025,"College University", "Northeast", 2.3);
College westCol = new College(28450,"Westcoast College", "West", 2.9);
College budgCol = new College(700,"Budget College", "Southeast", 1.0);
College goodUni = new College(95000,"Reallygood University", "Northeast", 3.9);
College partyUni = new College(22150,"Partyschool U ", "West", 2.1);
College hogwarts = new College(12000,"Hogwarts", "Northeast", 3.5);
collegeList.addCollege(colUni);
collegeList.addCollege(westCol);
collegeList.addCollege(budgCol);
collegeList.addCollege(goodUni);
collegeList.addCollege(partyUni);
collegeList.addCollege(hogwarts);
System.out.println(collegeList.getColleges());
System.out.println(colUni.toString());
budgCol.setTuition(8);
System.out.println(getColleges(20));
}

Java blackjack program

So I rewrote it with your suggestion (Todd Hopp) and updated the post in the (*) section in the BlackJack class so you can see how I have it now but I'm still getting the same errors and it is not printing the computePlayerValue for some reason....
ERROR:
Exception in thread "main" java.lang.NumberFormatException: For input string: "King" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at BlackJack.dealCards(BlackJack.java:25)
at PlayCardGame.main(PlayCardGame.java:9)
P.S. I'm was trying to look this up in the book but couldn't find the answer...The BlackJack class is partially source code from an earlier chapter in the book and I couldn't figure out if it was necessary to have super(); in the constructor there? I thought it only had to do if the parent class constructor had an argument? Any help on if it has to be there and if so what it's doing.
BlackJack Class
public class BlackJack extends CardGameFP{
int computePlayerValue;
int computeDealerValue;
int cardValue;
public BlackJack() {
**super();**
player1 = 2;
player2 = 2;
}
public void display() {
System.out.println("BlackJack");
}
//*************************************************************
public int getCardValue(Card card) {
final String rank = card.getRank();
switch (rank) {
case "Ace":
return 1;
case "King":
case "Queen":
case "Jack":
return 10;
default:
return Integer.parseInt(rank);
}
}
public void dealCards() {
//Player 1
System.out.println("Player 1:");
for(int x = 0; x < playerHand; x++) {
shuffle();
System.out.println(fullDeck[x].getRank() + " of " + fullDeck[x].getSuit());
}
cardValue1 = getCardValue(fullDeck[0]);
cardValue2 = getCardValue(fullDeck[1]);
computePlayerValue = cardValue1 + cardValue2;
System.out.println(computePlayerValue);
}
//*************************************************************
//Dealer hand
System.out.println("\nPlayer 2:");
for(int x = 0; x < player2; x++) {
System.out.println(fullDeck[x].getRank() + " of " + fullDeck[x].getSuit() );
shuffle();
}
}
}
public class Card {
protected String suit;
protected int value;
protected String rank;
protected final int LOW_VALUE = 1;
protected final int HIGH_VALUE = 13;
public String getRank() {
return rank;
}
public int getValue() {
return value;
}
public String getSuit() {
return suit;
}
public void setSuit(String st) {
suit = st;
}
public void setValue(int val) {
if(val >= LOW_VALUE && val <= HIGH_VALUE) {
value = val;
}
else {
value = LOW_VALUE;
}
if(val == 1) {
rank = "Ace";
}
else if(val == 11) {
rank = "Jack";
}
else if(val == 12) {
rank = "Queen";
}
else if(val == 13) {
rank = "King";
}
else {
rank = Integer.toString(value);
}
}
}
CardGame Class
abstract public class CardGameFP {
int suitNum = 1;
int val = 1;
int player1;
int player2;
protected final int DECK_OF_CARDS = 52;
Card fullDeck[] = new Card[DECK_OF_CARDS];
protected final int LOW_VALUE = 1;
protected final int HIGH_VALUE = 13;
protected final int HIGH_SUIT = 4;
protected final int CARDS_IN_SUIT = 13;
public abstract void display();
public abstract void dealCards();
public CardGameFP() {
for(int i = 0; i < fullDeck.length; i++) {
fullDeck[i] = new Card();
if(suitNum == 1) {
fullDeck[i].setSuit("Spades");
}
else if(suitNum == 2) {
fullDeck[i].setSuit("Hearts");
}
else if(suitNum == 3) {
fullDeck[i].setSuit("Diamonds");
}
else {
fullDeck[i].setSuit("Clubs");
}
fullDeck[i].setValue(val);
val++;
if(val > HIGH_VALUE) {
suitNum++;
val = 1;
}
}//end for
}
public void shuffle() {
for(int firstCard = 0; firstCard < DECK_OF_CARDS; firstCard++ ) {
firstCard = ((int)(Math.random() * 500) % DECK_OF_CARDS);
int secondCard = ((int)(Math.random() * 500) % DECK_OF_CARDS);
Card temp = fullDeck[firstCard];
fullDeck[firstCard] = fullDeck[secondCard];
fullDeck[secondCard] = temp;
}
}
}
PlayCardGame Class
PlayerCardGame
public class PlayCardGame {
public static void main(String[] args) {
Card CG = new Card();
BlackJack BJ = new BlackJack();
BJ.display();
BJ.dealCards();
}
}
Instead of this line:
cardValue = Integer.parseInt(fullDeck[0].getRank());
I suggest that you create a getCardValue(Card) method:
public int getCardValue(Card card) {
final String rank = card.getRank();
switch (rank) {
case "Ace":
return 1;
case "King":
case "Queen":
case "Jack":
return 10;
default:
return Integer.parseInt(rank);
}
}
and then use:
cardValue = getCardValue(fullDeck[0]);
EDIT: Following the suggestion by #WorldSEnder, you can define a Rank enum:
public enum Rank {
ACE("Ace", 1),
TWO("2", 2),
...
QUEEN("Queen", 10),
KING("King", 10);
private final String displayName;
private final int value;
protected Rank(String displayName, int value) {
this.displayName = displayName;
this.value = value;
}
public String displayName() {
return displayName;
}
public int value() {
return value;
}
}
Then you can modify Card to use a Rank instead of a String for the rank and use:
cardValue = fullDeck[0].getRank().value();
When you call :
cardValue = Integer.parseInt(fullDeck[0].getRank());
the method Interger.parseInt() is attempting to read an int from a string. The problem is that some cards have ranks which themselves are not strings like, King. So when you return the rank of that card, parseInt() doesn't know how to handle King. You should instead be getting the cards actual value using fullDeck[0].getVaule() and parsing that instead. It will be a string between 1 and 13.

Applet does not load on html page

I have this applet and i cant figure out why it doesnt load on html page.I have added full permissions in java.policy file. I use the default html file from NetBeans Applet's output.
/* Hearts Cards Game with AI*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.awt.Graphics;
import java.awt.Image;
import java.security.AccessController;
import javax.swing.ImageIcon;
import javax.swing.*;
import javax.swing.JPanel;
public class Game extends JApplet implements MouseListener, Runnable {
int initNoCards = 13;
int width, height;
boolean endGame = false;
int turn = -1;
int firstCard = 0;
int firstTrick = 0;
String leadingSuit = null;
Cards leadingCard = null;
Cards playCard = null;
String startCard = "c2";
Cards[] trickCards = new Cards[4];
ArrayList<Cards>[] playerCards = new ArrayList[4];
ArrayList<Cards>[] takenCards = new ArrayList[4];
boolean heartsBroken = false;
ArrayList<Cards> cards = new ArrayList<Cards>();
String[] hearts = {"h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "h10", "h12", "h13", "h14", "h15"};
String queen = "s13";
int cardHeight = 76;
int cardWidth = 48;
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
int selectedCard = -1;
//set the background image
Image backImage = new ImageIcon("deck\\back2.png").getImage();
public void GetDataFromXML() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
boolean image = false;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
if (qName.equalsIgnoreCase("IMAGE")) {
image = true;
}
}
#Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (name) {
cards.add(new Cards(s));
name = false;
}
if (image) {
image = false;
}
}
};
saxParser.parse("deck\\deck.xml", handler);
} catch (Exception e) {
}
}
//function for comparing cards from same suite
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
//checks if a card is valid to play
public boolean ValidMove(Cards c) {
if (firstCard == 0) {
if (c.getName().equals(startCard)) {
firstCard = 1;
return true;
}
return false;
}
boolean result = playerCards[turn].indexOf(c) >= 0;
if (leadingSuit == null) {
return result;
}
boolean found = false;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) == leadingSuit.charAt(0)) {
found = true;
break;
}
}
if (!found) {
boolean justHearts = true;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) != 'h') {
justHearts = false;
break;
}
}
if (firstTrick == 0) {
if (c.getName().equals(queen)) {
return false;
}
if (!justHearts && c.getName().charAt(0) == 'h') {
return false;
}
} else {
if (c.getName().charAt(0) == 'h' && leadingSuit == null && !heartsBroken && !justHearts) {
return false;
}
}
} else {
if (c.getName().charAt(0) != leadingSuit.charAt(0)) {
return false;
}
}
return result;
}
#Override
public void init() {
GetDataFromXML();
setSize(500, 500);
width = super.getSize().width;
height = super.getSize().height;
setBackground(Color.white);
addMouseListener(this);
for (int i = 0; i < cards.size(); i++) {
System.out.println(cards.get(i).getName());
System.out.println(cards.get(i).getImage());
}
Shuffle();
}
public int GetTrickCount() {
int count = 0;
for (int i = 0; i < trickCards.length; i++) {
if (trickCards[i] != null) {
count++;
}
}
return count;
}
public void ResetTrick() {
for (int i = 0; i < trickCards.length; i++) {
trickCards[i] = null;
}
}
#Override
public void run() {
try {
PlayTurn();
} catch (InterruptedException ex) {
}
}
public void start() {
Thread th = new Thread(this);
th.start();
}
//function for shuffling cards and painting players cards
public void Shuffle() {
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
}
ArrayList<Cards> list = new ArrayList<Cards>();
list.addAll(cards);
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getName() + " ");
}
//initializare liste carti
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
for (int j = 0; j < initNoCards; j++) {
playerCards[i].add((list.get(j + i * initNoCards)));
if (list.get(j + i * initNoCards).getName().equals(startCard)) {
turn = i;
}
}
Collections.sort(playerCards[i], c);
ShowCards(i);
}
for (int i = 0; i < playerCards[0].size() - 1; i++) {
rectangles.add(new Rectangle((141 + 1) + 13 * i - 2, 350 + 1, 13 - 2, cardHeight - 1));
}
rectangles.add(new Rectangle((141 + 1) + 13 * 12 - 2, 350 + 1, cardWidth, cardHeight - 1));
ShowPlayersCards();
}
Comparator<Cards> c = new Comparator<Cards>() {
#Override
public int compare(Cards o1, Cards o2) {
if (o2.getName().charAt(0) != o1.getName().charAt(0)) {
return o2.getName().charAt(0) - o1.getName().charAt(0);
} else {
int a, b;
a = Integer.parseInt(o1.getName().substring(1));
b = Integer.parseInt(o2.getName().substring(1));
return a - b;
}
}
};
public void PlayTurn() throws InterruptedException {
endGame = true;
System.out.println("Its " + turn);
for (int i = 0; i < 4; i++) {
if (!playerCards[i].isEmpty()) {
endGame = false;
}
}
if (endGame) {
System.out.println("Game over!");
GetPlayersScore();
return;
}
if (turn != 0) {
Random r = new Random();
int k = r.nextInt(playerCards[turn].size());
Cards AIcard = playerCards[turn].get(k);
while (!ValidMove(AIcard)) {
k = r.nextInt(playerCards[turn].size());
AIcard = playerCards[turn].get(k);
}
leadingCard = AIcard;
playCard = AIcard;
} else {
System.out.println("\nIt is player's (" + turn + ") turn");
System.out.println("Player (" + turn + ") enter card to play:");
leadingCard = null;
playCard = null;//new Cards(read);
while (true) {
if (playCard != null) {
break;
}
Thread.sleep(50);
}
}
repaint();
Thread.sleep(1000);
repaint();
if (playCard.getName().charAt(0) == 'h') {
heartsBroken = true;
}
playerCards[turn].remove(playCard);
trickCards[turn] = playCard;
if (GetTrickCount() == 1)//setez leading suit doar pentru trickCards[0]
{
leadingSuit = GetSuit(playCard);
}
System.out.println("Leading suit " + leadingSuit);
System.out.println("Player (" + turn + ") chose card " + playCard.getName() + " to play");
ShowTrickCards();
ShowPlayersCards();
if (GetTrickCount() < 4) {
turn = (turn + 1) % 4;
} else {
turn = GetTrickWinner();
leadingSuit = null;
firstTrick = 1;
playCard = null;
repaint();
}
PlayTurn();
}
public void ShowTrickCards() {
System.out.println("Cards in this trick are:");
for (int i = 0; i < 4; i++) {
if (trickCards[i] != null) {
System.out.print(trickCards[i].getName() + " ");
}
}
}
public String GetSuit(Cards c) {
if (c.getName().contains("c")) {
return "c";
}
if (c.getName().contains("s")) {
return "s";
}
if (c.getName().contains("h")) {
return "h";
}
if (c.getName().contains("d")) {
return "d";
}
return null;
}
public String GetValue(Cards c) {
String get = null;
get = c.getName().substring(1);
return get;
}
public int GetTrickWinner() {
int poz = 0;
for (int i = 1; i < 4; i++) {
if (trickCards[poz].getName().charAt(0) == trickCards[i].getName().charAt(0) && lowerThan(trickCards[poz], trickCards[i]) == true) {
poz = i;
}
}
System.out.println("\nPlayer (" + poz + ") won last trick with card " + trickCards[poz].getName());
ResetTrick();
return poz;
}
public void ShowPlayersCards() {
ShowCards(0);
ShowCards(1);
ShowCards(2);
ShowCards(3);
}
public void GetPlayersScore() {
GetScore(0);
GetScore(1);
GetScore(2);
GetScore(3);
}
public void ShowCards(int player) {
System.out.print("\nPlayer (" + player + ") cards: ");
for (int i = 0; i < playerCards[player].size(); i++) {
System.out.print(playerCards[player].get(i).getName() + " ");
}
System.out.println();
}
public int GetScore(int player) {
int score = 0;
for (int i = 0; i < takenCards[player].size(); i++) {
for (int j = 0; j < hearts.length; j++) {
if (takenCards[player].get(i).getName().equals(hearts[j])) {
score++;
break;
}
}
if (takenCards[player].get(i).getName().equals(queen)) {
score += 13;
}
}
return score;
}
#Override
public void paint(Graphics g) {
g.drawImage(backImage, 0, 0, getWidth(), getHeight(), this);
for (int i = 0; i < playerCards[0].size(); i++) {
if (selectedCard == i) {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 340, null);
} else {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 350, null);
}
if (trickCards[0] != null) {
g.drawImage(trickCards[0].getImage(), 225, 250, 48, 76, null);
}
if (trickCards[1] != null) {
g.drawImage(trickCards[1].getImage(), 177, 174, 48, 76, null);
}
if (trickCards[2] != null) {
g.drawImage(trickCards[2].getImage(), 225, 98, 48, 76, null);
}
if (trickCards[3] != null) {
g.drawImage(trickCards[3].getImage(), 273, 174, 48, 76, null);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
if (turn != 0) {
return;
}
for (int i = 0; i < rectangles.size(); i++) {
if (rectangles.get(i).contains(e.getPoint())) {
if (i == selectedCard) {
if (ValidMove(playerCards[0].get(i))) {
selectedCard = -1;
rectangles.get(rectangles.size() - 2).width = rectangles.get(rectangles.size() - 1).width;
playCard = playerCards[0].get(i);
leadingCard = playCard;
rectangles.remove(rectangles.size() - 1);
trickCards[0] = playerCards[0].remove(i);
} else {
if (firstCard == 0) {
JOptionPane.showMessageDialog(this, "You have to play 2 of clubs!");
}
}
} else {
selectedCard = i;
rectangles.get(i).y -= 10;
}
repaint();
break;
}
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
class Cards extends JPanel {
private String name;
private String image;
private Image img;
public Cards(String name) {
super();
this.name = name;
this.image = "deck\\" + name + ".png";
this.img = new ImageIcon(image).getImage();
}
public Cards() {
super();
this.name = null;
this.image = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Image getImage() {
return img;
}
public void setImage(String image) {
this.image = image;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Cards)) {
return false;
}
Cards c = (Cards) obj;
return name.equals(c.getName()) && image.equals(c.getImage());
}
#Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 31 * hash + (this.image != null ? this.image.hashCode() : 0);
return hash;
}
#Override
public void paint(Graphics g) {
g.drawImage(img, WIDTH, HEIGHT, this);
}
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
public int compareTo(Cards c) {
if (c.getName().charAt(0) != name.charAt(0)) {
return c.getName().charAt(0) - name.charAt(0);
} else {
int a, b;
a = Integer.parseInt(name.substring(1));
b = Integer.parseInt(c.getName().substring(1));
return a - b;
}
}
}
HTML
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<APPLET codebase="classes" code="Game.class" width=350 height=200></APPLET>
</P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
Image backImage = new ImageIcon("deck\\back2.png").getImage();
If I am the user of the applet when it is on the internet, the will cause the JRE to search for a File relative to the current user directory on my PC, either that or the cache of FF. In either case, it will not locate an image by the name of back2.png.
For fear of sounding like a looping Clip:
Resources intended for an applet (icons, BG image, help files etc.) should be accessed by URL.
An applet will not need trust to access those resources, so long as the resources are on the run-time class-path, or on the same server as the code base or document base.
Further
I have added full permissions in java.policy file.
This is pointless. It will not be workable at time of deployment unless you control every machine it is intended to run on. If an applet needs trust in a general environment, it needs to be digitally signed. You might as well sign it while building the app.
cant figure out why it doesnt load on html page.
Something that would assist greatly is to configure the Java Console to open when an applet is loaded. There is a setting in the last tab of the Java Control Panel that configures it.

transfer form one state to another

I use centralized patter to coding vending machine. The problem is I found out that I cannot change states. In the constructor, I initialized state to Ls[0], but when I go to the method public void coin() to change the state, I found that the state doesn't changed. The part of my code is:
class Vending_machine {
State st;
private int price;
private int k;
private int k1;
private int t;
private int s;
private State[] Ls;
public Vending_machine() {
Ls = new State[7];
Ls[0] = new Idle();
Ls[1] = new Coins_inserted();
Ls[2] = new Sugar();
Ls[3] = new No_small_cups();
Ls[4] = new No_large_cups();
Ls[5] = new Exit();
Ls[6] = new Start();
st = Ls[0];
st.vm = this;
k = 0;
k1 = 0;
t = 0;
price = 0;
s = 0;
}
public void setK(int k) {
this.k = k;
}
public int getK() {
return k;
}
public void setS(int s) {
this.s = s;
}
public int getS() {
return s;
}......
public void coin() {
st.coin();
if (st.getId() == 0) {
if (t + 25 < price) {
// t=t+25;
st = Ls[0];
}
if (t + 25 >= price && price > 0) {
// s=0;
// t=0;
st = Ls[1];
}
}......
class State {
public Vending_machine vm;
int id = 0;
public void coin() {}
public void small_cup() {}
public void large_cup() {}
public void sugar() {}
public void tea() {}
public void insert_large_cups(int n) {}
public void insert_small_cups(int n) {}
public void set_price(int p) {}
.......
}
class Idle extends State {
public void coin() {
if (vm.getT() + 25 < vm.getPrice()) {
vm.setT((vm.getT()) + 25);
System.out.println(vm.getT());
}
else if ((vm.getT() + 25 >= vm.getPrice()) && (vm.getPrice() > 0)) {
vm.setS(0);
vm.setT(0);
}
}......

Categories