<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Go &#8211; Blog of Kliment Andreev &#8211; A place so I won&#039;t forget things</title>
	<atom:link href="https://blog.andreev.it/tag/go/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.andreev.it</link>
	<description></description>
	<lastBuildDate>Sat, 31 Oct 2020 14:36:49 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>Programming: Go or Golang &#8211; Battleship game</title>
		<link>https://blog.andreev.it/2018/07/133-go-lang-battleship-game/</link>
					<comments>https://blog.andreev.it/2018/07/133-go-lang-battleship-game/#respond</comments>
		
		<dc:creator><![CDATA[Kliment Andreev]]></dc:creator>
		<pubDate>Sun, 29 Jul 2018 20:48:48 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[battleship]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[Go]]></category>
		<guid isPermaLink="false">http://blog.iandreev.com/?p=3971</guid>

					<description><![CDATA[I&#8217;ve decided to play with the Go or Golang language and what better way&#8230;]]></description>
										<content:encoded><![CDATA[<div id="bsf_rt_marker"></div><p>I&#8217;ve decided to play with the Go or Golang language and what better way to learn than to give yourself a small task and see if you can make it. So, I&#8217;ve made a small variant of the Battleship game. It&#8217;s my first project in Go and it can be much better optimized, but hey, it&#8217;s my first try. Save the source as <strong>battleship.go</strong> and start with go <strong>run battleship.go</strong>. Looks like this in a Linux terminal.<br />
<a href="https://blog.andreev.it/wp-content/uploads/2018/07/P110-01.png"><img fetchpriority="high" decoding="async" src="https://blog.andreev.it/wp-content/uploads/2018/07/P110-01.png" alt="" width="295" height="439" class="aligncenter size-full wp-image-8248" /></a></p>
<pre class="brush: cpp; collapse: true; light: false; title: ; toolbar: true; notranslate">
//--------------------------------
// Battleship - K.Andreev 20182907
// BSD 2.0 License
// https://blog.andreev.it
//--------------------------------
package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;math/rand&quot;
	&quot;os&quot;
	&quot;strings&quot;
	&quot;time&quot;
)

//Size of the board 10 x 10
var intBoardSize = 10

//Total number of ships on each side
var intTotalShips = 15

//Player's name
var sYourName = &quot;&quot;

//Holder for &quot;press any key&quot;
var sAnyKey = &quot;&quot;

//Number of player's turns
var intPlayerTurns = 0

//Number of computer's turns
var intComputerTurns = 0

//Who plays first
var bPlayerFirst = true

//How many ships left for the player
var intPlayerShipsLeft = 15

//How many ships left for the computer
var intComputerShipsLeft = 15

//Define a two dimensional array for the player
var arrPlayerBoard &#x5B;10]&#x5B;10]int

//Define a two dimension array for the computer
var arrComputerBoard &#x5B;10]&#x5B;10]int

//Define Unicode elements for on-screen presentation
//If there are any issues with the display, change them here
//const emptyElement = &quot;\u25a2&quot;     //replace with &quot; &quot;
//const shipElement = &quot;\u25a3&quot;      //replace with &quot;X&quot;
//const shipWreckElement = &quot;\u25a4&quot; //replace with &quot;+&quot;
//const missedElement = &quot;\u25a9&quot;    //replace with &quot;o&quot;
const emptyElement = &quot; &quot;     
const shipElement = &quot;X&quot;      
const shipWreckElement = &quot;+&quot; 
const missedElement = &quot;o&quot;    

func main() {
	//Initialize the random generator
	rand.Seed(time.Now().UnixNano())
	//Print the initial greetings and instructions
	printInstructions()
	//Initialize the boards
	initBoard()
	//Get player's name
	inputYourName()
	//Print the boards
	printBoard()
	//Get the player's ships (coordinates)
	inputFleet()
	//Generate computer's fleet
	generateComputerFleet()
	//Print the boards
	printBoard()
	//Who plays first
	decideFirstPlayer()
	//MAIN GAME LOOP
	for {
		if bPlayerFirst {
			playerMove()
			computerMove()
		} else {
			computerMove()
			playerMove()
		}
	}
}

//Print's game instructions
func printInstructions() {
	fmt.Println(&quot;				==========&quot;)
	fmt.Println(&quot;				Battleship&quot;)
	fmt.Println(&quot;				==========&quot;)
	fmt.Println(&quot;&quot;)
	fmt.Println(&quot;The goal of this game is to sink all of the enemy's ships on the&quot;, intBoardSize, &quot;X&quot;, intBoardSize, &quot;board.&quot;)
	fmt.Println(&quot;You do that by guessing ship's location using coordinates (e.g. LAUNCH AT&gt; C3).&quot;)
	fmt.Println(&quot;If you or the computer hit a ship, another chance is given until you miss again.&quot;)
	fmt.Println(&quot;The game is over when you or the opponent sinks all&quot;, intTotalShips, &quot;ships.&quot;)
	fmt.Println(&quot;&quot;)
	fmt.Println(&quot;To make the game more difficult, you won't see where you missed on the computer board&quot;)
	fmt.Println(&quot;...and the computer won't hit the same place twice. HAVE FUN!!!&quot;)
	fmt.Println(&quot;&quot;)
	fmt.Println(&quot;K.Andreev - 20180729 - BSD Simplified License&quot;)
}

//Initialized both boards with zero values
//Sets the number of ships
func initBoard() {
	i := 0
	j := 0
	intPlayerShipsLeft = 15
	intComputerShipsLeft = 15
	intPlayerTurns = 0
	intComputerTurns = 0
	for i = 0; i &lt; intBoardSize; i++ {
		for j = 0; j &lt; intBoardSize; j++ {
			arrPlayerBoard&#x5B;i]&#x5B;j] = 0
			arrComputerBoard&#x5B;i]&#x5B;j] = 0
		}
	}
}

//Gets player's name
func inputYourName() {
	fmt.Println(&quot;&quot;)
	fmt.Print(&quot;Enter your name: &quot;)
	fmt.Scanln(&amp;sYourName)
	fmt.Println(&quot;&quot;)
	fmt.Println(&quot;Hello,&quot;, sYourName, &quot;!&quot;)
	fmt.Println(&quot;&quot;)
	fmt.Println(&quot;Please place your fleet using coordinates (e.g. D5)&quot;)
	fmt.Println(&quot;If you make a mistake, re-enter the same coordinate.&quot;)
	fmt.Println(&quot;&quot;)
	pressAnyKey()
}

//Ask the player to enter the coordinates of the fleet
func inputFleet() {
	intShipCounter := 0
	intXCoord := 0
	intYCoord := 0
	sPosition := &quot;&quot;
	fmt.Println(&quot;&quot;)
	for {
	enter:
		fmt.Print(&quot;SHIP AT&gt; &quot;)
		fmt.Scan(&amp;sPosition)
		//If the length is different than two, coordinate is wrong
		if len(sPosition) != 2 {
			fmt.Println(&quot;INVALID POSITION.&quot;)
			goto enter
		}
		//Convert the coordiantes in array position, e.g. A0 is (0,0), J9 is (9,9)
		sPosition = strings.ToUpper(sPosition)
		intXCoord = int(sPosition&#x5B;0] - 65)
		intYCoord = int(sPosition&#x5B;1] - 48)
		//If the array coordinate is not in &#x5B;(0,0)..(9,9)] range, coordinate is wrong
		if intXCoord &lt; 0 || intXCoord &gt; 9 {
			fmt.Println(&quot;INVALID POSITION.&quot;)
			goto enter
		}
		//If the player already entered a ship at a coordinate, toggle it, make it empty
		if arrPlayerBoard&#x5B;intXCoord]&#x5B;intYCoord] == 1 {
			arrPlayerBoard&#x5B;intXCoord]&#x5B;intYCoord] = 0
		} else {
			arrPlayerBoard&#x5B;intXCoord]&#x5B;intYCoord] = 1
			intShipCounter = intShipCounter + 1
		}
		printBoard()
		//Exit when all 15 ships are placed
		if intShipCounter == 15 {
			break
		}
	}
}

//Prints the boards on the screen
func printBoard() {
	fmt.Println(sYourName)
	i := 0
	j := 0
	intPlayerShipCounter := 0
	intComputerShipCounter := 0
	sChar := 'A'
	fmt.Println(&quot; 0123456789&quot;)
	//Prints player's board
	for i = 0; i &lt; intBoardSize; i++ {
		fmt.Print(string(sChar))
		sChar = sChar + 1
		for j = 0; j &lt; intBoardSize; j++ {
			switch arrPlayerBoard&#x5B;i]&#x5B;j] {
			case 0:
				fmt.Print(emptyElement)
			case 1:
				fmt.Print(shipElement)
				intPlayerShipCounter = intPlayerShipCounter + 1
			case 2:
				fmt.Print(shipWreckElement)
			case 3:
				fmt.Print(missedElement)
			}
		}
		fmt.Println(&quot;&quot;)
	}
	//Prints player's ships left and the total
	fmt.Println(&quot;SHIPS&quot;, intPlayerShipCounter, &quot;/&quot;, intTotalShips)
	fmt.Println(&quot;&quot;)
	//Prints computer's board
	fmt.Println(&quot;COMPUTER&quot;)
	i = 0
	j = 0
	sChar = 'A'
	fmt.Println(&quot; 0123456789&quot;)
	for i = 0; i &lt; intBoardSize; i++ {
		fmt.Print(string(sChar))
		sChar = sChar + 1
		for j = 0; j &lt; intBoardSize; j++ {
			switch arrComputerBoard&#x5B;i]&#x5B;j] {
			case 0:
				fmt.Print(emptyElement)
			case 1:
				//Uncomment the line below to see computer's ships (cheat)
				//fmt.Print(shipElement)
				intComputerShipCounter = intComputerShipCounter + 1
			case 2:
				fmt.Print(shipWreckElement)
			case 3:
				fmt.Print(missedElement)
			}
		}
		fmt.Println(&quot;&quot;)
	}
	//Prints computer's ships left and the total
	fmt.Println(&quot;SHIPS&quot;, intComputerShipCounter, &quot;/&quot;, intTotalShips)
}

//Places computer's fleet using random generator
func generateComputerFleet() {
	intShipCounter := 0
	intRandomShipatX := 0
	intRandomShipatY := 0
	for {
		intRandomShipatX = rand.Intn(10)
		intRandomShipatY = rand.Intn(10)
		if arrComputerBoard&#x5B;intRandomShipatX]&#x5B;intRandomShipatY] == 0 {
			arrComputerBoard&#x5B;intRandomShipatX]&#x5B;intRandomShipatY] = 1
			intShipCounter = intShipCounter + 1
		}
		if intShipCounter == 15 {
			break
		}
	}
}

//Who plays first. A number between 0 and 99 is drawn for both players.
//The bigger number plays first.
func decideFirstPlayer() {
	intPlayerFirst := 0
	intComputerFirst := 0
	fmt.Println(&quot;&quot;)
	fmt.Println(&quot;Prepare for the battle...&quot;)
	intPlayerFirst = rand.Intn(100)
	intComputerFirst = rand.Intn(100)
	if intPlayerFirst &gt;= intComputerFirst {
		bPlayerFirst = true
		fmt.Println(&quot;You play first. Random numbers say&quot;, intPlayerFirst, &quot;vs.&quot;, intComputerFirst)
		fmt.Scanln(&amp;sAnyKey)
		pressAnyKey()
	} else {
		bPlayerFirst = false
		fmt.Println(&quot;Computer plays first. Random numbers say&quot;, intComputerFirst, &quot;vs.&quot;, intPlayerFirst)
		fmt.Scanln(&amp;sAnyKey)
		pressAnyKey()
	}
}

//Get the player to input a coordinate
func playerMove() {
	intXCoord := 0
	intYCoord := 0
	sPosition := &quot;&quot;
	fmt.Println(&quot;&quot;)
enter:
	for {
		fmt.Print(&quot;LAUNCH AT&gt; &quot;)
		fmt.Scan(&amp;sPosition)
		//Same checks for invalid position
		if len(sPosition) != 2 {
			fmt.Println(&quot;INVALID POSITION.&quot;)
			goto enter
		}
		sPosition = strings.ToUpper(sPosition)
		intXCoord = int(sPosition&#x5B;0] - 65)
		intYCoord = int(sPosition&#x5B;1] - 48)
		if intXCoord &lt; 0 || intXCoord &gt; 9 {
			fmt.Println(&quot;INVALID POSITION.&quot;)
			goto enter
		}
		//Increase the turns number
		intPlayerTurns = intPlayerTurns + 1
		//This is a miss if the board has 0 value at the coordinate
		if arrComputerBoard&#x5B;intXCoord]&#x5B;intYCoord] == 0 {
			fmt.Print(&quot;You missed at &quot;, sPosition, &quot;.&quot;)
			fmt.Scanln(&amp;sAnyKey)
			pressAnyKey()
		} else {
			//This is a hit
			arrComputerBoard&#x5B;intXCoord]&#x5B;intYCoord] = 2
			fmt.Print(&quot;YOU HIT A SHIP AT &quot;, sPosition, &quot;.&quot;)
			fmt.Scanln(&amp;sAnyKey)
			pressAnyKey()
			printBoard()
			intComputerShipsLeft = intComputerShipsLeft - 1
			//Game over if all ships are hit
			if intComputerShipsLeft == 0 {
				fmt.Println(&quot;================&quot;)
				fmt.Println(&quot;&#x5B;   YOU WON    ]&quot;)
				fmt.Println(&quot;================&quot;)
				fmt.Println(intPlayerTurns, &quot;turns to complete the game...&quot;)
				os.Exit(0)
			}
			goto enter
		}
		printBoard()
		break
	}
}

//Computer logic for the play
func computerMove() {
	intRandomShipatX := 0
	intRandomShipatY := 0
enter:
	for {
		//Get a random coordinate
		intRandomShipatX = rand.Intn(10)
		intRandomShipatY = rand.Intn(10)
		//Increase the number of turns
		intComputerTurns = intComputerTurns + 1
		//If it's a miss, remember that position by placing &quot;3&quot; and never hit that position again
		if arrPlayerBoard&#x5B;intRandomShipatX]&#x5B;intRandomShipatY] == 0 {
			arrPlayerBoard&#x5B;intRandomShipatX]&#x5B;intRandomShipatY] = 3
			fmt.Println(&quot;Computer missed at&quot;, string(intRandomShipatX+65), string(intRandomShipatY+48))
			pressAnyKey()
			printBoard()
			break
		}
		//If it's a hit, mark the ship as hit by placing &quot;2&quot;
		if arrPlayerBoard&#x5B;intRandomShipatX]&#x5B;intRandomShipatY] == 1 {
			arrPlayerBoard&#x5B;intRandomShipatX]&#x5B;intRandomShipatY] = 2
			fmt.Println(&quot;COMPUTER HIT A SHIP at&quot;, string(intRandomShipatX+65), string(intRandomShipatY+48))
			pressAnyKey()
			printBoard()
			intPlayerShipsLeft = intPlayerShipsLeft - 1
			if intPlayerShipsLeft == 0 {
				fmt.Println(&quot;================&quot;)
				fmt.Println(&quot;&#x5B; COMPUTER WON ]&quot;)
				fmt.Println(&quot;================&quot;)
				fmt.Println(intComputerTurns, &quot;turns to complete the game...&quot;)
				os.Exit(0)
			} else {
				goto enter
			}
		}
		//If the random coordinate is where the ship was already hit, go guess again
		if arrPlayerBoard&#x5B;intRandomShipatX]&#x5B;intRandomShipatY] == 2 {
			goto enter
		}
		//If the random coordinate is where we missed, go guess again
		if arrPlayerBoard&#x5B;intRandomShipatX]&#x5B;intRandomShipatY] == 3 {
			goto enter
		}
	}
}

//Wait for any key to be pressed
func pressAnyKey() {
	in := bufio.NewReader(os.Stdin)
	line, _ := in.ReadString('\n')
	_ = line
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.andreev.it/2018/07/133-go-lang-battleship-game/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
