Coin Takers
Coin Takers
is an interesting two player game which is played using coins.
In every
round there would be total 31 coins and both players are allowed to pick up to
5 coins maximum turn by turn. Means you can pick minimum 1 coin and maximum 5.
In this game one player will be you and other player will be computer. The
player who will pick the last coin will lose.
Let see an example:
To simulate this game you need two variables: one
which will tell whose turn it is and 2nd variable which will tell how many
coins are left.
One example running
is following:
1st Player’s Name
is Computer
2nd Player’s Name:
Harry
Harry, you
have won the toss, start the game
Harry, pick
your coins: 4
Remaining
Coins are 27
Computer
has picked 5 coins
Remaining
Coins are 22
Harry, pick
your coins: 5
Remaining
Coins are 17
Computer
has picked 4 coins
Remaining
Coins are 13
Harry, pick
your coins: 5
Remaining
Coins are 8
Computer
has picked 4 coins
Remaining
Coins are 4
Harry, pick
your coins: 3
Computer,
you have lost by picking the last coin... Good luck for next time…
Assignment
Write a
program which will simulate this simple game by randomly deciding who will take
first turn. You will choose your
coins yourself and Computer will choose its coins randomly. You need to use
Math.random() functions to complete this game.
Java code for given assignment is as below:
/* Rashid-5717 */
import java.util.*;
import javax.swing.*;
class CoinTakerVersion1{
public static void main(String a[]){
Scanner obj=new Scanner(System.in);
int n=0;
int rem=31;
int turn=(int)(Math.random() * ((2 - 1) + 1) + 1);
if(turn==1){
System.out.println("Harry! You have won the toss, start the game!");
}else if(turn==2){
System.out.println("Computer won the toss!");
}
do{
if(turn==1){
System.out.print("Harry, Pick your Coins?: ");
n=obj.nextInt();
}
else{
if(rem>5){
n=(int)(Math.random() * ((5 - 1) + 1) + 1);
}else{
if(rem!=1){
n=rem-1;
}else{
n=1;
}
}
System.out.println("Computer Picked "+n+" Coins!");
}
if(n<=rem){
if(n<=5 && n>=1){
rem=rem-n;
System.out.println("Remaining Coins are "+rem);
if(turn==1){
turn=2;
}else if(turn==2){
turn=1;
}
}
else{
System.out.println("You can Pick minimum 1 and maximum 5 Coins!");
}
}
else{
System.out.println("Not enough Coins");
}
}while(rem>0);
if(turn==1){
System.out.println("Harry Won the Game!");
}else{
System.out.println("Computer Won the Game!");
}
}
}
No comments:
Post a Comment