Last active
December 28, 2015 09:39
-
-
Save Rican7/7480097 to your computer and use it in GitHub Desktop.
A Dart(lang) translation of an old Codecademy project originally used to learn Python.
PS: Dart's pretty boss. Original Python version: https://gist.github.com/Rican7/5941418
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "dart:math"; | |
import "dart:io"; | |
// Declare our game variables | |
List board; | |
Random randomizer; | |
int numOfRows = 5; | |
int numOfCols = 5; | |
int shipRow; | |
int shipCol; | |
int numOfTurns = 4; | |
/// Setup our board | |
setupBoard(List board, int numOfRows, int numOfCols) { | |
// Setup our board by filling it with [numOfRows] rows | |
var board = new List<List>.generate(numOfRows, (int index) { | |
// Create a list with a [numOfCols] of "O" characters | |
return new List<string>.filled(numOfCols, "O"); | |
}); | |
return board; | |
} | |
/// Print our board | |
printBoard(List board) { | |
print(""); | |
for (var row in board) { | |
print(row.join(" ")); | |
} | |
print(""); | |
} | |
/// Play the game | |
playGame(List board, int shipRow, int shipCol, int numOfTurns) { | |
for (var turn = 0; turn < numOfTurns; turn++) { | |
// Print the board | |
printBoard(board); | |
// Get the guess row | |
print("Guess row: "); | |
var guessRow = int.parse(stdin.readLineSync()); | |
// Get the guess col | |
print("Guess col: "); | |
var guessCol = int.parse(stdin.readLineSync()); | |
print(""); | |
if (guessRow == shipRow && guessCol == shipCol) { | |
print("Congratulations! You sunk my battleship!"); | |
break; | |
} else { | |
if ((guessRow < 0 || guessRow > (board.length - 1)) || | |
(guessCol < 0 || guessCol > (board.first.length - 1))) { | |
print("Oops, that's not even in the ocean."); | |
} else if (board[guessRow][guessCol] == "X") { | |
print("You guessed that one already."); | |
} else { | |
print("You missed my battleship!"); | |
board[guessRow][guessCol] = "X"; | |
} | |
} | |
print("Finished turn ${turn + 1}"); | |
} | |
print("Game Over"); | |
} | |
/// Main program entry | |
main() { | |
// Setup our board | |
board = setupBoard(board, numOfRows, numOfCols); | |
randomizer = new Random(); | |
// Create our target ship"s points | |
shipRow = randomizer.nextInt(board.length); | |
shipCol = randomizer.nextInt(board[0].length); | |
// Herrro! | |
print("Let's play Battleship!"); | |
playGame(board, shipRow, shipCol, numOfTurns); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment