Tuesday, March 10, 2015

Head First Java Chapter 6

    In this chapter we learned more about the java api in order to fix our old battle ship game. We used the api to get arraylist which i have already been using and know about. They are a lot better than arrays because I find them easier to use and more versatile (They are slower though). I also learned about import packages from the java api. You can browse the internet to see all the classes in it. You have to know the full location or name of the file. You can also import as static which was not discussed but allows makes it so you don't have to type the name of the class to run a method or access a variable. Boolean operators were also explained like and (&&) and or (||), the equals(==) and not equals(!=), and the non short circuit and(&) and or(|).

    This is the code for the battle ship game created in this chapter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import java.util.ArrayList;

public class DotCom {
	private ArrayList<String> locationCells;
	private String name;

	public void setLocationCells(ArrayList<String> loc) {
		locationCells = loc;
	}

	public void setName(String n) { //setter
		name = n;
	}

	public String checkYourself(String userInput) {
		String result = "miss";
		int index = locationCells.indexOf(userInput);
		if (index >= 0) {
			locationCells.remove(index);

			if (locationCells.isEmpty()) {
				result = "kill";
				System.out.println("Ouch! You sunk " + name + " : ( ");
			} else {
				result = "hit";
			} // close if
		} // close if
		return result;
	} // close method
} // close class 
 
  

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.ArrayList; 

public class DotComBust {

	private GameHelper helper = new GameHelper();
	private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
	private int numOfGuesses = 0;

	private void setUpGame() {
	 // first make some dot coms and give them locations
		 DotCom one = new DotCom();
		 one.setName("Pets.com");
		 DotCom two = new DotCom();
		 two.setName("eToys.com");
		 DotCom three = new DotCom();
		 three.setName("Go2.com");
		 dotComsList.add(one);
		 dotComsList.add(two);
		 dotComsList.add(three);
		 System.out.println("Your goal is to sink three dot coms.");
		 System.out.println("Pets.com, eToys.com, Go2.com");
		 System.out.println("Try to sink them all in the fewest number of guesses");

		 for (DotCom dotComToSet : dotComsList) {
			 ArrayList<String> newLocation = helper.placeDotCom(3);
			 dotComToSet.setLocationCells(newLocation);
		 } // close for loop
	 } // close setUpGame method

	private void startPlaying() {
		 while(!dotComsList.isEmpty()) {
			 String userGuess = helper.getUserInput("Enter a guess");
			 checkUserGuess(userGuess);
		 } // close while
		 finishGame();
	 } // close startPlaying method

	private void checkUserGuess(String userGuess) {
		 numOfGuesses++;
		 String result = "miss";
		 
		 for (DotCom dotComToTest : dotComsList) {
			 result = dotComToTest.checkYourself(userGuess);
			 if (result.equals("hit")) {
				 break;
			 }
			 if (result.equals("kill")) {
				 dotComsList.remove(dotComToTest);
				 break;
			 }
		 } // close for
		 System.out.println(result);
	 } // close method

	private void finishGame() {
		 System.out.println("All Dot Coms are dead! Your stock is now worthless.");
		 if (numOfGuesses <= 18) {
			 System.out.println("It only took you " + numOfGuesses + " guesses.");
			 System.out.println(" You got out before your options sank.");
		 } else {
			 System.out.println("Took you long enough. "+ numOfGuesses + " guesses.");
			 System.out.println("Fish are dancing with your options.");
		 }
	 } // close method

	public static void main(String[] args) {
		DotComBust game = new DotComBust();
		game.setUpGame();
		game.startPlaying();
	} // close method

}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.*;
import java.util.*;

public class GameHelper {
	private static final String alphabet = "abcdefg";
	private int gridLength = 7;
	private int gridSize = 49;
	private int[] grid = new int[gridSize];
	private int comCount = 0;

	public String getUserInput(String prompt) {
		String inputLine = null;
		System.out.print(prompt + " ");
		try {
			BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
			inputLine = is.readLine();
			if (inputLine.length() == 0) return null;
		} catch (IOException e) {
			System.out.println("IOException: " + e);
		}
		return inputLine.toLowerCase();
	}

	public ArrayList<String> placeDotCom(int comSize) {
		ArrayList<String> alphaCells = new ArrayList<String>();
		String[] alphacoords = new String[comSize]; // holds ‘f6’ type coords
		String temp = null; // temporary String for concat
		int[] coords = new int[comSize]; // current candidate coords
		int attempts = 0; // current attempts counter
		boolean success = false; // flag = found a good location ?
		int location = 0; // current starting location

		comCount++; // nth dot com to place
		int incr = 1; // set horizontal increment
		if ((comCount % 2) == 1) { // if odd dot com (place vertically)
			incr = gridLength; // set vertical increment
		}
		while (!success & attempts++ < 200) { // main search loop (32)
			location = (int) (Math.random() * gridSize); // get random starting point
			//System.out.print(“ try “ + location);
			int x = 0; // nth position in dotcom to place
			success = true; // assume success
			while (success && x < comSize) { // look for adjacent unused spots
				if (grid[location] == 0) { // if not already used
					coords[x++] = location; // save location
					location += incr; // try ‘next’ adjacent
					if (location >= gridSize) { // out of bounds - ‘bottom’
						success = false; // failure
					}
					if (x > 0 && (location % gridLength == 0)) { // out of bounds - right edge
						success = false; // failure
					}
				} else { // found already used location
					// System.out.print(“ used “ + location);
					success = false; // failure
				}
			}
		} // end while

		int x = 0; // turn location into alpha coords
		int row = 0;
		int column = 0;
		// System.out.println(“\n”);
		while (x < comSize) {
			grid[coords[x]] = 1; // mark master grid pts. as ‘used’
			row = (int) (coords[x] / gridLength); // get row value
			column = coords[x] % gridLength; // get numeric column value
			temp = String.valueOf(alphabet.charAt(column)); // convert to alpha

			alphaCells.add(temp.concat(Integer.toString(row)));
			x++;
			// System.out.print(“ coord “+x+” = “ + alphaCells.get(x-1));
		}

		// System.out.println(“\n”);

		return alphaCells;
	}
}

No comments:

Post a Comment