Skip to content

Instantly share code, notes, and snippets.

@Rican7
Created May 23, 2014 19:06
Show Gist options
  • Save Rican7/fac67bb68672be09678e to your computer and use it in GitHub Desktop.
Save Rican7/fac67bb68672be09678e to your computer and use it in GitHub Desktop.
A Go(lang) translation of an old Codecademy project originally used to learn Python. Original Python version: https://gist.github.com/Rican7/5941418
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
// Default configuration
var boardSize = 5
var maxTurns = 4
// Setup the game board
func setupBoard(size int) [][]string {
// Set a default size
if size <= 0 {
size = boardSize
}
board := make([][]string, size)
// Fill the board with size*size O's
for i := 0; i < size; i++ {
board[i] = make([]string, size)
for idx := range board[i] {
board[i][idx] = "O"
}
}
return board
}
// Make it easier to print our board
func printBoard(board [][]string) {
// Print an empty spacing line
fmt.Println()
for _, row := range board {
fmt.Println(strings.Join(row, " "))
}
fmt.Println()
}
// Quick macro to generate a random integer
func randomInt(min, max int) int {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return r.Intn(max-min) + min
}
// Setup our enemy ship
func setupShip(board [][]string) []int {
row := randomInt(0, len(board))
col := randomInt(0, len(board[0]))
return []int{row, col}
}
// Play the game!
func playGame(board [][]string, enemyShip []int, maxTurns int) bool {
won := false
for i := 0; i < maxTurns; i++ {
printBoard(board)
guess := [2]int{0, 0}
// Get our guess
fmt.Println("Guess the row: ")
fmt.Scanf("%d", &guess[0])
fmt.Println("Guess the column: ")
fmt.Scanf("%d", &guess[1])
fmt.Println()
if guess[0] == enemyShip[0] && guess[1] == enemyShip[1] {
fmt.Println("Congratulations! You sunk my battleship!")
won = true
break
} else {
switch {
case (guess[0] < 0 || guess[0] > (len(board)-1)) || (guess[1] < 0 || guess[1] > (len(board[0])-1)):
fmt.Println("Oops, that's not even in the ocean.")
case board[guess[0]][guess[1]] == "X":
fmt.Println("You guessed that one already.")
default:
fmt.Println("You missed my battleship!")
board[guess[0]][guess[1]] = "X"
}
fmt.Println("Finished turn", (i + 1))
}
}
return won
}
func main() {
board := setupBoard(boardSize)
ship := setupShip(board)
fmt.Println("Let's play Battleship!")
won := playGame(board, ship, maxTurns)
if won {
fmt.Println("Woot!")
} else {
fmt.Println("Sorry... Game over")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment