4

After transferring from C to Java I have learned that Java contains many functions that can do the job for you, so to speak, unlike in C where you must do things manually.

I am currently designing an OOP board game, in which multiple players are allowed to pick a playing piece, that represents them throughout the game. I have stored the playing pieces in an array, and then asked the number of players to pick a playing piece. However, they are not allowed to pick the same playing piece as the player before them, for obvious reasons. Therefore, my question is there a function that allows me to remove one of the picked playing pieces from the array or must I do this manually, so to speak. My code is below, if needed:

String[] potential_player_pieces = new String[10]; // Array storing the playing pieces available
potential_player_pieces[0]= "*";
potential_player_pieces[1]= "|";
potential_player_pieces[2]= "?";
potential_player_pieces[3]= "@";
potential_player_pieces[4]= "&";
potential_player_pieces[5]= "¬";
potential_player_pieces[6]= "!";
potential_player_pieces[7]= "%";
potential_player_pieces[8]= "<\n";

String[] player_pieces = new String[players+1]; // String to store the playing pieces that the players have chosen

for (int i=1; i<=players; i++) // Loops to the number of players and asks them what playing piece they want
{
    System.out.print("Player " + i + " pick a playing piece:"); // Asks the players the question
    for (int j=0; j<=8; j++){
        System.out.print(potential_player_pieces[j]); // Displays the possible playing pieces  
    }
    player_pieces[i] = reader.nextLine();//Saves the player chioces to the array made above
}
5
  • 1
    Use a Set, not an array. docs.oracle.com/javase/tutorial/collections Commented Apr 7, 2018 at 9:55
  • No, I'm afraid there isn't for Arrays however there is for an ArrayList or List object. You could manually delete the play piece from the array and by creating a second array then copying the second array into the original array to act as though it were deleted. If you don't want to use an ArrayList then perhaps keeping track of what pieces were selected by placing those pieces into another array, and then don't let it be selected if it's in that 'piece selected' array. Commented Apr 7, 2018 at 9:59
  • @JBNizet I disagree. The OP seems to want to print each array element to show all the possible options. As a set is unordered, the order of the available pieces might be different for each player. As a user, I would not expect such behaviour. Commented Apr 7, 2018 at 10:00
  • @Sweeper not all sets are unordered. But yes, a List would be fine here as well. The point is: learn collections, don't use arrays. Commented Apr 7, 2018 at 10:02
  • Can I chime in? Why not create an playerPiece object that has bool var "isChosenAlready" and a var pieceType which is an enum of the different types. and a method "choosePiece(int player)" ... ? Commented Apr 7, 2018 at 10:02

4 Answers 4

2

I would introduce a new List<String> of available options for a current player:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

...

List<String> availableOptions = new ArrayList<>(
    Arrays.asList(potential_player_pieces)
);

and remove the chosen element after the pick is done:

for (int i = 0; i < players; ++i) {
    System.out.println("Player " + i + " pick a playing piece: " + availableOptions);
    availableOptions.remove(player_pieces[i] = reader.nextLine());
}

You also might have shortened initialisation of the array to:

String[] potentialPlayerPieces = new String[] {"*", "|", ..., "<"};

Note that I have renamed the variable to look more Javaish.

Sign up to request clarification or add additional context in comments.

9 Comments

The IDE throws out this error on line 1 with List<String>..., but everything else is fine: incompatible types: cannot infer type arguments for ArrayList<> reason: inference variable E has incompatible bounds equality constraints: String lower bounds: T,ArrayList<String> where E,T are type-variables: E extends Object declared in class ArrayList T extends Object declared in method <T>asList(T...) The type of <E>ArrayList(Collection<? extends E>) is erroneous where E is a type-variable: E extends Object declared in class ArrayList ---- @Andrew
There is no check here if the player has chosen a correct piece.
How do you mean?
@BarryBBenson, shouldn't be any issues, I ran it on my machine
@ReazMurshed, OP didn't check it either, but we can wrap player_pieces[i] = reader.nextLine() with a method which checks it
|
1

I would like to suggest a HashMap in your case. I think this data structure is effective and serves your purpose.

Map<String, Integer> pieceMap = new HashMap<String, Integer>();
// HashMaps stores the value as a key value format. 
// Here the keys are the piece options 
// And the 0 is indicating that, primarily the piece is not used. 
pieceMap.put("*", 0);
pieceMap.put("|", 0);
pieceMap.put("?", 0);
pieceMap.put("@", 0);
pieceMap.put("&", 0);
pieceMap.put("¬", 0);
pieceMap.put("!", 0);
pieceMap.put("%", 0);
pieceMap.put("<\n", 0);

String[] player_pieces = new String[players + 1]; 
for (int i = 0; i < players; i++) {
    System.out.print("Player " + i + " pick a playing piece:"); // Asks the players the question

    printAvailablePieces(pieceMap);

    String piecePlayed = reader.nextLine();

    if(pieceMap.containsKey(piecePlayed) && pieceMap.get(piecePlayed).equals(0)) {
        // The piece has not used yet. 
        pieceMap.put(piecePlayed, 1);
        player_pieces[i] = piecePlayed;
    } else {
        // The piece was played before
        System.out.println("Please play a different piece");
        i--; // Take the user input again. 
    }
}

public void printAvailablePieces(HashMap<String, Integer> pieceMap) {
    for (Map.Entry<String, Integer> entry : pieceMap.entrySet()) 
        if(entry.getValue().equals(0)) System.out.print(entry.getKey() + " ");
}

Hope that helps.

2 Comments

a Map<String, Boolean> can suit better, can't it?
Yes, that will do too. Thanks for the valued suggestion.
0

I would suggest using a HashSet instead of an array to store all the board pieces. Once a player chooses a piece it could be easily removed from the set by calling remove. Also you could validate the choice by calling the contains method on the set.

Comments

0

Use List and HashMap

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Temp {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List<String> potential_player_pieces = new ArrayList<String>();//Array storing the playing pieces available
             potential_player_pieces.add("*");
             potential_player_pieces.add("|");
             potential_player_pieces.add( "?");
             potential_player_pieces.add( "@");
             potential_player_pieces.add( "&");
             potential_player_pieces.add( "¬");
             potential_player_pieces.add( "!");
             potential_player_pieces.add( "%");
             potential_player_pieces.add( "<\n");
             Collections.sort(potential_player_pieces);

             System.out.println(potential_player_pieces);

             int length=potential_player_pieces.size();
             Scanner reader= new Scanner(System.in);

           Map<Integer,String> player_pieces = new HashMap<Integer,String>();//String to store the playing pieces that the players have chosen
                 for (int i=1; i<=length; i++)//Loops to the number of players and  asks them what playing piece they want
                 {
                     System.out.print("Player " + i + " pick a playing piece: ");//Asks the players the question


                     for (int j=0; j<potential_player_pieces.size(); j++){

                            if(j==0) 
                            {
                                System.out.print(potential_player_pieces.get(0)+"\n");
                                player_pieces.put(i, potential_player_pieces.get(0));
                                potential_player_pieces.remove(0);

                            }
                            if(potential_player_pieces.size()>0)
                         System.out.println(potential_player_pieces.get(j)); //Displays the possible playing pieces


                     }

                      //Saves the player chioces to the array made above

                 }

                 System.out.println(player_pieces);

    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.