Last active
August 29, 2015 14:21
-
-
Save avdept/45c5379fadcfe6820597 to your computer and use it in GitHub Desktop.
console minesweeper in go lang
This file contains hidden or 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
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
"strconv" | |
) | |
func main(){ | |
fmt.Println("hello") | |
game_ended := false | |
rand.Seed( time.Now().UTC().UnixNano()) | |
var row, col, mines int | |
fmt.Print("enter rows cols and mines: ") | |
fmt.Scan(&row, &col, &mines) | |
ui_field := make([][]string, row) | |
for i := range ui_field { | |
ui_field[i] = make([]string, col) | |
} | |
for i := 0; i < row; i++ { | |
for j := 0; j < col; j++ { | |
ui_field[i][j] = "x" | |
} | |
} // field visible to user | |
ary := make([][]int, row) | |
for i := range ary { | |
ary[i] = make([]int, col) | |
} //field with real data | |
total_mines := 0 | |
//filling field with mines. Mines marked with -1 | |
for i := 0; i < row; i++ { | |
for j := 0; j < col; j++ { | |
if total_mines < mines { | |
x,y := rand.Intn(row), rand.Intn(col) | |
if ary[x][y] != -1{ | |
ary[x][y] = -1 | |
total_mines ++ | |
} | |
} | |
} | |
} | |
//this probably needs to be refactored, but have no idea how | |
for i := 0; i < row; i++ { | |
for j := 0; j < col; j++ { | |
if ary[i][j] == -1 { | |
for k := max(0, i - 1); k <= min(row - 1, i + 1); k++ { | |
for l := max(0, j - 1); l <= min(col - 1, j + 1); l++ { | |
if ary[k][l] != -1 { | |
ary[k][l] ++ | |
} | |
} | |
} | |
} | |
} | |
} | |
x, y := 0, 0 | |
for (game_ended == false) { | |
fmt.Println("enter coordinates for next open") | |
fmt.Scan(&x, &y) | |
if x > row || y > col { | |
fmt.Println("Entered coordinates not in range of field, try again") | |
continue | |
} | |
if ary[x][y] != -1 { | |
ui_field[x][y] = strconv.Itoa(ary[x][y]) | |
for _, i := range ui_field { | |
fmt.Println(i); | |
} | |
} else { | |
fmt.Println("you have exploded") | |
game_ended = true | |
for _, i := range ary { | |
fmt.Println(i); | |
} | |
} | |
} | |
} | |
func max(x, y int) int { | |
if x > y { | |
return x | |
} | |
return y | |
} | |
func min(x, y int) int { | |
if x < y { | |
return x | |
} | |
return y | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment