To implement pile of cards and manage players - java

includes a pile of cards in a player’s hand and two actions: TAKE and DISCARD. TAKE puts a card on the top of a player’s pile of cards when that player receives a card from a dealer. DISCARD removes a card from the top of a player’s pile of cards when a player plays it against another player in the game. Each player receives 16 cards from the dealer at the
beginning of a game........
I tried my code like this which gives me nothing
public class play {
int noOfCards = 16;
static void TAKE(Stack st, int a) {
st.push(new Integer(a));
}
static void DISCARD(Stack st) {
Integer a = (Integer) st.pop();
}
public static void main(String args[]) {
for(int i=0; i<=16; i++) {
Stack st = new Stack();
st.take();
st.discard();
}
}
}
I am new to this concepts ....give me a path to solve this question

I'm sorry but I didn't fully understand the whole process you're trying to do. But I still gave it a shot.
public class Play
{
private static int noOfCards = 16;
private static Stack<Integer> player1 = new Stack<Integer>();
private static Stack<Integer> player2 = new Stack<Integer>();
static void takeCard(Stack<Integer> st,int cardValue){
st.push(cardValue);
}
static int discardCard(Stack<Integer> st){
return st.pop();
}
static int getRandomValue(int min, int max){
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
//Filled card pile with random values from 1-13
public static void main(String[] args)
{
for(int i = 0 ; i < noOfCards; i++){
takeCard(player1,getRandomValue(1,13));
takeCard(player2,getRandomValue(1,13));
}
//player 1 takes a card!
//Size of player1's pile before and after taking card
System.out.println("Before:" + player1.size());
takeCard(player1, getRandomValue(1, 13));
System.out.println("After" + player1.size());
//player 2 discards a card and outputs the card's value
System.out.println("Player 2 discards: " + discardCard(player2));
}
}

Not sure what you want it to do. Are you just trying to implement TAKE and DISCARD? Despite not knowing exactly what you're trying to do, there are lots of issues with your code.
One immediate issue is the fact that your Stack initialization is inside your for loop meaning that every time you execute that loop, you create a brand new Stack, which will be empty. So, essentially, your main method does this:
Create a new Stack (it's empty)
Add a card to the stack
Remove a card from the stack
Repeat steps 1-3 16 times
Another issue is that Java is case sensitive so calling st.take() doesn't match up with TAKE().
Yet another issue is that st.take() is like saying "Call the 'take()' method on my instance of Stack". Stack doesn't define a method called take() - it has methods like push() and pop() (look here: http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html). Your take and discard methods are on the class Play, so you'd want to invoke them like this:
Play.TAKE(st, 3);
Play.DISCARD(st);
Another issue: when you try to invoke keep or discard, you don't send any parameters, but you've defined these methods to take parameters. See above.
Is discard supposed to return the value of the card being discarded? You retrieve that value and store it into the local variable "a" and then you don't do anything with it. If you're not going to return it, you don't need to create "a". If you are going to return it, your return type shouldn't be void.

Related

JAVA seperate class method not incrementing a variable in my main class method

so this is the main code for my text-based game.
import java.util.Scanner;
public class D_M_RPG {
public static void main(String[] args) {
//Creating the class to call on my toolbox
D_M_RPGtoolbox toolbox = new D_M_RPGtoolbox();
//Creating the scanner class for user input
Scanner input = new Scanner(System.in);
//Initiating variables and final variables aswell as arrays
//token variable to validate open spots in an array
int slotCounter = 0;
int inventoryExpander = 11;
//First initiated will be the character creation variables
String hairColor = "";
String eyeColor = "";
String skinColor = "";
String gender = "";
//Initiating the arrays for character inventory slots
String[] weaponSlots = new String[10];
//initiating the arrays for the character creation
String[] hairColorARR = {"black","Green","Yellow","Brown","Blue","Blonde","Grey","White"};
String[] eyeColorARR = {"Green","Brown","Blue","Grey",};
String[] skinColorARR = {"White","brown","Black",};
String[] genderARR = {"Male","Female"};
//Creating the introduction title and introduction
System.out.println("Welcome to, COLD OMEN.");
System.out.println("\nNOVEMBER 12th, 2150: ONTARIO, CANADA");
System.out.println("\nYou hear loud shouts and gun fire all around you but can't pinpoint the location of anything, you feel a bit dazed until someone grabs you and you open your eyes and snap out of it.");
System.out.println("\nUnknown: 'Get up, its time to move out. Take this.'");
System.out.println("\nUnknown hands you a 'M4-A4 RIFLE'");
System.out.println("\nyou manage to catch a small glimpse of him before you get up.");
//Character creation screen
System.out.println();
//ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "M4-A4 RIFLE");
System.out.println("\n" + weaponSlots[0]);
toolbox.insert(weaponSlots, slotCounter, inventoryExpander, "ak47");
System.out.println(weaponSlots[0]);
}
}
so I have this method I made to basically add an "item" to the weaponSlots array (the inventory) but whenever I run it it will add to the first element in the array [0] but it wont incremement the slotcounter which should go up by one every time the method is used so that I dont replace any items in the array It should just add items until its full which is checked using the inventoryExpander variable. at the moment I have it printing the element at 0 and 0 for the array but i have checked 1 aswell and 1 is just null no item added it only just replaces the element at 0. heres the code for the method to increment etc:
public class D_M_RPGtoolbox {
//method for random number generating to be used for crit hits, turns, loot generation etc
public int randomGen(){
int x = (int) (Math.random()*((20-0)+1)+0);
return x;
}
//method for inserting into an array ONLY WORKS ONCE WONT INCREMEMENT THE SLOTCOUNTER FIX
public void insert(String[] a, int b, int d , String c) {
if(b < d) {
a[b] = c;
b++;
}//end of if statement
}//end of method
}
What you are actually performing the ++ operation on in b is a copy of the value in slotCounter.
The variable slotCounter is passed into insert "by-value".
This unlike what you probably imagine, that it is passed "by-reference".
One solution would be to do the slotCounter++ from the call row instead; and another would be to let the toolbox own the slotCounter variable completely.
This question uses the image of passing a copy of document content (by value) where changes to the document would not be seen by the sender; or as a link to a shared document (by reference), where changes could be made to the same page that the sender sees.
Its always going to be zero since you are passing zero and incrementing the local variable b.
Try calling the method as below with post increment ++ to slotCounter and see if it works for you,
toolbox.insert(weaponSlots, slotCounter++, inventoryExpander, "M4-A4 RIFLE");

Using loops and arrays to switch between players in a quiz game

I'm in the process of writing a very simple quiz-style boardgame that moves players around the board based on if they answer the question correctly and what they roll on the dice. I'm attempting to create and pass an array mehtod that stores the scores of player 1 and player 2, but the array doesn't seem to actually keep track of the score. For example, a fragment of some of the code is as follows:
public static int[] scorearray
{
int scoreplayer1 = 0;
int scoreplayer2 = 0;
return new int[] = {scoreplayer1, scoreplayer2};
}
public static int questions(int diceroll, int[] score)
{
String textinput = input("What's 9+10?");
int ans = Integer.parseInt(textinput);
if (ans == 19)
{
output("Fantastic answer, that's correct!");
diceroll = dicethrow(diceroll); // rolls the dice
output("Move forward " + diceroll + " squares. You are on square " + score[0]);
//I need the output above to print position 0 in the above array
score[0] = score[0] + diceroll; //array stores the cumulative score
}
else
{
output("Sorry, the answer was 19. Next player's turn.")
//This is where I need the loop to switch between players
}
In addition, I need to come up with a way of switching between player 1 and 2 while also switching to the position 1 in the above array, that is, I need to add to player two's score instead of player one's. I've been combing through this code for ages now trying to figure out how to do this but I can only come up with the idea of using a for/while loop. Other than that I'm truly stumped.
Thanks.
EDIT: It appears that my array apparently still does not store the score when being used in the method questions.
Also I have now realised I can control whose turn it is by creating another method, for example public static void activePlayer() but I'm still not sure how to use a loop (or anything else for that matter) to switch between the two. Also my concern is where I use score[0] = score[0] + diceroll; in my questions method only keeps the score (or at least attempts to; see above problem) for player one. How would I switch it to keep score for score[1]? Please.
your options here seem to be either have your questions function output the score or change your score object to be a static object instead of a static function.
public static int[] scorearray = [0,0];
or
public static int[] questions(int diceroll, int[] score)

Adding the output of Stack.pop()

import java.util.Random;
import java.util.Stack;
public class Blackjack {
public static void main(String[] args) {
int cardValue; /* card value is from 2 to 11 */
Stack Player1 = new Stack();
Stack Addition = new Stack();
Random r = new Random();
int i = 2 + r.nextInt(11);
System.out.println("Welcome to Mitchell's blackjack program!");
for (int a = 1; a <= 2; a++) { /* Start's the game by assigning 2 cards each, to the players */
Player1.push(i);
}
while (!Player1.empty()) {
System.out.print("You get a " + Player1.pop());
System.out.print("and");
int sum = 0;
for (int n = 0; n < Player1.size(); n++) {
sum = sum + Player1.pop();
System.out.print("Your total is " + sum);
}
}
}
}
So I just started learning java and I'm trying to accomplish this BlackJack project But, when I try to compile using javac the output was bad operand types for binary operator '+' for the 'sum = sum + Player1.pop();'
The solution i used in the above coding was from here
Player1.pop() returns an Object because you used Stack without providing a type. and you cannot do int + Object. If you need to store ints in the Stack, just use generics and do
Stack<Integer> Player1 = new Stac<Integer>k();
Stack<Integer> Addition = new Stack<Integer>();
And your
System.out.print("Your total is " + sum);
should be outside the for otherwise you will get a temporary sum
Change Stack to Stack<Integer>.
By default, you get a stack of (unknown) Objects, and you can't add an Object to an int.
Stack takes a generic argument that determines the type of Object that the Stack will store. This in turn defines the type of Object that pop() returns. In your case you could use a numeric type e.g.
Stack Player1 = new Stack<Integer>();
Providing no type argument will result in Object being returned and int + Object is not defined, hence your error.
Others have explained this using Java generics, the new Stack() approach, which tells the compiler to only let you put Integers into the Stack, and automatically takes Integers out.
Before generics, you'd just cast whatever it was you brought out of the Stack to an Integer. As people have said, the problem is that your code doesn't know what it's getting back from the stack, so it assumes Object, and doesn't know how to add those. Casting would look like:
sum = sum + (Integer)Player1.pop();
Although using Stack will solve this problem. But I guess there are issues the way you have used loop.
Your while loop will execute only once, as you for loop will empty that stack. Not sure if that's what you want to do.

connect 4 java issues: How do I do this?

I am a noob to java, as well as programming, and I am having large difficulties picturing how to actually execute each method in order to create the Connect Four game. There are 4 methods, main, printBoard, checkWinner, and playerMove. I may add more methods if necessary. I am overwhelmed and need a ton of guidance. how to approach each method? Sorry if this is a mammoth question, I am throughly confused.
import java.util.Scanner;
public class ConnectFour{
// We will represent the game board using a 2 dimensional integer array.
// Each entry of the array will contain a 0, 1, or -1.
// A 0 entry in the array represents an empty slot.
// A 1 entry represents Player 1's piece.
// A -1 entry represents Player 2's piece.
// Since most methods will need to access this board, we have decided to
// make it a global class variable.
import java.util.Scanner;
public class ConnectFour{
public static int[][] board = new int[6][7];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// initializing board
for(int i = 0; i < 6; i++){
for(int j = 0; j < 7; j++){
board[i][j] = 0;
}
}
// WRITE CODE HERE
if (j < 7 && j >= 0)
f[i][j] =".";
else f[i][j] = " ";
return board;
}
}
// This method prints the board on the screen.
// To represent Player 1's pieces, print 'X'.
// To represent Player 2's pieces, print 'O'.
// To represent an empty slot, print '.'.
public static void printBoard(){
// WRITE CODE HERE
for (int i = 0; i < 6; i++)
{
for (int j = 0;j < 7; j++)
{
System.out.print(f[i][j]);
}
System.out.println();
}
}
// This method scans the current board and checks if there is a winner.
// The method should return 1 if Player 1 has connected 4 pieces.
// It should return -1 if Player 2 has connected 4 pieces.
// It should return 0 if no player has connected 4 pieces.
public static int checkWinner(){
// WRITE CODE HERE
return;}
// This method implements a player's move and updates the board accordingly.
// The method has two integer inputs.
// The first input indicates the player (1 for Player 1, -1 for Player 2).
// The second input indicates the column number that the player has
// chosen to play.
// If the column number is out of range or the column is currently full,
// the method should return false.
// Otherwise, the board should be updated and the method should return true.
public static boolean playerMove(int player, int columnNum){
// WRITE CODE HERE
}
}
Think about how your program should work, logically. I would personally put your board in a separate class, but it's not too important, especially since the program is pretty small. This isn't really as much as a code problem as much as a logic one, so we'll walk through how the game works.
First off, what does each function do? We have checkWinner(), playerMove(), and printBoard(). So we'll have a loop until the game ends, which should be controlled by checkWinner(), like so
while !checkWinner
So the game will loop until a winner is found, and any code executed after the while loop is end game code. Inside our while loop should go all of code executed every frame while there is no winner, since that is how our while loop is setup now. So let's think about what should execute every frame of your game.
printBoard()? Yeah, probably, since we want to update the display every frame right?
playerMove()? Yeah, since if the game hasn't ended, we want the players to execute a move. However, you need to make sure that the code is functional for switching between players. If you do that, the basic game loop should be finished. Here's some psuedocode for that
//setup board here
while !checkWinner
printBoard
playerMove
//since checkwinner did not return 0, a player won. so we put in endgame code here
The main issue here is thinking out how your program should work, logically. So plan out which functions do what, and try to write it out.
Hope that helps.

Bingo Card Game in Java

I created two methods for my Bingo Game in Java. One method creates a new board which populates the Bingo Board with integers according to the Bingo rule (1-75). My second method generates random numbers with a range of 1 - 75.
public static int drawNum(){
Random rand = new Random();
int num = rand.nextInt(75)+1;
return num;
}
public static void bingoCard(){
int [][]card=new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
int tmp = 0;
for(int i = 0; i <= 4; i++){
for(int row = 0; row < card.length; row++){
while(!valid){
tmp = (int)(Math.random() * 15) + 1 + 15 * i;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][i] = tmp;
valid = false;
}
}
card[2][2] = 0;
//create array to make title.
String title []={"B","I","N","G","O"};
for(int i=0;i<title.length;i++){
System.out.print(title[i]+ "\t");
}
System.out.println();
for(int row=0;row<card.length;row++){
for(int col=0;col<card[row].length;col++){
System.out.print(card[row][col]+ "\t");
}
System.out.println();
}
}
What I need help with is, how do I check whether or not the drawNum() method corresponds to any values stored inside my bingoCard() array? If so, print out a new array with the integers filled in. If the condition is met for a bingo, then you win.
I hope I don't make it sound like I want you to do it for me, but I am confused as to how to start coding that part. Thank you.
This my recommendation - Learn Object Oriented Programming immediately
I see you are using objects provided in the JDK, so why not learn to make your own?
Make two classes with the following methods (-) and members (+) (PS. This is not a formal way to document code)
BingoCard
+list of numbers on card
-reset() : gets new numbers for this card
-test(BingoDrawer) : Tests to see if this card won on this drawing
-toString() : returns a String representation of this card
BingoDrawer
+list of numbers drawn
-reset() : draws new numbers
-hasNumber(int number) : tests if this number was drawn
-toString() : returns a String representation of this drawing
One more suggestions
Instead of keeping track of what you used, keep track of what you have not used, it will make things much easier because you can just choose stuff from that list randomly. Unlike your current action which is choosing (a logical number) from thin air and hoping (which causes issues) it is not a collision
If you follow my recommendation you can write code like this
public static void main(String[] args) {
BingoCard bc = new BingoCard();
BingoDrawer bd = new BingoDrawer();
while(thePlayerWantsToPlay()) { //function to be defined by you
bc.reset();
bd.reset();
System.out.println(bc);
System.out.println(bd);
System.out.println(bc.test(bd));
}
}
You can take it a step further and make a BingoGame class and do what I did in main there and just create an instance of BingoGame and call some start method on the object.
For checking if you have the number in your board, read through the board in a similar manner as you do for the already_used numbers, except with the number the user just entered.
The conditions for the user to win should be checked after the board has another number guessed.
There are a few ways to do this, a simple one would be to iterate over every possible pattern that could win, checking to see if there are tokens there.
All of this would be in a loop, that goes a little like this:
Set up board via user entering numbers.
Start loop
set either a timer to wait for, or wait for a keypress (so the game doesn't just play really fast)
Get random number
Possibly add to board
Check if winner
if winner, break the loop and do something else.
Print the new board out.
(end of loop)
If they got here, that could mean they won!
Wait to exit
You can just write it out as pseudo-code and fill in the methods after that. It usually helps to work on these things in a top-down fashion. So, for bingo you might have:
board = generateBoard();
while (!bingoFound(board)) {
number = drawNumber();
board = stampNumbers(board, number);
}
If that makes sense, you can go a step deeper and define each method. For example, bingoFound might look like:
public boolean bingoFound(int[][] board) {
boolean wasFound = bingoRowFound(board)
|| bingoColFound(board)
|| bingoDiagonalFound(board);
return wasFound;
}
Again, I've defined everything in (mostly) pseudo-code. If this looks ok, you can move a step deeper. Let's define the bingoRowFound method.
public boolean bingoRowFound(int[][] board) {
for (int row = 0; row < NUM_ROWS; row++) {
boolean rowIsABingo = true;
for (int col = 0; col < NUM_COLS; col++) {
// We have to check that everything up until this point has
// been marked off. I am using -1 to indicate that a spot has
// been marked.
rowIsABingo = rowIsABingo && board[row][col] == -1;
}
if (rowIsABingo) { return rowIsABingo; }
}
return false; // If we didn't find a bingo, return false.
}
Some of the methods (like drawNumber) will be really easy to implement. Others, like looking for a diagonal bingo might be a bit more difficult.
Feb 12 2014 Update:
Retracted code, since this was a college course assignment, and I want to prevent people just copying the code. I almost got in trouble for being accused of sharing code (which is a nono in assignments) when another student lifted my code from my Github repo and sent it in as their own.
There were two classes, one main class and a class to hold my methods and constructors.
BINGOFINAL.java was my main class.
Bingo_Card.java held my constructor and methods.
If you want to run this, make sure you create a new project called BINGOFINAL, and put Bingo_Card.java into that same */src/ extension.

Categories