Monday, March 2, 2015

Chapter 5's Basic Battleship Game

This chapter focused on making a Battleship-style game, but only in one dimension. The code in the chapter was left somewhat unfinished - they used a fake "GameHelper" object in place of real user input - but I fixed it and used a Scanner object to detect user input. Here's the code:

import java.util.Scanner;

public class SimpleDotCom {

  int[] locationCells;
 int numOfHits = 0;
 
 public void setLocationCells(int[] locs) {
  locationCells = locs;
 }
 
 public String checkYourself(String stringGuess) {
  int guess = Integer.parseInt(stringGuess);
  String result = "miss";
  
  for (int cell : locationCells) {
   if (guess == cell) {
    result = "hit";
    numOfHits++;
    break;
   }
  }
  
  if (numOfHits == locationCells.length) {
   result = "kill";
  }
  
  System.out.println(result);
   return result;
 }
 
 public static void main(String[] args) {
  int numOfGuesses = 0;
  Scanner user_input = new Scanner(System.in); //Switched "GameHelper" to Scanner function
  
  SimpleDotCom theDotCom = new SimpleDotCom();
  int randomNum = (int) (Math.random() *5);
  
  int[] locations = {randomNum, randomNum+1, randomNum+2};
  theDotCom.setLocationCells(locations);
  boolean isAlive = true;
  
  while(isAlive == true) {
   System.out.println("Enter a number:");
   String guess = user_input.nextLine(); //Used scanner functionality for user input
   String result = theDotCom.checkYourself(guess);
   numOfGuesses++;
   if (result.equals("kill")) {
    isAlive = false;
    System.out.println("You took " + numOfGuesses + " guesses!");
   }
  }
  user_input.close();
 }
}

And here's an example of a game in action:

Enter a number:
5
miss
Enter a number:
4
miss
Enter a number:
7
miss
Enter a number:
8
miss
Enter a number:
6
miss
Enter a number:
1
hit
Enter a number:
2
hit
Enter a number:
3
kill
You took 8 guesses!


No comments:

Post a Comment