Skip to content

Instantly share code, notes, and snippets.

@lourintp
Created February 16, 2023 20:37
Show Gist options
  • Select an option

  • Save lourintp/593ec9df3a378047ddf74a41dff1505e to your computer and use it in GitHub Desktop.

Select an option

Save lourintp/593ec9df3a378047ddf74a41dff1505e to your computer and use it in GitHub Desktop.
Minesweeper Game
// Define the size of the board
let row = 8
let column = 8
// Define the number of mines
let numberOfMines = 10
// Create an 2D array to represent the board
var board = [[Int]](repeating: [Int](repeating: 0, count: 8), count: 8)
// Create array to represent the fog status
var discovered = [[Bool]](repeating: [Bool](repeating: false, count: 8), count: 8)
// Prints the board without fog
func printUnfoggedBoard() -> Void {
// Print the board
for i in 0..<row {
for j in 0..<column {
if board[i][j] == -1 {
print("*", terminator: " ")
} else {
print(board[i][j], terminator: " ")
}
}
print("")
}
}
// Prints the board with fog
func printFoggedBoard() {
for i in 0..<row {
for j in 0..<column {
if !discovered[i][j] {
print("#", terminator: " ")
} else {
print(board[i][j], terminator: " ")
}
}
print("")
}
}
// Reveals a cell (to be implemented)
func reveal(x: Int, y: Int) -> Void {
// cell is out of board or already revealed
if x < 0 || x >= row || y < 0 || y >= column || discovered[x][y] {
return
}
discovered[x][y] = true // fog was dispelled
if board[x][y] == -1 {
print("Boom! You lost!\n")
return
}
if board[x][y] == 0 { // I assume `being empty` means equals zero
for i in x-1...x+1 {
for j in y-1...y+1 {
reveal(x: i, y: j)
}
}
}
var fogged = 0
for i in 0..<row {
for j in 0..<column {
if !discovered[i][j] {
fogged += 1
}
}
}
if fogged == 0 { // Every cell was unfogged and you're not dead
print("You win!")
return
}
}
// I changed this mechanism because in some cases the mines were being added in positions that already had one
private func placeMines() {
// Place mines randomly on the board
var count = 0
var mines = Set<Int>()
let spots = row * column
if spots <= numberOfMines {
print("Woops... You can't add so many mines!")
}
while count < numberOfMines {
let randomIndex = Int.random(in: 0..<board.count * board[0].count)
if mines.contains(randomIndex) {
continue
}
mines.insert(randomIndex)
let row = randomIndex / board[0].count
let column = randomIndex % board[0].count
board[row][column] = -1
count += 1
}
}
private func calculateNumberOfMines() {
// Calculate the number of mines in each cell's surrounding
for i in 0..<row {
for j in 0..<column {
if board[i][j] == -1 {
continue
}
var count = 0
for x in i-1...i+1 {
for y in j-1...j+1 {
if x >= 0 && x < row && y >= 0 && y < column && board[x][y] == -1 {
count += 1
}
}
}
board[i][j] = count
}
}
}
placeMines()
calculateNumberOfMines()
printUnfoggedBoard()
printFoggedBoard()
reveal(x: 1, y: 1)
printFoggedBoard()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment