Dealing with a specific rule of a card game - java

I am working on a card game and I'm facing a problem regarding the gameplay. So basically the rules of the game are that who finishes the hand first gets placed first, second second and so on. I am keeping a list of the players in a List<Player, and if one finishes I just skip the turn from him (checks if >= 1 cards in hand), until 1 player is left. Now, the rule is that if one finishes with an unbeatable card/move or everyone else passes for example, the turn should be to the next player and he is free to make a move. I've been struggling and haven't found a proper solution yet. How to achieve this?
I am currently saving the waste (last played list of cards) cards into a List<Card>, and I am keeping a Player instance lastPlayed for the last playing player, and a Player instance hasTurn for the current player on turn.
The turns are shifted in this method inside the Game class:
public void determineNextPlayerTurn()
{
if(playersLeft() > 1)
{
int i = players.indexOf(hasTurn) + 1;
if(i == 4)
i = 0;
hasTurn = players.get(i);
if(hasTurn.isPlaying())
{
if(!isHumanTurn())
{
display.disableButtons();
AI temp = (AI)players.get(i);
temp.onPlayerTurn(this);
}
else
display.enableButtons();
}
else
{
determineNextPlayerTurn();
}
}
else
newGame(0);
The method of AI that is called when it is an ai's turn:
public void onPlayerTurn(Game game)
{
selectCardsToPlay(game.getWaste(), game.getLastPlayedPlayer());
if(getSelectedCards().isEmpty())
{
game.determineNextPlayerTurn();
}
else
{
if(Moves.canBePlayed(getSelectedCards(), game.getWaste(), this, game.getLastPlayedPlayer()))
{
playMove(game);
game.determineNextPlayerTurn();
}
else
game.determineNextPlayerTurn();
}
}
While for the user, nothing is called as the determineNextPlayerTurn() is called within the ActionListener of the playing buttons (Play, Pass).
Note: Currently like this, if the scenario occurs with the human last playing there will be a stackoverflow for the reason that every ai is doing a Pass. Every other code is fine for now, but I need help with implementing a simple solution to that specific case, and if I am doing something wrong I am open.

Why don't you have a counter for the number of "passes" that are executed and then compare that to the number of players. If the passes are equal to the number of players - 1 then that would mean that following player should be free to make a move. Also what is an "unbeatable move" if there is such a thing then wouldn't you be able to classify the turn as that and then attach a boolean that checks the player for whether or not they have made one of these types of moves?

Related

Minmax algorithm doesn't return direct child of root (returns illegal move)

I am trying to create "AI" for Nine Men's Morris but I got hardstuck on minMax algorithm. Summing up, I was trying to find the issue for over 10h but didn't manage to. (debugging this recursion is nasty or I am doing it badly or both)
Since I started doubting everything I wrote I decided to post my issue so someone can find anything wrong in my version of minMax. I realise it is really hard task without the whole application so any suggestions where I should triple check my code are also very welcome.
Here is link to the video, explaining minMax, on which I based my implementation: https://www.youtube.com/watch?v=l-hh51ncgDI (First video that pops up on yt after searching for minmax - just in case you want to watch the video and don't want to click the link)
My minMax without alpha-beta pruning:
//turn - tells which player is going to move
//gameStage - what action can be done in this move, where possible actions are: put pawn, move pawn, take opponent's pawn
//depth - tells how far down the game tree should minMax go
//spots - game board
private int minMax(int depth, Turn turn, GameStage gameStage, Spot[] spots){
if(depth==0){
return evaluateBoard(spots);
}
//in my scenario I am playing as WHITE and "AI" is playing as BLACK
//since heuristic (evaluateBoard) returns number equal to black pawns - white pawns
//I have decided that in my minMax algorithm every white turn will try to minimize and black turn will try to maximize
//I dont know if this is correct approach but It seems logical to me so let me know if this is wrong
boolean isMaximizing = turn.equals(Turn.BLACK);
//get all possible (legal) actions based on circumstances
ArrayList<Action> children = gameManager.getAllPossibleActions(spots,turn,gameStage);
//this object will hold information about game circumstances after applying child move
//and this information will be passed in recursive call
ActionResult result;
//placeholder for value returned by minMax()
int eval;
//scenario for maximizing player
if(isMaximizing){
int maxEval = NEGATIVE_INF;
for (Action child : children){
//aplying possible action (child) and passing its result to recursive call
result = gameManager.applyMove(child,turn,spots);
//evaluate child move
eval = minMax(depth-1,result.getTurn(),result.getGameStage(),result.getSpots());
//resets board (which is array of Spots) so that board is not changed after minMax algorithm
//because I am working on the original board to avoid time consuming copies
gameManager.unapplyMove(child,turn,spots,result);
if(maxEval<eval){
maxEval = eval;
//assign child with the biggest value to global static reference
Instances.theBestAction = child;
}
}
return maxEval;
}
//scenario for minimizing player - the same logic as for maximizing player but for minimizing
else{
int minEval = POSITIVE_INF;
for (Action child : children){
result = engine.getGameManager().applyMove(child,turn,spots);
eval = minMax(depth-1,result.getTurn(),result.getGameStage(),result.getSpots());
engine.getGameManager().unapplyMove(child,turn,spots,result);
if(minEval>eval){
minEval=eval;
Instances.theBestAction = child;
}
}
return minEval;
}
}
Simple heuristic for evaluation:
//calculates the difference between black pawns on board
//and white pawns on board
public int evaluateBoard(Spot[] spots) {
int value = 0;
for (Spot spot : spots) {
if (spot.getTurn().equals(Turn.BLACK)) {
value++;
}else if(spot.getTurn().equals(Turn.WHITE)){
value--;
}
}
return value;
}
My issue:
//the same parameters as in minMax() function
public void checkMove(GameStage gameStage, Turn turn, Spot[] spots) {
//one of these must be returned by minMax() function
//because these are the only legal actions that can be done in this turn
ArrayList<Action> possibleActions = gameManager.getAllPossibleActions(spots,turn,gameStage);
//I ignore int returned by minMax() because,
//after execution of this function, action choosed by minMax() is assigned
//to global static reference
minMax(1,turn,gameStage,spots);
//getting action choosed by minMax() from global
//static reference
Action aiAction = Instances.theBestAction;
//flag to check if aiAction is in possibleActions
boolean wasFound = false;
//find the same action returned by minMax() in possibleActions
//change the flag upon finding one
for(Action possibleAction : possibleActions){
if(possibleAction.getStartSpotId() == aiAction.getStartSpotId() &&
possibleAction.getEndSpotId() == aiAction.getEndSpotId() &&
possibleAction.getActionType().equals(aiAction.getActionType())){
wasFound = true;
break;
}
}
//when depth is equal to 1 it always is true
//because there is no other choice, but
//when depth>1 it really soon is false
//so direct child of root is not chosen
System.out.println("wasFound?: "+wasFound);
}
Is the idea behind my implementation of minMax algorithm correct?
I think the error might exist in that you are updating Instances.theBestAction even while evaluating child moves.
For example, lets say 'Move 4' is the true best move that will eventually be returned, but while evaluating 'Move 5', theBestAction is set to the best child action of 'Move 5'. From this point on, you won't update the original theBestAction back to 'Move 4'.
Perhaps just a simple condition that only sets theBestAction when depth == originalDepth?
Rather than using a global, you could also consider returning a struct/object that contains both the best score AND the move that earned the score.

Counter only adds once

I have a simple hangman game that has a Jlabel that is supposed to show how many times the word was guessed right. It uses a simple counter wins++ and will show up properly after the first win but any after won't work. The counter won't add more so do I need to use a loop in some way?
if (word.equals(dashes.toString()))
{
wordOutput.setText("You Win!");
wins++; //add 1 to win counter
winsOutput.setText("Wins: " + wins);
}
Seems like this should be simple but I don't know what's wrong
I think you made the win variable as a local, which will get its initial stage after every execution, make the win variable outside of the method and you can also make it static.
public class Hangman {
// here is the variable..
private int wins = 0;
// Here are your other methods..
public void processGame(){
}
}
By the way, it will also works fine without static if your game does not have more than one classes etc. Give it a try with static and without it, but the main point is initializing it outside of the class.

Check winner from arraylist of players in card game

My card game needs a method to check the winner. Without the draw if statement, it works to check that a winning value. However I feel that without a draw check the rest of the project is redundant. How can I do this properly?
public String winChecker(){
Player winningPlayer = players.get(0);
for (Player player : players) {
if (player.getOverallHandValue() > winningPlayer.getOverallHandValue()){
winningPlayer = player;
}
if (player.getOverallHandValue() == winningPlayer.getOverallHandValue()){
return "draw!";
}
return winningPlayer.getName();
}
}
//...
public String winChecker(){
boolean many = false;
boolean initial = true;
Player winningPlayer = players.get(0);
for (Player player : players) {
if (player.getOverallHandValue() > winningPlayer.getOverallHandValue()){
winningPlayer = player;
many = false;
}
if (player.getOverallHandValue() == winningPlayer.getOverallHandValue()){
if (initial){
initial = false;
} else {
many = true;
}
}
}
if (many) {
return "draw";
}
return winningPlayer.getName();
}
is what you're looking for. In the current code there was a bug which was that in case the results were:
1 1 2 3 4 5
current code returned "draw" which is obviously wrong. Look, when you're trying to decide which of the players won, you can't decide who is the winner before reading scores of all players.
Let's describe both algorithms in English.
Set 0th element of players list as current winner.
loop through all players
if current player has a better score then currently winning, set the current player to currently winning.
if they have the same score, decide that the game is drawn. Look, that on the first iteration it's always true!
and the second algorithm
Set 0th element of players list as current winner.
loop through all players
if current player has a better score then currently winning, set the current player to currently winning and mark that there is a single leader at the moment.
if they have the same score, mark that there are at least two players on lead so there is possibility of a draw.
As this code stands you will always get "draw" returned.
If the players collection is like this
["Player A", "Player B", "Player C"]
Then this line of code
Player winningPlayer = players.get(0);
will get you Player A.
The problem is, when you iterate over players, the first iteration will get you Player A as well.
Therefore
if (player.getOverallHandValue() == winningPlayer.getOverallHandValue())
condition will always be true in the first iteration itself.
I think figuring out a way to fix this is best left to your own devices.

Java Method not working constantly

I have a text based game that I am making. It is a RPG style where the user is given options linked to numbers and they have to choose a number. Now my problem is that when running the program. A certain method, Decision(), only works certain times. The method is in a superClass while it is being called in the subclass. in the subclass, It works the first time, but not necessarily the second. Also, when I copy the decision method from the superclass into the subclass its starts working, but the next time it is called, it stops. Here is what I've tried and the results. I've included the decision method and where it is being called.
Decision Method:
public int decision(String question, int length, String[] choices){
int[] numbers = new int[length];
int iterator = 1;
for(int i = 0; i < length; i++){
numbers[i] = iterator;
iterator++;
}
boolean done = false;
while(!done){
//print("Test");
print("");
print(question);
String options = "";
for(int i = 0; i < numbers.length; i++){
options = (options + numbers[i] + " - " + choices[i] + " ");
}
print(options);
boolean univSet = true;
int entry = 1;
while(univSet){
if(univInt != 0){
univSet = false;
entry = univInt;
univInt = 0;
//print("testing");
}
}
if(entry == 23){
help();
}else{
for(int i = 0; i < numbers.length; i++){
if(entry == numbers[i]){
done = true;
univInt = 0;
return entry;
}
}
print("Invalid Number, Try again");
print("");
univInt = 0;
}
}
return (Integer) null;
}
Chapter1 Class (Where it's being called:
public class Chapter1 extends Story implements Serializable {
Player player;
public Chapter1(Player player){
this.player = player;
}
public void engage() {
// TODO Auto-generated method stub
player.chapter = 1;
save(player.name);
sPrint("Welcome to Chapter 1");
print("You wake up in a lighted room with white walls.\nA fresh breeze is coming through the window yet the air smells rotten.");
print("You jolt up suddenly. You don't remember anything about how you got here. You've even forgotten who you are.");
print("You look down at your white shirt, there is a streak of blood across the top.\nYou are wearing a nametag that says: " + player.name + ".");
print("You're sitting in a chair but there are no restraints. You decide to get up and look around");
cur = decision("What do you do?", 2, new String[]{"Try the door", "Look out the window"});
print(cur + "");
if(cur == 1){
print("You walk over to the door and try and open it, it is unlocked.\nYou walk through and are welcomed by a cold and poorly lit hallway");
}else{
print("You walk to the window and look outside. You see a huge barren field. You can make out a humanoid like structure.\nYou call out yet the figure doesn't move.");
print("You decide to try the door. It's unlocked so you walk through into a cold dimly lit hallway.");
}
print("You see a dull knife on the floor as well as a door on the end of the hallway");
cur = decision("What do you do?", 2, new String[]{"Go to the door", "Take the knife"});
if(cur == 2){
print("You pick up the knife.");
addWeapon("Kitchen Knife", player);
}else{
print("You walk down the hallway to the door when suddenly the door opens and out comes a zombie.\nIt Lunges for your shoulder. You are caught by surprise and it bites into your skin and you are infected");
gameOver();
}
print("You continue to walk down the hall when suddenly a hideous creature lunges out from the door.\nYou jump back and prepare yourself for a battle.");
battle("Zombie", 5, 2, player);
sPrint("I see that you have succeeded in your first encounter with the undead.\nI congratulate you but you have a long way to go. Remember, I am your only way to learning about your past. \nNow, make your way down to the bottom of the tower. I will help you where I see fit along the way.");
print("You look around and see that the lights have brightened up. The zombie has been mutilated by your Kitchen Knife. \nYou don't know where the voice came from but you are scared. Behind the zombie's original hiding spot you see a staircase.\nYou follow it down, onto what seems to be..the 11th floor.");
print("");
print("Please input 'complete' to continue");
pause();
sPrint("Chapter 1 complete");
}
Now in this class, engage() is being called to run this chapter. And decision is being called where you see it, as well as in the battle() method(the battle method loops a couple times and decision() is called every loop.
Originally, both Decision and battle are in the superclass, but not in the sub class. This results in the first decision method in the class to be called, but not the second. In the second, it stops at the loop checking the value of univInt.
When I put the decision method into the sub class, It passes the first two but it fails to get past the first one in the battle method for the same reason.
When I put both the decision and battle method into the sub class, it has the same result as just putting decision.
Finally if I put battle in the sub class but not decision it only passes the first two again.
In the project I have one variable named cur that holds the integer value of whatever decision returns. I reuse it for every decision. I don't know if that has anything to do with it. This really doesn't make sense to me how whether the methods are in the same class, or inherited would matter at all if they are the same method.
I am ready to clarify anything and I hope someone is able to understand what is going wrong.
EDIT:
univInt is being set to another number other than 0 outside of decision. thats why it works some times. It is a swing class and a method in a superclass sets univInt to whatever is in a TextField when a button is pressed so with that while loop I try to constantly check to see univInt has been changed from 0
It seems like your "univInt" is a class member, not a local variable, and you do not reinitialize it when entering the function. Thus it won't be changed back to allow the program to enter the if-statement you mention.

Making a player move on 2D array game grid

I am creating a game using a 10x10 2D array. The player starts at the top left hand corner indicated as "P" and the objective is to get the player to avoid obstacles to get to the treasure indicated as "T" located in the lower right corner.
How would I go about making the player move about the grid using commands Up/Down/Left/Right?
Would I use a for loop to count through the elements in the array to designate the move?
Here is what I have so far:
import java.util.Scanner;
import java.util.Random;
public class Adventure {
public static void main(String[] args) {
char grid[][]= new char[10][10];
Scanner move = new Scanner(System.in);
System.out.println("Here is the current game board:");
System.out.println("-------------------------------");
for(int i=0; i<grid.length; i++) {
for(int j=0; j<grid.length; j++) {
double random = Math.random();
if(random <=.05) {
grid[i][j]='*';
}
else if(random > .06 && random <= .15) {
grid[i][j]='X';
}
else {
grid[i][j]='.';
}
grid[0][0]='P';
grid[9][9]='T';
System.out.print(grid[i][j]);
}
System.out.println("");
}
System.out.print("Enter your move (U/D/L/R)>");
}
}
you should keep track of the current position of the player and just update those variables.
initial values would be (0,0) as you said.
int px = 0;
int py = 0;
when a move is made, update the variables accordingly:
grid[px][py] = <empty cell>;
switch (move) {
case 'u': py += 1; break;
case 'r': px += 1; break;
...
}
grid[px][py] = 'P';
of course you shouldn't just updated the values "blindly", you should insert some validation logic to follow the rules of the game:
if (grid[px][py] != <obstacle> )
// update player coordinates...
Looks like you're using row-major ordering, judging from the way your board prints out. Based on that, here's what you'll need to do:
First, you need to store the player's position somewhere. Right now it's hardcoded to 0,0.
Second, you need to read in the player's move. That will have to happen in a loop, where you get a move, check if the move is allowed, perform the move, and display the results.
Third, you need to be able to calculate the new position based on the move. Up means row -= 1. Right means column += 1. Etc.
Given the new coordinates, you need to make sure the move is valid. At the very least, you have to stop them from walking off the board, but you may also prevent them from entering a square with an obstacle, etc.
Once you know that the move is valid, you have to update the variables you're storing the current coordinates in.
At the end of the loop, you'll need to redraw the board.
That's the basic gist of it. Right now you are doing everything in main(), and that's okay, but if it were me I would start to split things out into separate methods, like InitializeBoard(), GetNextMove(), CheckIfMoveIsValid(int r, int c), and so on. That way, main() becomes a high-level view of your game loop, and the guts of the different operations are compartmentalized and more easy to deal with. This will require storing off things like your game board into class variables rather than local variables, which should actually make things like obstacle detection easier than it would be currently.
All of the above answers are great. Here are a few suggestions I would make:
Instead of a char two-dimensional array, I would make a custom object, such as Space, and define a two-dimensional array of Spaces (eg, Space[][]). There are a few reasons for this:
You can define a space in a variety of ways (rather than just 1 character). For example, Space[i][j].hasTreasure() can return a boolean to let you know whether or not you found the treasure.
If you want to add functionality later, its as easy as adding an attribute to your Space class. Again, you are not limited to one character here.
More to your question of movement, I would also recommend a few things. Similar to redneckjedi's suggestion of a CheckIfMoveIsValid() method, I would pass the grid and move direction as parameters and return a boolean. To ensure that you do not end up with ArrayIndexOutOfBounds issues, I would also suggest adding a row/column of walls on each side. I would widen the grid out to 12x12 and put a strip of obstacle-type blocks around the outside. This will ensure that you cannot step outside of the grid as hitting a wall will always return 'false' on a valid move.

Categories