Skip to content

Instantly share code, notes, and snippets.

@jayzalowitz
Created March 1, 2016 22:53
Show Gist options
  • Save jayzalowitz/9c3c7b9a872f4500eb86 to your computer and use it in GitHub Desktop.
Save jayzalowitz/9c3c7b9a872f4500eb86 to your computer and use it in GitHub Desktop.
A ruby based minesweeper command line game
def minesweeper(size,mines)
@gamestate = "Ongoing"
@size = size
@number_of_squares = size * size
@mines = mines
@mine_grid = []
@count = 0
@clicks = []
@clicks.push()
@size.times do
@mine_grid[@count] = []
@size.times do
@mine_grid[@count].push(0)
end
@count += 1
end
time = @mines
time.times do
while !try_to_fill?
end
end
end
def try_to_fill?
x = rand(@size)
y = rand(@size)
if !@mine_grid[x][y].is_a?(String)
@mine_grid[x][y] = "M"
increment_nearby(x,y)
return true
else
return false
end
end
def increment_nearby(x,y)
max_size = @size -1
min_x = [x-1,0].max
min_y = [y-1,0].max
max_x = [x+1,max_size].min
max_y = [y+1,max_size].min
(min_x..max_x).each do |x_index|
(min_y..max_y).each do |y_index|
if @mine_grid[x_index][y_index] != "M"
@mine_grid[x_index][y_index] = @mine_grid[x_index][y_index].to_i + 1
end
end
end
end
def cascade_nearby(x,y)
if !@clicks.include?([x,y])
@clicks.push([x,y])
end
max_size = @size -1
min_x = [x-1,0].max
min_y = [y-1,0].max
max_x = [x+1,max_size].min
max_y = [y+1,max_size].min
(min_x..max_x).each do |x_index|
(min_y..max_y).each do |y_index|
if (@mine_grid[x_index][y_index] != "M") && !@clicks.include?([x_index,y_index])
if @mine_grid[x_index][y_index] == 0
cascade_nearby(x_index,y_index)
else
@clicks.push([x_index,y_index])
end
end
end
end
end
def show_grid
@mine_grid.each_with_index do |yrow,xindex|
counter = 0
row = []
@mine_grid[xindex].each_with_index do |xrow,yindex|
if @clicks.include?([xindex,yindex])
row.push(@mine_grid[xindex][yindex])
else
row.push(".")
end
end
puts row.join(" ")
end
#ap @clicks
end
def prompt_user
puts "please pick another coordinate, comma delimited"
end
def check_square(x,y)
if @mine_grid[x][y] != "M"
click_square(x,y)
else
@gamestate = "Boom"
end
end
def click_square(x,y)
@clicks.push([x,y])
cascade_nearby(x,y)
if @clicks.length == (@number_of_squares - @mines)
@gamestate = "Victory"
end
end
minesweeper(10,10)
while @gamestate == "Ongoing"
show_grid
prompt_user
input = gets
x,y = input.split(",")
x = x.to_i
y = y.to_i
if !@clicks.include?([x,y])
check_square(x,y)
end
end
puts "Game Over: #{@gamestate}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment