how do I clear my memory after the fifth action?
to be able to create a new basket again and fill it with new balls.
Because now, when you re-create the basket and fill it with balls,
the error appears on the second action (filling the basket)
how to clear the cache with the first bucket so that you can enter the second one?
//main
public class Dialogue {
private static Scanner scanner = new Scanner(System.in);
private static boolean buildBasket = false;
private static boolean completedBasket = false;
private Basket basket;
private static int volumeOfBasket = 0;
public static void main(String[] args) {
boolean buildBasket = false;
boolean completedBasket = false;
Basket basket =null;
int volumeOfBasket = 0;
try {
while (true) {
System.out.println("1 - build а basket");
System.out.println("2 - add balls to basket");
System.out.println("3 - output information about basket");
System.out.println("4 - weight of balls in the basket");
System.out.println("5 - quantity red balls");
int i = ScunnerInformation.checkInformatio();
if (i == 1) {
System.out.println("what max count of ball will into basket?");
volumeOfBasket = ScunnerInformation.getVolumeBasket();
Basket newBasket = new Basket("<Basketballs>", volumeOfBasket);
System.out.println("Basket was build with name: " + newBasket.getNameBasket() +
" and with the size " + newBasket.getVolume());
buildBasket = true;
basket = newBasket;
} else if (i == 2) {
if (buildBasket) {
basket = WorkWithBasket.fillBasket(basket);
completedBasket = true;
System.out.println("you have successfully added balls to the basket");
}else {
System.out.println("error");
}
} else if (i == 3) {
if (completedBasket) {
WorkWithBasket.InfoOut(basket);
} else {
System.out.println("error");
}
}else if (i == 4) {
if (completedBasket) {
System.out.println("weight basket: " + WorkWithBasket.countWeight(basket));
} else {
System.out.println("error");
}
}else if (i==5) {
if (completedBasket) {
System.out.println(WorkWithBasket.countRedBalls(basket) + " it it number of red balls");
} else {
System.out.println("error");
}
} else if (i == 6) {
break;
}
}
}finally {
if (scanner!=null){
scanner.close();
}
}
}
//fillBasket
public class WorkWithBasket {
public static Basket fillBasket(Basket basket){
for(int i =0; i < basket.getVolume(); i++){
Ball temp = new Ball(Color.getRandomColor(), WorkWithBall.CostBall(),WorkWithBall.WeightBall());
basket.addBall(temp);
}
return basket;
}
//addBall
public void addBall(Ball ball){
if (ball !=null){
basket[ball.getId() -1] = ball;
}
}
//basket initialization
public class Basket {
private Ball[] basket;
public Basket(){
this.basket = new Ball[this.volume];
}
public Basket (String nameBasket, int volume){
this.basket = new Ball[volume];
}
public Ball[] getBasket(){
return basket.clone();
}
public void addBall(Ball ball){
if (ball !=null){
basket[ball.getId() -1] = ball;
}
}
Related
So when I run the code(there are 5 more files that go with this) It is supposed to run a card game up to 10 rounds and determine a winner. However I only get up to the first round and then it terminates. I got some help with what might be wrong. I need to reinitialize my player so it stops giving me a
NullPointerException
import java.util.ArrayList;
import java.util.Random;
public class Game
{
private static deckOfCards deck = new deckOfCards();
private static ArrayList<Card> table = new ArrayList<>();
private static Card topCard;
private static Player p1 = new Player("Player One");
private static Player p2 = new Player("Player Two");
private static Player currentPlayer = p1;
private static int rounds = 1;
private static boolean gameOver = false;
public static void startGame()
{
System.out.println("Starting game now:");
dealCards();
chooseFirstPlayer();
playRounds();
declareWinner();
}
public static void dealCards()
{
for (int i = 0; i < 26; i++)
{
p1.takeCard(deck.deal());
p2.takeCard(deck.deal());
}
}
public static void chooseFirstPlayer()
{
Random r = new Random();
int n = r.nextInt(2);
if (n == 1)
{
Player temp = p1;
p1 = p2;
p2 = temp;
}
}
public static void playRounds()
{
while (rounds <= 10 && (gameOver == false))
{
System.out.println("Round " + rounds);
System.out.println();
showHand();
playRound();
rounds++;
}
}
public static void playRound()
{
boolean suitMatch = false;
Card cardToPlay;
if ((p1.handSize() == 52) || (p2.handSize() == 52))
{
gameOver = true;
}
while (suitMatch == false)
{
cardToPlay = currentPlayer.playCard();
table.add(cardToPlay);
suitMatch = checkSuitMatch();
if (suitMatch == false)
switchCurrentPlayer();
}
collectCards();
System.out.println();
try
{
Thread.sleep(500);
}
catch (InterruptedException e){
}
}
public static void switchCurrentPlayer()
{
if (currentPlayer == p1)
currentPlayer = p2;
else if (currentPlayer == p2)
currentPlayer = p1;
}
public static boolean checkSuitMatch()
{
int tableSize = table.size();
int lastSuit;
int topSuit;
if (tableSize < 2)
{
return false;
}
else
{
lastSuit = table.get(tableSize - 1).getSuit();
topSuit = table.get(tableSize - 2).getSuit();
}
if (lastSuit == topSuit)
{
System.out.println();
System.out.println(currentPlayer.getName() + " wins the round!");
System.out.println();
return true;
}
return false;
}
public static void collectCards()
{
System.out.print(currentPlayer.getName() + " takes the table (" + table.size() + "): ");
displayTable();
for (int i = 0; i < table.size(); i++)
{
Card cardToTake = table.get(i);
currentPlayer.takeCard(cardToTake);
}
table.clear();
}
public static void displayTable()
{
for (int i = 0; i < table.size(); i++)
{
if (table.get(i) != null)
{
System.out.print(table.get(i).getName() + " ");
}
}
System.out.println();
System.out.println();
}
public static void showHand()
{
p1.showHand();
p2.showHand();
}
public static void declareWinner()
{
if (p1.handSize() > p2.handSize())
{
System.out.println(p1.getName().toUpperCase() + " wins " + "by having " + p1.handSize() + " cards!");
}
else if (p2.handSize() > p1.handSize())
{
System.out.println(p2.getName().toUpperCase() + " wins " + "by having " + p2.handSize() + " cards!");
}
else
{
System.out.println("It's a draw.");
}
System.out.println();
}
public static void main(String[] args)
{
startGame();
}
}
Here is my player class just incase:
public class Player
{
private Hand hand; //for the player's hand
private String name;
//Constructors
public Player(String name)
{
hand = new Hand();
this.name = name;
}
//prints and determines the card the player will play
public Card playCard()
{
Card playerCard = hand.playCard();
System.out.println(String.format("%5s", name) + playerCard.getName());
return playerCard;
}
//takes the card if player can match
public void takeCard(Card card)
{
hand.addCard(card);
}
public String getName()
{
return name;
}
//how the hand of player
public void showHand()
{
System.out.println(name + " hand " + hand.getSize() + ":");
hand.show();
System.out.println();
}
//get the size of players' hand
public int handSize()
{
return hand.getSize();
}
}
I'm almost done with this java game project. I just have to add a defeated enemy's money to the main character's bag. I also have to add weapons and armor if they are better than the main character's weapons and armor. How do I add the enemy's money to the main character's money? In my mind, main_ch.getBag().getMoney() = main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney(); should work, but it doesn't.
Here is my main class:
import java.util.Scanner;
import Character.Character;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("> Welcome to The Game Project <");
System.out.println("\n >> Input Main Character Name: ");
String main_name = scanner.nextLine();
System.out.println(">> Input Main Character Power: ");
int main_power=scanner.nextInt();
System.out.println(">> Input Main Character Hp: ");
int main_hp=scanner.nextInt();
System.out.println("----------------------------------------------------");
Character main_ch=new Character (main_hp,main_power,main_name);
show_status(main_ch);
check_bag(main_ch);
Character enemies[]=new Character [10];
enemies[0]= new Character("Werewolf");
enemies[1]= new Character("Vampire");
enemies[2]= new Character("Alien");
enemies[3]= new Character("Witch");
enemies[4]= new Character("Ghost");
enemies[5]= new Character("Skeleton");
enemies[6]= new Character("Zombie");
enemies[7]= new Character("Demon");
enemies[8]= new Character("Mummy");
enemies[9]= new Character("Dragon");
boolean check = false;
int dead_count=0;
while(true) {
Random rnd=new Random();
int selected = rnd.nextInt(enemies.length); //random enemy selected
System.out.println();
System.out.println(">>>>> An enemy has appeared! <<<<<");
while(enemies[selected].getHp()>0) {
System.out.println();
System.out.println(">>>>> "+enemies[selected].getName()+" wants to fight!");
show_status(enemies[selected]);
check_bag(enemies[selected]);
System.out.println();
System.out.println(">> What do you want to do?");
System.out.println("\t1. Fight!");
System.out.println("\t2. Use skill.");
System.out.println("\t3. Check your stats.");
int input = scanner.nextInt();
if(input==1) {
int damageToEnemy = main_ch.hit_point();
int damageTaken = enemies[selected].hit_point();
enemies[selected].hp -= damageToEnemy;
main_ch.hp -= damageTaken;
if(enemies[selected].hp <= 0) {
enemies[selected].hp=0;
dead_count=dead_count+1;
main_ch.level=main_ch.level+1; //gain one level after enemy defeated
System.out.println(">> You defeated the enemy and gained a level!");
// The below code also doesn't work.
int pickUpMoney = main_ch.getBag().getMoney();
pickUpMoney=main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney();
System.out.println();
System.out.println("You found "+enemies[selected].getBag().getMoney()+" dollars. You now have "+main_ch.getBag().getMoney()+" dollars in your bag."); //take defeated enemy's money
for(int i = 0; i<4; i++) {
if(enemies[selected].getWeapon().getPower() > main_ch.getWeapon().getPower()) {
main_ch.getBag().getWeaponArray()[i]=enemies[selected].getBag().getWeaponArray()[i];
System.out.println("You found better weapons! They have been added to your bag.");
}
}
for(int i = 0; i<4; i++) {
if(enemies[selected].getArmor().getDefense()>main_ch.getArmor().getDefense()) {
main_ch.getBag().getArmorArray()[i]=enemies[selected].getBag().getArmorArray()[i];
System.out.println("You found better armor! They have been added to your bag.");
}
}
break;
}
System.out.println("\n>> You caused "+ damageToEnemy +" damage to the enemy! Their hp is now "+ enemies[selected].hp+".");
System.out.println(">> You received "+ damageTaken +" damage from the enemy! Your hp is now "+main_ch.hp+".");
if(main_ch.hp <=0) {
System.out.println();
System.out.println(">> Oh no! You died! Better luck next time. Thanks for playing!");
System.out.println();
break;
}
}
else if(input==2) {
if(main_ch.getSkill()>0 && main_ch.getMp()>0) {
main_ch.useSkill();
System.out.println("\t>> You used a skill. Your hit point increased to "+main_ch.hit_point()+". Your MP decreased to "+main_ch.getMp()+".");
}
else {
if(main_ch.getSkill()<=0) {
System.out.println("You have no skill points left.");
}
else{
System.out.println("\t>> Your MP is too low to use skill.");
}
}
}
else if(input==3) {
System.out.println();
show_status(main_ch);
check_bag(main_ch);
}
else {
System.out.println(">> You have entered an invalid key.");
}
}
if(dead_count==enemies.length) {
check=true;
}
if(check) {
System.out.println();
System.out.println(">>>>>>>>>> You won! Congratulations, you defeated all of your enemies! <<<<<<<<<");
break;
}
if(main_ch.hp <=0) {
System.out.println();
System.out.println(">> Oh no! You died! Better luck next time. Thanks for playing!");
System.out.println();
break;
}
}
}
public static void show_status(Character character) {
System.out.println("----------------- Character Status -----------------");
System.out.println("\tCharacter Name:\t\t"+character.getName());
System.out.println("\tCharacter HP:\t\t"+character.getHp());
System.out.println("\tCharacter Power:\t"+character.getPower());
System.out.println("\tCharacter Defense:\t"+character.getDefense());
System.out.println("\tCharacter MP:\t\t"+character.getMp());
System.out.println("\tCharacter Level:\t"+character.getLevel());
System.out.println("\tCharacter Hit Point:\t"+character.hit_point());
System.out.println("\tCharacter Skill:\t"+character.getSkill());
System.out.println("\tWeapon Name:\t\t"+character.getWeapon().getName());
System.out.println("\tWeapon Power:\t\t"+character.getWeapon().getPower());
System.out.println("\tArmor Name:\t\t"+character.getArmor().getName());
System.out.println("\tArmor Defense:\t\t"+character.getArmor().getDefense());
System.out.println("----------------------------------------------------");
}
public static void check_bag(Character character) {
System.out.println("-------------------- Bag Status --------------------");
System.out.println("\tMoney:\t\t\t$"+ character.getBag().getMoney());
for(int i = 0; i<4; i++) {
System.out.println("\tWeapon Name/Power:\t"+ character.getBag().getWeaponArray()[i].getName()+" // "+character.getBag().getWeaponArray()[i].getPower());
}
for(int i = 0; i<4; i++) {
System.out.println("\tArmor Name/Defense:\t"+ character.getBag().getArmorArray()[i].getName()+" // "+character.getBag().getArmorArray()[i].getDefense());
}
System.out.println("----------------------------------------------------");
}
}
Here is my Character class:
package Character;
import java.util.Random;
import Equipment.*;
public class Character {
private Armor armor = new Armor();
private Weapon weapon = new Weapon();
private Bag bag = new Bag();
public static String server_name = "CS172";
public int hp, power, defense, mp, level, skill;
private String name;
Random rnd=new Random();
public Character(String name) {
this.name=name;
Random rnd=new Random();
this.hp=rnd.nextInt(500)+1;
this.power=rnd.nextInt(100)+1;
this.defense=rnd.nextInt(100)+1;
this.mp=rnd.nextInt(50)+1;
this.level=1;
this.skill=5;
}
public Character(int hp, int power, String name) {
this.hp=hp;
this.power=power;
this.name=name;
this.defense=rnd.nextInt(100)+1;
this.mp=rnd.nextInt(50)+1;
this.level=1;
this.skill=5;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public int getMp() {
return mp;
}
public void setMp(int mp) {
this.mp = mp;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getName() {
return name;
}
public int damage(int enemy_power) {
int damage = enemy_power - this.defense;
if(damage<0){ //avoid healing by damage
damage=0;
}
this.hp=this.hp - damage;
if(this.hp<0) { //avoid negative hp
this.hp = 0;
}
return damage;
}
public Armor getArmor() {
return armor;
}
public void setArmor(Armor armor) {
this.armor = armor;
}
public Weapon getWeapon() {
return weapon;
}
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
public int hit_point() {
int total_power = this.power + this.weapon.getPower();
return total_power;
}
//------------------------------------------------------why isn't this increasing the hit point at all?
public int useSkill() {
this.mp=this.mp-1;
this.skill--;
return this.hit_point()+30;
}
public int getSkill() {
return skill;
}
public Bag getBag() {
return bag;
}
public void setBag(Bag bag) {
this.bag = bag;
}
public class Bag{
Weapon weaponArray[] = new Weapon[4];
Armor armorArray[] = new Armor[4];
int money = 150;
public Bag(){
for(int i=0; i<weaponArray.length; i++) {
weaponArray[i] = new Weapon();
armorArray[i] = new Armor();
}
}
public Weapon[] getWeaponArray() {
return weaponArray;
}
public void setWeaponArray(int yourWeaponIndex, Weapon enemyWeapon) {
this.weaponArray[yourWeaponIndex] = enemyWeapon;
}
public Armor[] getArmorArray() {
return armorArray;
}
public void setArmorArray(Armor[] armorArray) {
this.armorArray = armorArray;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
}
You are calling an accessor method like it will also set, which it doesn't. Try something like this:
main_ch.getBag().setMoney(main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney());
For some obscene reason this works when reward = "DIAMOND" and amount = 10
public ItemStack giveReward() {
return new ItemStack(Material.matchMaterial(reward), amount);
}
p.getInventory().addItem(o.giveReward()); //gives the player 10 DIAMONDS
but when reward = "ACACIA_DOOR" and amount = 1 the same method gives the player NOTHING and no error is thrown. I have no clue why. Also
System.out.println(Material.getMaterial("ACACIA_DOOR"))
prints ACACIA_DOOR so shouldn't my above code work?
here's the rest of the code:
//imports omitted
public class ObjectivesRPG extends JavaPlugin implements Listener {
//TODO
//add view command
//implement rewards and requirements
//test for completeness
//future - allow ops to modify player data
public static void main(String args[]) {
Objective o = new Objective("Spider", 1, 3, "DIAMOND", 1);
Material m = Material.getMaterial("ACACIA_DOOR");
System.out.println(m);
//meta.setDisplayName(ChatColor.GOLD + "Excaliber");
//meta.setLore(Arrays.asList(ChatColor.AQUA + "The legendary sword", ChatColor.GREEN + "Wow"));
//sword.setItemMeta(meta);
//System.out.println(o.getName());
/*
System.out.println(Material.DIAMOND_SWORD);
ItemStack stack = new ItemStack(Material.DIAMOND_SWORD, 1);
ItemMeta meta = stack.getItemMeta();
stack.setItemMeta(meta);*/
}
private ArrayList<Objective> objectives = null;
private HashMap<String, ArrayList<Objective>> loadedPlayerData = null;
#SuppressWarnings("unchecked")
#Override
public void onEnable() {
System.out.println("ObjectivesRPG loaded");
loadedPlayerData = new HashMap<>();
File dir = getDataFolder();
if (!dir.exists()) {
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[ObjectivesRPG] Could not find data directory, creating it");
if (!dir.mkdir()) {
System.out.println("Error: Could not create data directory");
}
}
objectives = (ArrayList<Objective>) load(new File(getDataFolder(), "objectives.dat"));
if (objectives == null) {
objectives = new ArrayList<>();
}
getServer().getPluginManager().registerEvents(this, this); // ParamListener,
// ParamPlugin
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]) {
if (label.equalsIgnoreCase("objectives")) {
if (sender instanceof Player) {
Player p = (Player) sender;
if(args.length == 0) {
for(Objective o: loadedPlayerData.get(p.getName())) {
p.sendMessage(o.getName() + " " + o.getTillComplete() + " ");
}
}
if (args.length > 0) {
if (args[0].equals("create")) {
if (!p.isOp()) {
p.sendMessage(ChatColor.RED + "You must be op to use this command");
} else if (args.length == 6) {
Objective objective = new Objective(args[1] ,Integer.parseInt(args[2]), Integer.parseInt(args[3]), args[4], Integer.parseInt(args[5]));
objectives.add(objective);
save(objectives, new File(getDataFolder(), "objectives.dat"));
} else {
p.sendMessage(ChatColor.RED + "Error: Bad arguments.");
}
}
}
}
}
return true;
}
public void onDisable() {
save(objectives, new File(getDataFolder(), "objectives.dat"));
}
public void save(Object o, File f) {
try {
if (!f.exists()) {
f.createNewFile();
}
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f));
os.writeObject(o);
Bukkit.getConsoleSender().sendMessage("[ObjectivesRPG] Saved objective");
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Object load(File f) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Object result = ois.readObject();
ois.close();
return result;
} catch (Exception e) {
return null;
}
}
#EventHandler
private void checkKills(EntityDeathEvent e) {
Entity killed = e.getEntity();
Entity killer = e.getEntity().getKiller();
if(killer instanceof Player) {
Player p = (Player) killer;
for(Objective o: loadedPlayerData.get(p.getName())) {
if(o.isComplete()) {
continue;
}
if(!o.isComplete() && (o.getRequirement() == Requirement.kill_Spiders && killed instanceof Spider ||
o.getRequirement() == Requirement.kill_Zombies && killed instanceof Zombie) ||
o.getRequirement() == Requirement.kill_Skeletons && killed instanceof Skeleton
) {
o.setTillComplete(o.getTillComplete() - 1);
if(o.getTillComplete() == 0) {
p.sendMessage(ChatColor.GREEN + "Congragulations! You completed objective " + o.getName() + "! Here is your reward!");
p.getInventory().addItem(o.giveReward());
o.setComplete(true);
}
}
}
}
}
#EventHandler
private void onQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
File f = new File(getDataFolder(), player.getName());
save(loadedPlayerData.get(player.getName()), f);
loadedPlayerData.remove(player.getName());
}
#EventHandler
private void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
File f = new File(getDataFolder(), player.getName());
ArrayList<Objective> playerObjectives = null;
try {
if(!f.exists()) {
f.createNewFile();
Bukkit.getConsoleSender().sendMessage("[ObjectivesRPG] Could not find " + player.getName() + "'s objective data, creating it");
playerObjectives = new ArrayList<>();
for(Objective objective: objectives) {
playerObjectives.add(objective);
}
player.sendMessage(ChatColor.GREEN + "You have new objective(s) to complete! Type /objectives to view them.");
save(playerObjectives, f);
} else {
playerObjectives = (ArrayList<Objective>) load(f);
System.out.println(objectives.size() + " " + playerObjectives.size());
//If server objective list is larger than playerObjectives new objectives must be added to player list
if(objectives.size() > playerObjectives.size()) {
player.sendMessage(ChatColor.GREEN + "You have new objective(s) to complete! Type /objectives to view them.");
for(int i = 0; i < objectives.size(); i++) {
boolean objectiveAdded = false;
for(int j = 0; j < playerObjectives.size(); j++) {
if(objectives.get(i).getName().equals(playerObjectives.get(j).getName())) {
objectiveAdded = true;
//break;
}
}
if(!objectiveAdded) {
playerObjectives.add(objectives.get(i));
}
}
save(playerObjectives, f);
}
}
loadedPlayerData.put(player.getName(), playerObjectives);
} catch(Exception e) {
e.printStackTrace();
}
}
}
public class Objective implements Serializable {
private static final long serialVersionUID = -2018456670240873538L;
private static ArrayList<Requirement> requirements = new ArrayList<>();
private String name;
private Requirement requirement;
private String reward;
private int amount;
private int tillComplete;
private boolean complete;
public Objective(String name, int requirementIndex, int tillComplete, String reward, int amount) {
if(requirements.isEmpty()) {
requirements.add(Requirement.kill_Skeletons);
requirements.add(Requirement.kill_Spiders);
requirements.add(Requirement.kill_Zombies);
}
this.name = name;
this.requirement = requirements.get(requirementIndex);
this.tillComplete = tillComplete;
this.reward = reward;
this.amount = amount;
complete = false;
}
public ItemStack giveReward() {
return new ItemStack(Material.matchMaterial(reward), amount);
}
public String getName() {
return name;
}
public Object getRequirement() {
return requirement;
}
public static ArrayList<Requirement> getRequirements() {
return requirements;
}
public static void setRequirements(ArrayList<Requirement> requirements) {
Objective.requirements = requirements;
}
public int getTillComplete() {
return tillComplete;
}
public void setTillComplete(int tillComplete) {
this.tillComplete = tillComplete;
}
public void setName(String name) {
this.name = name;
}
public void setRequirement(Requirement requirement) {
this.requirement = requirement;
}
public void setReward(String reward) {
this.reward = reward;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
public String getReward() {
return reward;
}
public boolean isComplete() {
return complete;
}
}
This has tripped people up more than once. Doors are two-component items. ACACIA_DOOR represents the top-part of the door, while ACACIA_DOOR_ITEM represents the bottom-part and also the item id. Use ACACIA_DOOR_ITEM when creating an ItemStack.
Tip: If you are unsure about an item id, launch Minecraft in creative mode and enable Advanced Tooltips by pressing F3+H. The real item id will be displayed in the tool tip as you hover over items in the creative inventory. For example, hovering over an Acacia Door would display
Acacia Door (#0430)
Use this information to lookup the appropriate Material enum in org.bukkit.Material, which in this case would be ACACIA_DOOR_ITEM.
I have a problem with my GUI timer. I start my timer when the player clicks on a button in the mine field, and I stop my timer when the game ends.
The first time I test my game, the timer starts and ends normally. However, if I try to play a second round of the game, my timer does not stop.
public class Minesweeper7 extends JFrame implements ActionListener {
static public boolean revealed [][];
public static CountTimer ct;
public Minesweeper7 (int row, int column) {
ct = new CountTimer ();
}
private void setTimerText (String sTime) {
timeLabel.setText (sTime);
}
public void actionPerformed(ActionEvent event){
String coords = event.getActionCommand();
String[] squarePressed = coords.split(",");
x_pressed = Integer.parseInt(squarePressed[0]);
y_pressed = Integer.parseInt(squarePressed[1]);
System.out.println("The button you have pressed is " + x_pressed + ", " + y_pressed);
if (ct.timer.isRunning() == false){
ct.start ();
System.out.println ("timer is running");
}
reveal (row,column,x_pressed,y_pressed,revealed,mines,revealed_number);
gameEnd (row, column, revealed, mines, countMines, counter, end);
System.out.println("There are " + countMines + " .");
System.out.println("");
for (int r = 0;r<row;r++){
for (int c = 0;c<column;c++){
label[r][c].setText(String.valueOf(revealed_number[r][c]));
}
}
}
public void reveal () {
//a recursive method that reveals my buttons
}
public static void main (String args []) {
java.awt.EventQueue.invokeLater (new Runnable () {
public void run () {
new Minesweeper7 (10, 10);
}
});
}
public void gameEnd (int row, int column, boolean revealed [][], boolean mines [][], int countMines, int counter, boolean end) {
for (int r = 0; r < row; r++) {
for (int c = 0; c < column; c++) {
if (mines [r][c] == false && revealed [r][c] == true) {
counter++;
}
else if (mines [r][c] == true && revealed [r][c] == true) {
System.out.println ("Sorry, you lost because you clicked on a mine.");
end = true;
break;
}
}
}
if (counter == (row*column-countMines)) {
System.out.println ("Congratulations! You won the game!");
end = true;
instruction.setText("Congratulations! You won the game!");
}
if (end == true) {
ct.stop ();
}
}
public class CountTimer implements ActionListener {
public static final int ONE_SECOND = 1000;
public int count = 0;
public boolean isTimerActive = false;
public Timer timer = new Timer (ONE_SECOND, this);
public CountTimer () {
count = 0;
setTimerText (TimeFormat (count));
}
public void actionPerformed (ActionEvent e) {
if (isTimerActive) {
count++;
setTimerText (TimeFormat (count));
}
}
public void start () {
count = 0;
isTimerActive = true;
timer.start ();
}
public void stop () {
timer.stop ();
}
public void reset () {
count = 0;
isTimerActive = true;
timer.restart ();
}
}
}
if you start a new game, you could just make a new timer instead of starting and stopping.
if (game end) {
timer = new Timer();
timer.start();
}
To make my code more efficient, I have tried to separate the GUI and Gameplay. The code complies but when I make a new Game(); the Gui displays correctly but when I try to interact with it (i.e. change a name on the board or click a button the methods do not work.
The GUI Class Constructor:
public GUI()
{
makeFrame();
assignmines();
}
note: Assign mines and make frame are the only methods in this class.
The Game Class: (From the constructor)
public Game()
{
new GUI();
//UPDATES THE LABELS
updateGamesPlayed() ;
UpdateName();
}
// *********************************GAME CONTROLS************
private void quit()
{
System.exit(0);
}
//RESETS THE BOARD
public void reset()
{
frame.setVisible(false);
String tempName = Game.this.namelabel.getText();
frame.dispose();
Game gb= new Game();
gb.namelabel.setText(tempName);
score = 0;
}
// iNITIATES NEW GAME
public void newGame(){
frame.setVisible(false);
frame.dispose();
new Game();
}
// INCREASE THE ARRAY OF BUTTONS
public void biggerBoard(){
boardsize = 10;
reset();
}
// INCREASES NUMBER OF MINES ASSIGNED TO THE BOARD
public void changeDifficulty(){
numberOfMines = 15;
mine = 15;
minesLeft = 15;
reset();
}
}
// LOSING THE GAME ALERT
public void lose() {
status.setText("You're finished");
gamegoing = false;
JFrame parent = new JFrame();
JOptionPane.showMessageDialog(parent, "Sorry, you lost");
reset();
}
// WINNING THE GAME ALERT
public void win() {
status.setText("You won!");
gamegoing = false;
JFrame parent = new JFrame();
JOptionPane.showMessageDialog(parent, "Congratualations, you won!");
updateGamesWon();
Game.this.setVisible(false);
Game.this.dispose();
reset();
}
// UPDATING THE SCORE
public void updatescore() {
scorelabel.setText("" + score + " points");
if (100 - score <= 10) win();
}
public void gamesPlayed() {
gamesPlayed.setText("" + noGamesPlayed + " Games Played");
}
//UPDATES THE NAME BASED ON BUTTON CLICK
public void UpdateName() {
saveName.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
playername = nameEnter.getText();
namelabel.setText(playername);
}
});
}
//INCREMENTS THE NUMBER OF GAMES THAT HAVE BEEN PLAYED
public void updateGamesPlayed() {
noGamesPlayed ++;
}
//uPDATES HOW MANY GAMES HAVE BEEN WON
public void updateGamesWon() {
noGamesWon ++;
}
//WHAT VALUES THE CHARACTER HAVE
static char getUserChar(int cellValue) {
if(cellValue == Mine) {
return 'X';
} else if( cellValue == Empty) {
return '+';
} else if (cellValue == Flag || cellValue == FlaggedMine) {
return 'F';
} else if (cellValue == UncoveredMine) {
return 'X';
} else { String adjMines = Integer.toString(cellValue);
return adjMines.charAt(0);
}
}
//METHOD TO DISPLAY HOW MANY MINES AROUND THE BUTTON CLICKED
static int numAdjMines(int[][] mineBoard, int row, int col) {
int numMines = 0;
for(int dr = -1; dr <= 1; dr ++) {
for(int dc = -1; dc <= 1; dc++) {
if(row + dr >= 0 && row + dr < mineBoard.length &&
col+ dc >= 0 && col + dc < mineBoard[0].length) {
if(mineBoard[row+dr][col+dc] == Mine ||
mineBoard[row+dr][col+dc] == FlaggedMine) {
numMines++;
}
}
}
}
return numMines;
}
// TAKES X AND Y VALUE DESCRIBES WHAT HAPPENS ON CLICK
public void click(int row, int col) {
if(mineBoard[row][col] == Mine) {
buttons[row][col].setIcon( new ImageIcon( "images/bomb.gif" ) );
lose();
} else {
score += 1;
updatescore();
buttons[row][col].setText("" + numAdjMines(mineBoard, row, col));
buttons[row][col].setForeground(Color.GREEN);
mineBoard[row][col] = UncoveredEmpty;
//buttons[row][col].setText(Character.toString(getUserChar(mineBoard[row][col])));
if(numAdjMines(mineBoard, row, col) == Empty) {
for(int dr = -1; dr <= 1; dr ++) {
for(int dc = -1; dc <= 1; dc++) {
if(row+dr >= 1 && row+dr < 10 &&
col+dc >= 1 && col+dc < 10) {
if(mineBoard[row+dr][col+dc] == Empty) {
click(row+dr,col+dc);
}
}
}
}
}
}
}
//ACTION WHEN USER CLICKS ON A BUTTON
private class MouseListener extends MouseAdapter {
private int x = 0;
private int y = 0;
public MouseListener(int row, int col) {
this.x = row;
int i = 0;
this.y = col;
}
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
if((mineBoard[x][y] == Empty) && (Game.this.gamegoing == true)) {
Game.this.click(x, y);
} else if(mineBoard[x][y] == Mine) {
buttons[x][y].setIcon( new ImageIcon( "images/bomb.gif" ) );
Game.this.lose();
}} else if(e.getButton() == MouseEvent.BUTTON3) {
Game.this.buttons[x][y].setText("F");
}
}
}
}
How can I link the GUI and the functionality? I think I have got the wrong logic in the constructors but i'm not sure. (I hope all the relevant code is there, I have omitted some fields and methods due to length).