public class Basic
{
public static int numGuess;
public int guess;
public int numHits = 0;
private static int[] ships;
private boolean hitShip;
public static boolean shipSunk;
private int[]board = new int[5];
public Basic()
{
numGuess = 0;
hitShip = false;
shipSunk = false;
}
public static void setShips (int[] loc)
{
ships = loc;
}
public int Check(int z)
{
for(int cell : ships)
{
if(z == cell)
{
hitShip = true;
System.out.println("\nYou hit an enemy ship!");
numHits++;
numGuess++;
if(numHits == ships.length)
{
shipSunk = true;
System.out.println("\nYou sunk the enemy ship!");
System.out.println("the number of guesses it took you to sink the ship is " + numGuess/3);
break;
}
}
else
{
System.out.println("You've missed the enemy ship!");
}
}
return z;
}
}
So I've been working on this battleship project for school and i made this 1-D board for my game. So far i think I've got my code correct, but now i'm stuck. In my for each loop, since it checks my guess with each of the three values of my ship, it prints whether or not i hit the ship three different times everytime i guess. I'm trying to get my program just to print whether or not i hit the ship once everytime i guess.
import java.util.Scanner;
import java.util.Random;
public class BasicTester
{
public static void main(String[] args)
{
Basic shipp = new Basic(); //initalizes basic class
int ship = (int)(Math.random() * 5); // gives ship a random # between 1 - 5
int ship1;
int ship2;
int guess;
if(ship <= 2)
{
ship1 = ship + 1;
ship2 = ship + 2;
}
else
{
ship1 = ship - 1;
ship2 = ship - 2;
}
int[] locations = {ship, ship1, ship2};// sets array of locations
shipp.setShips(locations); // sets locations to ships in other class
Scanner guesss = new Scanner(System.in); // Scanner
do
{
System.out.println("\nTell me where the enemy ship is.");
guess = guesss.nextInt(); // gives guess the int from Scanner
int resultb = shipp.Check(guess); // puts the int guess through the check method
}
while(Basic.shipSunk == false);
}
}
Instead of having your
else
{
System.out.println("You've missed the enemy ship!");
}
Inside the loop, you should set a flag before the loop
hitIt = false;
Then, when you check against the three "ships", you can set this flag to "true" when you find a hit. Finally, check the flag after the loop. If it is still false, print your message.
Related
I am working on a lab that requires me to return the number it flips it requires to get heads. I used a for loop, and a while loop but it appears that returning the method values along with the loops is not making the code runnable. I would appreciate the assistance. There are two pieces of codes, each different classes calling upon another class.
import java.util.*;
public class GVCoin {
// true for heads, false for tails
private boolean isHeads;
private int flips, heads;
private Random r;
public GVCoin() {
r = new Random();
heads = 0;
flips = 0;
isHeads = true;
}
public void flip() {
isHeads = r.nextBoolean(); // Flip the coin by randomly choosing true / false
flips++; // Increment flip count
if(isHeads){
heads++; // Increment heads count if current flip results in heads
}
}
public boolean isHeads() {
return isHeads; // Return true if coin is currently heads
}
public String toString() {
String str;
str = "Flips: " + flips + " Heads: " + heads + " isHeads: " + isHeads;
return str; // Return String representation of important values
}
public int numFlips() {
return flips; // Return number of total flips
}
public int numHeads() {
return heads; // Return number of total heads
}
public int numTails() {
return flips - heads; // Return number of total tails
}
public void setToHeads(boolean h) {
isHeads = h;
}
public GVCoin(int seed) { // Create the coin with a random seed
this();
r = new Random(seed);
}
}
public class TossingCoins {
public int flipForHeads(GVCoin coin, int goal) {
int i = 0;
do {
coin.flip();
i++;
} while (i < goal);
return i;
}
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVCoin coin = new GVCoin(15); // Create a GVCoin object with seed value 15
int numHeads = 100; // Desire 100 heads
int totalFlips;
totalFlips = game.flipForHeads(coin, numHeads);
System.out.println("Total number of flips for 100 heads: " + totalFlips);
}
}
I suggest you not to use seed when you create Random. If you do, the outcome will be always the same.
Here some working code. I removed some code you wrote which I thought not actually needed. Cheers!
class GVCoin {
private Random r;
public GVCoin() {
r = new Random();
}
public GVCoin(int seed) {
this();
r = new Random(seed);
}
public boolean flip() {
return r.nextBoolean();
}
}
public class TossingCoins {
public int flipForHeads(GVCoin coin, int goal) {
int count = 0;
int numberOfHeads = 0;
while (numberOfHeads < goal) {
count++;
boolean isHead = coin.flip();
if (isHead) {
numberOfHeads++;
}
}
return count;
}
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVCoin coin = new GVCoin();
int numberOfHeads = 5;
int totalFlips;
totalFlips = game.flipForHeads(coin, numberOfHeads);
System.out.println("Total number of flips for "+ numberOfHeads + " heads: " + totalFlips);
}
}
I managed to figure out the code. On the method call I simply formatted the code as follows:
int flips = 0;
while (coin.numHeads() < goal) {
coin.flip();
flips++ ;
}
return flips;
I have a project I am working on in my java class and cannot figure out what a few lines of code.
The project consists of flipping a coin and using various methods to detect how many heads or tails as well as how many flips have occurred so far.
import java.util.*;
public class GVcoin{
// true for heads, false for tails
private boolean isHeads;
private int flips, heads;
private Random r;
//Create the coin
public GVcoin(){
r = new Random();
heads = 0;
flips = 0;
isHeads = true;
}
//Flip the coin by random choosing true / false
public void flip(){
isHeads = r.nextBoolean();
flips++;
if(isHeads){
heads++;
}
}
//return true if coin is currently heads
public boolean isHeads(){
return isHeads;
}
//return String representation of important values
public String toString(){
String str;
str = "Flips: " + flips + " Heads: " + heads + " isHeads: " + isHeads;
return str;
}
//return number of total flips
public int numFlips(){
return flips;
}
//return number of total heads
public int numHeads(){
return heads;
}
//return number of total tails
public int numTails(){
return flips - heads;
}
//Set the coin to heads (or tails) to start
public void setToHeads(boolean h){
isHeads = h;
}
//Create the coin with a random seed
public GVcoin(int seed){
this();
r = new Random(seed);
}
}
The problem I can not seem to figure out is in a different class called TossingCoins and is the method public int consecutiveHeads(GVcoin c, int goal)
public class TossingCoins {
public int countHeads(GVcoin c, int goal){
while(c.numHeads() != goal) {
c.flip();
}
return c.numFlips();
}
public int flipForTails(GVcoin c, int goal){
while(c.numTails() != goal) {
c.flip();
}
return c.numFlips();
}
public int consecutiveHeads(GVcoin c, int goal){
while(c.numHeads() != goal){
c.flip();
}
}
// This method creates a TossingCoins object and calls the method for testing
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVcoin c = new GVcoin();
int numHeads = game.countHeads(c, 100);
}
}
What I have tried so far is see if the numHeads is not equal to the goal of heads. Then if it is not equal to the number of heads(goal), I would set the flip to add one. Which wold count 1, 2, 3, 4, 5 and so on till it hits the amount flips needed to hit the number of heads(goal).
The NumberTile class models a number tile which is an arrayList of 4 integers, the TileGame class inserts a tile into the board, and a test class to start the game. A hand is an arraylist of 5 NumberTiles, but when I compile this, every time I reference to an ArrayList of NumberTile in TileGame, it cannot find the symbol NumberTile.
Do I need to create a package so it would recognize it? My instructor provided most of those statements and I cannot change them. I did not type the other methods because I do not think they are necessary.
Also, the line TileGame game = new TileGame(); says cannot find symbol. What would be the right way to initialize it?
I need any help I can get. Thank you.
Class TileGame:
public class TileGame
{
//provided by instructor
private ArrayList<NumberTile> board ;
// Creates an empty board
public TileGame()
{
//do not modify this method
board = new ArrayList<NumberTile>();
}
// Accessor for the board
public ArrayList<NumberTile> getBoard()
{
// Do not modify this method
return board ;
}
// Creates and returns a hand of 5 random number tiles
public ArrayList<NumberTile> getHand()
{
ArrayList<NumberTile> hand = new ArrayList<NumberTile>() ;
for (int a = 0; a < 5; a++)
{
hand.add(a, new NumberTile());
}
return hand;
}
// If the current tile fits in the board (without rotating) then
// return the index i of a tile in the board so that the current tile
// fits before ti for i = 0..k-1, or return k if the current tile fits
// after the last tile. If the tile does not fit, return -1
public int getIndexForFit(NumberTile currentTile)
{
NumberTile firstTile = board.get(0);
NumberTile lastTile = board.get(board.size() - 1);
if(firstTile.getLeft() == currentTile.getRight())
{
return 0;
}
else if (lastTile.getRight() == currentTile.getLeft())
{
return board.size() - 1;
}
else
{
return -1 ;
}
}
// Call the method getIndexForFit to see whether a tile can be inserted
// into the board. In this method the tile can be rotated. If the tile
// can be inserted, return true. If the tile does not fit after
// rotating (at most 3 times), return false.
public boolean canInsertTile(NumberTile currentTile)
{
//call get index for fit
int canInsert = getIndexForFit(currentTile);
boolean canInsertOrNot = false;;
//if true, modify index
if(canInsert == -1)
{
//rotate
for (int rotations = 0; rotations < 3; rotations++)
{
currentTile.rotate();
int didRotationWork = getIndexForFit(currentTile);
if (didRotationWork == -1)
{
continue;
}
else if (didRotationWork != -1)
{
canInsertOrNot = true;
}
}
return false;
}
else if(canInsert != -1)
{
return true;
}
return canInsertOrNot;
}
// Make a move. I.e. if a tile in the hand fits on the board
// then remove it from the hand and place it in the board. If no tile
// from the hand fits, then add another tile to the hand
public void makeMove(ArrayList<NumberTile> hand)
{
boolean fits;
for (int x = 0; x < hand.size(); x++)
{
//call caninterserttile
fits = canInsertTile(hand.get(x));
if(fits)
{
int index = getIndexForFit(hand.get(x));
board.add(index, hand.get(x));
hand.remove(x);
break;
}
else
{
hand.add(hand.size() -1, new NumberTile());
}
}
}
public String toString()
{
// Do not modify this method
return board.toString() ; // ArrayList as a String
}
} // end of TileGame class
Class NumberTile:
public class NumberTile
{
public ArrayList<Integer> tile = new ArrayList<>();
// Constructs a NumberTile object using 4 random integers in the
// range 1 to 9
public NumberTile()
{
Random generator = new Random() ;
for (int a = 0; a < 4; a++)
{
int random = generator.nextInt(9);
tile.add(a, random);
}
}
// Rotate the tile 90 degrees
public void rotate()
{
int temp = tile.get(0);
tile.set(0, tile.get(1));
tile.set(1, tile.get(3));
tile.set(3, tile.get(2));
tile.set(2, temp);
}
public int getLeft()
{
// Do not modify this method
return tile.get(0) ;
}
public int getRight()
{
// Do not modify this method
return tile.get(2) ;
}
public String toString()
{
String out = "";
out += " "+tile.get(0)+" ";
out += tile.get(1) + " " + tile.get(2);
out += " "+tile.get(3)+" ";
return out;
}
} // end of NumberTile class
Class TileGameTester:
public class TileGameTester {
public static void main(String[] args){
TileGame game = new TileGame();
boolean winner = false;
//get two hands
ArrayList<NumberTile> hand1 = game.getHand();
ArrayList<NumberTile> hand2 = game.getHand();
//create an empty board
System.out.println(game.getBoard());
do{
//make moves
game.makeMove(hand1);
game.makeMove(hand2);
//check if they won
if (hand1.isEmpty() || hand2.isEmpty())
{
winner = true;
}
}while(!winner);
hand1.toString();
hand2.toString();
if (hand1.isEmpty() && hand2.isEmpty())
{
System.out.println("It is a tie!");
}
else if (hand1.isEmpty())
{
System.out.println("Player 1 won!");
}
else if (hand2.isEmpty())
System.out.println("Player 2 won!");
}
}
Though it is incomplete so i am not sure if you are adding data to the arraylist or not but if you are getting Symbol not found .
I am also not able to see any import statements . Did you import the objects
eg TileGameTester should have import -> import com.something.TileGame and import com.something.NumberTile
also check if you have import statement in TileGame and common imports like arraylist
I think you may need to insert "import java.util.Random;" and "import java.util.ArrayList;" between your package declaration (if you have one) and the class declaration in the files where these are used.
You can import TileGame class to TileGameTester class that might solve your issue.
This is the code for FlipRace program which initiates a race between two coins. GOAL is a globally declared variable. Whichever coin reaches GOAL number of heads fastest wins. Below it is the code for the Coin class.
My problem is that if I put GOAL = 3 , that is whichever coin gets 3 heads fastest wins, it works ok. When I set GOAL = 4 , still it works ok. But something weird starts happening once I put GOAL > 4. Say I put GOAL = 7, still the final result comes only when one coin has registered 4 heads NOT 7.
// FlipRace.java
package nisarg;
public class FlipRace {
public static void main(String[] args){
final int GOAL = 6;
int count1=0,count2=0;
Coin myCoin1 = new Coin();
Coin myCoin2 = new Coin();
while(count1 < GOAL && count2 < GOAL){
myCoin1.Flip();
myCoin2.Flip();
System.out.print("Coin1 : " +myCoin1 +"\t");
System.out.println("Coin2 :"+myCoin2);
count1 = (myCoin1.isHeads())? count1+1 : 0;
count2 = (myCoin2.isHeads())? count2+1 : 0;
}
if(count2 < GOAL) {
System.out.println("Coin1 wins!!");
} else if(count1 < GOAL){
System.out.println("Coin2 wins!!");
}
else {
System.out.println("Its a tie!!");
}
}
}
// Coin.java
package nisarg;
import java.util.Random;
public class Coin {
private final int HEADS = 1;
private final int TAILS = 0;
private int face;
public Coin(){
Flip();
}
public void Flip(){
face = (int)(Math.random()*2);
}
public boolean isHeads(){
return(face == HEADS);
}
public String toString(){
String faceName;
if(face == HEADS){
faceName = "H";
}
else {
faceName = "T";
}
return faceName;
}
}
I am trying to learn OOP, starting with Java as I have read and been told it's the best place to start. With that said, I am trying to create a game for fun to help my learning, but I also know game programming and design can be more challenging.
So my goal here is to generate a new value from the RollDice D20 without having to reset or restart the program. You'll notice when I print out the values I print the same instance twice to demonstrate what I am avoiding, and a new instance to show that the new instance does indeed generate a new value. Perhaps, I am not approaching this in the right way, but this is a hurdle I am hoping to overcome with some help!
What I ultimately want is to figure out how to generate a new instance or at least a new roll value as many times as I want. Any and all help is greatly appreciated! I have added the code below as an example. Also any other feedback is appreciated.
import java.util.Random;
class RollDice
{// Begin RollDice Class
// Initiate method rollDice
public static int rollDice(int number, int nSides)
{
// System.out.println( "--- Welcome to the Dice Game v2! ---" ); //
// welcomes player
Random r = new Random();
// Declare class variables
int num = 0;
int roll = 0;
if (nSides >= 3)
{
for (int i = 0; i < number; i++)
{
roll = r.nextInt(nSides) + 1;
// System.out.println("Roll is: " + roll);
num = num + roll;
}
}
else
{
System.out.println("Error num needs to be from 3");
}
return num;
} // end method rollDice
int d4 = rollDice(1, 4);
int d6 = rollDice(1, 6);
int d8 = rollDice(1, 8);
int d10 = rollDice(1, 10);
int d12 = rollDice(1, 12);
int d20 = rollDice(1, 20);
public RollDice()
{
this.d4 = d4;
}
public void setD4(int D4)
{
this.d4 = D4;
}
public int getD4()
{
return d4;
}
// ////////////////
{
this.d6 = d6;
}
public void setD6(int D6)
{
this.d6 = D6;
}
public int getD6()
{
return d6;
}
// ////////////////
{
this.d8 = d8;
}
public void setD8(int D8)
{
this.d8 = D8;
}
public int getD8()
{
return d8;
}
// ////////////////
{
this.d10 = d10;
}
public void setD10(int D10)
{
this.d10 = D10;
}
public int getD10()
{
return d10;
}
// ////////////////
{
this.d12 = d12;
}
public void setD12(int D12)
{
this.d12 = D12;
}
public int getD12()
{
return d12;
}
// ////////////////
{
this.d20 = d20;
}
public void setD20(int D20)
{
this.d20 = D20;
}
public int getD20()
{
return d20;
}
// ////////////////
}// End RollDice Class
class Champion
{// Begin Champion Class
RollDice champDice = new RollDice();
int champroll = champDice.getD20();
public Champion()
{
this.champroll = champroll;
}
public void setChampRoll(int ChampRoll)
{
this.champroll = ChampRoll;
}
public int getChampRoll()
{
return champroll;
}
}// End Champion Class
public class DiceRollTest
{
public static void main(String ars[])
{
Champion tChampion = new Champion();
Champion pChampion = new Champion();
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + tChampion.getChampRoll() + "\n");
System.out.println("Your Champion defends with a " + pChampion.getChampRoll() + "\n");
}
}
Your RollDice class is not accomplishing what you want. All it's doing is storing a single dice roll result for each type of dice you have. Therefore, when you go an call getChampRoll() on your Champion object, all it's doing is returning the roll that already took place when you constructed your RollDice class.
Instead, you should make rollDice() a member function of your RollDice class. RollDice should then take in its constructor an argument indicating which dice should be rolled when rollDice() is called. That way, when you call getD20(), it will roll the D20 and give you the result.
I'll leave you with this as a starting point:
import java.util.Random;
public class Die {
private int mSides;
private Random mRandom;
public Die(int sides) {
this.mSides = sides;
mRandom = new Random(System.currentTimeMillis());
}
public int roll() {
return mRandom.nextInt(mSides + 1);
}
public int roll(int times) {
int sum = 0;
for (int i = 0; i < times; i++) {
sum += roll();
}
return sum;
}
}
This class can be inherited/subclassed for each dice you want to create. Then you can toss a few of these in your champion's pockets :)
First, you should create new Constructor. In this constructor you should inicialize Random object, and probably how many sides will dice have
class RollDice{
Random rand;
int sides;
public RollDice(int x){
sides = x;
rand = new Random()
}
}
then, in that class you can add method which will generate new value
public int roll(){
return rand.nextInt(x);
}
you may as well don,t generate RollDice object with fixed value of dice's sides and make the method like:
public int roll(int x){
return rand.nextInt(x);
}
if you want java to generate new value after you enter something on console just use loop with System.in.read() and if or switch statement (for example if someone enters 1 - generate new value, if 0, end program)