creating a team of players from a list - java

Hey im trying to create a random way to pick a team of 4 from a linkedlist and am wondering if this code will work.
heres an example code
public static void enterGame(Client c) {
int n = teamSize;
boolean startNewGame = false;
if(waitingPlayers.size() <= 3) {
return; // not enough players
}
startNewGame = true;
if(startNewGame) {
System.out.println("Starting new game");
for(int i=0; i<n; i++) {
Collections.shuffle(waitingPlayers);
System.out.println("Picking random player");
waitingPlayers.remove(c);
System.out.println("removing from random player list");
players.add(c);
System.out.println("adding player to ingame list");
}
}
}

I would use Collections.shuffle() and a sublist. In order to know if your code works why don't you test it (unit test or just some try)?
Also, this part:
boolean startNewGame = false;
if(waitingPlayers.size() > 3) {
startNewGame = true;
} else {
startNewGame = false;
return;
}
if(startNewGame) {
is over complicated, I would replace it by:
if(waitingPlayers.size() <= 3) {
return; // not enough players
}
Full code:
public static void enterGame(final Client c) {
if(waitingPlayers.size() <= 3) {
return; // not enough players
}
System.out.println("Starting new game");
Collections.shuffle(waitingPlayers);
System.out.println("Picking random players");
// ? to be replaced by the real type of objects inside waitingPlayers
final List<?> picked = waitingPlayers.subList(0, 3);
players.addAll(picked);
waitingPlayers.removeAll(picked);
}

You have a bug - you are picking a number from 0 to n. If n is selected, you will get an out of bounds exception. Other fhan that it seems fine.

Related

Removing a material from an Itemstack out of players inventory

I am working on a plugin that allows players to fly at the cost of a item.
I have this code that works but only if the item is in the first slot of the players inventory (Hotbar) and no where else.
To enable fly I have a command class that checks the players inventory for redstone and if they have it, They are added to an arrayList based on their UUID. Inside of my onEnable I have a TaskTimer that runs continually and checks for players in the arrayList.
Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
for (Player player : Bukkit.getOnlinePlayers()) {
if (Fly.flyingPlayers.contains(player.getUniqueId())) {
for (int i = 0; i < player.getInventory().getSize(); i++) {
ItemStack item = player.getInventory().getItem(i);
if (item !=null && item.getType().equals(Material.REDSTONE)) {
int amount = item.getAmount() -1;
item.setAmount(amount);
player.getInventory().setItem(i, amount > 0 ? item : null);
player.updateInventory();
break;
} else {
Fly.flyingPlayers.remove(player.getUniqueId());
player.setAllowFlight(false);
player.setFlying(false);
player.sendMessage(chatColor("" + this.getConfig().getString("Prefix") + "&4You are out of fuel"));
break;
}
}
}
}
}, 20L, 20L);
The issue comes from the if. If it's redstone, it will remove the item, else it will instantly think that it's finished instead of going to next slots.
You should do something like that:
Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
for (Player player : Bukkit.getOnlinePlayers()) {
if (Fly.flyingPlayers.contains(player.getUniqueId())) {
boolean hasEdited = false;
for (int i = 0; i < player.getInventory().getSize(); i++) {
ItemStack item = player.getInventory().getItem(i);
if (item != null && item.getType().equals(Material.REDSTONE)) {
int amount = item.getAmount() -1;
item.setAmount(amount);
player.getInventory().setItem(i, amount > 0 ? item : null);
player.updateInventory();
hasEdited = true; // save that it have been edited
break; // break the for loop
}
}
if(hasEdited) // edited in for loop
continue; // go to next player
Fly.flyingPlayers.remove(player.getUniqueId());
player.setAllowFlight(false);
player.setFlying(false);
player.sendMessage(chatColor(this.getConfig().getString("Prefix") + "&4You are out of fuel"));
}
}
}, 20L, 20L);

Break while loop only when all conditions in for loop are met

I would like to break a while loop only when all of the "bots" are upright. (*These bots being referred to are mini USB robots).
.upRight() returns true when a bot is standing and false when not.
public static boolean checkSomething() throws ... {
while (true) {
for (i = 0; i < bots; i++) { // bots = 2
if (!theMainBots[i].isUpright()) {
...
Thread.sleep(1000);
}
else {
return true;
}
}
}
The issue I'm facing, is that if the isUpright() method returns true for the first "bot", then all other bots are left unchecked and may return false. The intention is to wait for the user to place the bot in an upright position before proceeding.
You should check all the bots first, then act on the result. Don't try to act on the result inside the check loop.
Also, since the code doesn't return until all bots are upright, the method is misnamed and shouldn't return a value.
public static void waitUntilAllUpright() throws InterruptedException {
for (;;) { // forever loop
boolean allUpright = true;
for (i = 0; i < bots; i++) {
if (! theBots[i].isUpright()) {
allUpright = false;
break;
}
}
if (allUpright)
return;
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
} // loop back to check all bots again
}
If you want to wait until the user makes the bot upright you could change the if to a while:
while (true) {
for (i = 0; i < bots; i++) { // bots = 2
while(!theBots[i].isUpright()) {
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
}
}
return true;
}
This will loop through each element in the Array and while any given bot is not upright, it will loop and sleep until the bot is turned upright. In which case, you do not need to while(true) loop:
public static boolean checkUpright() throws InterruptedException {
for (i = 0; i < bots; i++) { // bots = 2
while(!theBots[i].isUpright()) {
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
}
}
return true;
}
One way to achieve this, is using a variable that will determine when to leave the loop. Your problem here, is that you also need to change your for loop for a while loop. Why is that? Because you don't know if the bot you just checked was moved or not. Also, the outer loop is unnecessarily, unless you wanted to recheck again. So the code would end looking something like this.
public static boolean checkUpright() throws InterruptedException {
int counter = 0;
while (counter <= theBots.length) { // bots = 2
if (!theBots[i].isUpright()) {
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
} else {
counter ++;
}
}
}
The context is not completely clear, but mixing logical control with user interaction might be the problem. Perhaps this approach might work:
public static boolean checkUpright() throws InterruptedException {
while (!areAllBotsUpright()) {
System.out.println("Please ensure I'm upright");
Thread.sleep(500);
}
}
public static boolean areAllBotsUpright() {
for (i = 0; i < bots; i++) {
if (!theBots[i].isUpright()) {
return false;
}
}
return true;
}
you can create a list from array of bots , iterate over this list using iterator
if a particular bot is upright , remove it from this list using iterator.remove.
outer while will run until list is not empty.
public static boolean checkUpright() {
ArrayList<Bot> notUprightBots= (ArrayList<Bot>) Arrays.asList(theBots);
while (!notUprightBots.isEmpty()) {
Iterator<Bot> iterator=notUprightBots.iterator();
while(iterator.hasNext()){
Bot bot=iterator.next();
if (!bot.isUpright()) {
System.out.println("Please ensure I'm upright");
try{
Thread.sleep(500);
}catch(InterruptedException e){
}
}else {
iterator.remove();
}
}
}
return true;
}

match and delete elements in arraylists

I am making a robot maze where the robot reaches a target automatically without crashing into walls. I want the robot to do the maze once, learn the correct route and then the second time be able to get there straight away without going to any deadends. I thought I could do this by making three arraylists.
One for all the squares the robot visits.
Two for all the squares that lead to a deadend.
Three for all the directions the robot goes.
If the squares that lead to a dead end are found in the first arraylist then i can delete the same indexes in the third arraylist. That way, the second time, i can just iterate the third Arraylist.
My full code is below:
import java.util.ArrayList;
import java.util.*;
import java.util.Iterator;
import java.util.stream.IntStream;
public class Explorer {
private int pollRun = 0; // Incremented after each pass.
private RobotData robotData; // Data store for junctions.
private ArrayList<Integer> nonWallDirections;
private ArrayList<Integer> passageDirections;
private ArrayList<Integer> beenbeforeDirections;
private Random random = new Random();
int [] directions = {IRobot.AHEAD, IRobot.LEFT, IRobot.RIGHT, IRobot.BEHIND};
private ArrayList<Square> correctSquares;
private ArrayList<Square> wrongSquares;
private ArrayList<Integer> correctDirections;
public void controlRobot (IRobot robot) {
// On the first move of the first run of a new maze.
if ((robot.getRuns() == 0) && (pollRun ==0))
robotData = new RobotData();
pollRun++; /* Increment poll run so that the data is not reset
each time the robot moves. */
int exits = nonwallExits(robot);
int direction;
if ((robot.getRuns() != 0))
direction = grandfinale(robot);
nonWallDirections = new ArrayList<Integer>();
passageDirections = new ArrayList<Integer>();
beenbeforeDirections = new ArrayList<Integer>();
correctSquares = new ArrayList<Square>();
correctDirections = new ArrayList<Integer>();
// Adding each direction to the appropriate state ArrayList.
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonWallDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.BEENBEFORE) {
beenbeforeDirections.add(item);
}
}
// Calling the appropriate method depending on the number of exits.
if (exits < 2) {
direction = deadEnd(robot);
} else if (exits == 2) {
direction = corridor(robot);
} else {
direction = junction(robot);
robotData.addJunction(robot);
robotData.printJunction(robot);
}
robot.face(direction);
addcorrectSquares(robot);
correctDirections.add(direction);
}
/* The specification advised to have to seperate controls: Explorer and Backtrack
and a variable explorerMode to switch between them.
Instead, whenever needed I shall call this backtrack method.
If at a junction, the robot will head back the junction as to when it first approached it.
When at a deadend or corridor, it will follow the beenbefore squares until it
reaches an unexplored path. */
public int backtrack (IRobot robot) {
if (nonwallExits(robot) > 2) {
addwrongSquares(robot);
return robotData.reverseHeading(robot);
} else {
do {
addwrongSquares(robot);
return nonWallDirections.get(0);
} while (nonwallExits(robot) == 1);
}
}
// Deadend method makes the robot follow the only nonwall exit.
public int deadEnd (IRobot robot) {
return backtrack(robot);
}
/* Corridor method will make the robot follow the one and only passage.
The exception is at the start. Sometimes, the robot will start with
two passages available to it in which case it will choose one randomly.
If there is no passage, it will follow the beenbefore squares
until it reaches an unexplored path.*/
public int corridor (IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) == 2) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
/* Junction method states if there is more than one passage, it will randomly select one.
This applies to crossroads as well as essentially they are the same.
If there is no passage, it will follow the beenbefore squares until it reaches an unexplored
path. */
public int junction(IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) > 1) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
// Calculates number of exits.
private int nonwallExits (IRobot robot) {
int nonwallExits = 0;
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonwallExits++;
}
}
return nonwallExits;
}
// Calculates number of passages.
private int passageExits (IRobot robot) {
int passageExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageExits++;
}
}
return passageExits;
}
// Calculates number of beenbefores.
private int beenbeforeExits (IRobot robot) {
int beenbeforeExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
beenbeforeExits++;
}
}
return beenbeforeExits;
}
// Resets Junction Counter in RobotData class.
public int reset() {
return robotData.resetJunctionCounter();
}
public void addcorrectSquares(IRobot robot) {
Square newSquare = new Square(robot.getLocation().x, robot.getLocation().y);
correctSquares.add(newSquare);
}
public void addwrongSquares(IRobot robot) {
Square badSquare = new Square(robot.getLocation().x, robot.getLocation().y);
wrongSquares.add(badSquare);
}
public int grandfinale (IRobot robot) {
IntStream.range(0, correctSquares.size())
.map(index -> correctSquares.size() - index - 1)
.filter(index -> (((wrongSquares.x).contains(correctSquares.x)) && ((wrongSquares.y).contains(correctSquares.y))).get(index))
.forEach(index -> correctDirections.remove(index));
Iterator<Integer> routeIterator = correctDirections.iterator();
while (routeIterator.hasNext()) {
break;
}
return (routeIterator.next());
}
}
class RobotData {
/* It was advised in the specification to include the variable:
private static int maxJunctions = 10000;
However, as I am not using arrays, but ArrayLists, I do not
need this. */
private static int junctionCounter = 0;
private ArrayList<Junction> junctionList = new ArrayList<Junction>();
// Resets the Junction counter.
public int resetJunctionCounter() {
return junctionCounter = 0;
}
// Adds the current junction to the list of arrays.
public void addJunction(IRobot robot) {
Junction newJunction = new Junction(robot.getLocation().x, robot.getLocation().y, robot.getHeading());
junctionList.add(newJunction);
junctionCounter++;
}
// Gets the junction counter for Junction info method in Junction class.
public int getJunctionCounter (IRobot robot) {
return junctionCounter;
}
// Prints Junction info.
public void printJunction(IRobot robot) {
String course = "";
switch (robot.getHeading()) {
case IRobot.NORTH:
course = "NORTH";
break;
case IRobot.EAST:
course = "EAST";
break;
case IRobot.SOUTH:
course = "SOUTH";
break;
case IRobot.WEST:
course = "WEST";
break;
}
System.out.println("Junction " + junctionCounter + " (x=" + robot.getLocation().x + ", y=" + robot.getLocation().y +") heading " + course);
}
/* Iterates through the junction arrayList to find the
heading of the robot when it first approached the junction.
It does this by finding the first junction in the ArrayList
that has the same x and y coordinates as the robot.*/
public int searchJunction(IRobot robot) {
Junction currentJunction = null;
Iterator<Junction> junctionIterator = junctionList.iterator();
while (junctionIterator.hasNext()) {
currentJunction = junctionIterator.next();
if ((((currentJunction.x)==(robot.getLocation().x))) && ((currentJunction.y)==(robot.getLocation().y)))
break;
}
return currentJunction.arrived;
}
// Returns the reverse of the heading the robot had when first approaching the junction.
public int reverseHeading(IRobot robot) {
int firstHeading = searchJunction(robot);
int reverseHeading = 1; // Random integer to Iniitalise variable.
switch (firstHeading) {
case IRobot.NORTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.AHEAD;
else
reverseHeading = IRobot.LEFT;
break;
case IRobot.EAST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.RIGHT;
else
reverseHeading = IRobot.AHEAD;
break;
case IRobot.SOUTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.BEHIND;
else
reverseHeading = IRobot.RIGHT;
break;
case IRobot.WEST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.LEFT;
else
reverseHeading = IRobot.BEHIND;
break;
}
return reverseHeading;
}
}
class Junction {
int x;
int y;
int arrived;
public Junction(int xcoord, int ycoord, int course) {
x = xcoord;
y = ycoord;
arrived = course;
}
}
class Square {
int x;
int y;
public Square(int cordx, int cordy){
x = cordx;
y = cordy;
}
}
IntStream.range(0, al1.length)
.filter(index -> al2.contains(al1.get(index)))
.forEach(index -> al3.remove(index));
Slightly more complex than this if removing elements from al3 shifts them left but in that case just reverse the stream before the .filter- then it will delete from the end. The easiest way to do that is:
.map(index -> al1.length - index - 1)
Without Streams the equivalent would be
for (int i = 0; i < al1.length; i++) {
if (al2.contains(al1.get(i))) {
al3.remove(i);
}
}
Similarly, if you need to delete from the right then the for loop would need to count down rather than up.
Without further details on arraylist structure it's hard to give any more hints.

Collision detection inside the same ArrayList

After searching around over the course of a few days, I have not found a solution. I have an ArrayList of collision elements that I want to iterate over and calculate collisions for. I have made several similar attempts, but I am currently stumped.
Collision method (called once a game-tick)
public void iterateCollision()
{
if(iterateBoxes)
{
if(iterateBoxes)
{
for(int i=0;i<boxPool.size();i++)
{
for(int j=i+1;j<boxPool.size();j++)
{
if(!(boxPool.get(i).equals(boxPool.get(j))) && checkCollision(boxPool.get(i), boxPool.get(j)))
{
boxPool.get(i).colliding = true;
boxPool.get(j).colliding = true;
}
}
}
}
}
}
Here is the collision detection method for those of you who would like to review it:
public boolean checkCollision(BaseAABB box1, BaseAABB box2)
{
//This is just to get the center vector of the bounding boxes.
Vector2f c1 = getAABBCenter(box1);
Vector2f c2 = getAABBCenter(box2);
if(Math.abs(c1.x - c2.x) > (box1.width + box2.width)) return false;
if(Math.abs(c1.y - c2.y) > (box1.height + box2.height)) return false;
return true;
}
You forgot to add a condition that i != j
I suspect that you should replace the following condition:
boxPool.get(i) != boxPool.get(j)
with:
!boxPool.get(i).equals(boxPool.get(j))
Further, there's no need to double loop over all the elements, you can always start with j = i + 1 and then you don't have to check that i != j:
for(int i=0;i<boxPool.size();i++)
{
// V
for(int j=i+1;j<boxPool.size();j++) // <-- this line has changed!
{
if(boxPool.get(i) != boxPool.get(j) && checkCollision(boxPool.get(i), boxPool.get(j)))
{
boxPool.get(i).colliding = true;
boxPool.get(j).colliding = true;
}
}
}

How do I check if a class' return of a method equals null?

In my program, I have a while loop that will display a list of shops and asks for an input, which corresponds with the shop ID. If the user enters an integer outside the array of shops, created with a Shop class, it will exit the loop and continue. Inside this loop is another while loop which calls the sellItem method of my Shop class below:
public Item sellItem()
{
displayItems();
int indexID = Shop.getInput();
if (indexID <= -1 || indexID >= wares.length)
{
System.out.println("Null"); // Testing purposes
return null;
}
else
{
return wares[indexID];
}
}
private void displayItems()
{
System.out.println("Name\t\t\t\tWeight\t\t\t\tPrice");
System.out.println("0. Return to Shops");
for(int i = 0; i < wares.length; i++)
{
System.out.print(i + 1 + ". ");
System.out.println(wares[i].getName() + "\t\t\t\t" + wares[i].getWeight() + "\t\t\t\t" + wares[i].getPrice());
}
}
private static int getInput()
{
Scanner scanInput = new Scanner(System.in);
int itemID = scanInput.nextInt();
int indexID = itemID - 1;
return indexID;
}
The while loop in my main class method is as follows:
boolean exitAllShops = true;
while(exitAllShops)
{
System.out.println("Where would you like to go?\nEnter the number which corresponds with the shop.\n1. Pete's Produce\n2. Moore's Meats\n3. Howards Hunting\n4. Foster's Farming\n5. Leighton's Liquor\n6. Carter's Clothing\n7. Hill's Household Products\n8. Lewis' Livery, Animals, and Wagon supplies\n9. Dr. Miller's Medicine\n10. Leave Shops (YOU WILL NOT BE ABLE TO RETURN)");
int shopInput = scan.nextInt();
if(shopInput >= 1 && shopInput <= allShops.length)
{
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
}
else
{
System.out.println("Are you sure you want to leave?\n1. Yes\n2. No");
int confirm = scan.nextInt();
if(confirm == 1)
{
exitAllShops = false;
}
}
The problem is here:
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
No matter what I do, I can't get "still null" to print to confirm that I'm correctly calling the return statement of the method sellItem of the class Shop. What am I doing wrong?
After calling allShops[...].sellItem(), allShops is still a valid array reference -- there's no way it could be null! You probably want to test the return value from sellItem:
if(allShops[shopInput-1].sellItem() == null)

Categories