Minor fixes

This commit is contained in:
2025-06-21 23:02:16 +03:00
parent 0965631664
commit dec67e94cb
2 changed files with 42 additions and 19 deletions

View File

@@ -2,14 +2,15 @@ require "xxhash"
# Game logic main class
class GameLogic
def initialize(player)
attr_reader :pos
def initialize
@seed = rand(111_111..999_999)
@pos = {
board: {},
lost: {},
cache: {},
}
@player = player
end
# Returns a pseudorandom number between 0 and 100
@@ -25,7 +26,18 @@ class GameLogic
return if clickable?(g_x, g_y)
case button
when "left"
reveal(g_x, g_y)
if revealed?(g_x, g_y)
if count(:mines, g_x, g_y) == count(:flags, g_x, g_y)
(-1..1).each do |x|
(-1..1).each do |y|
next if x.zero? && y.zero?
reveal(g_x + x, g_y + y)
end
end
end
else
reveal(g_x, g_y)
end
when "right"
flag(g_x, g_y)
end
@@ -35,9 +47,7 @@ class GameLogic
s_x = (g_x / 9).floor
s_y = (g_y / 9).floor
if @pos.lost["#{s_x}:#{s_y}"] ||
@pos.board.key?("#{s_x}:#{s_y}") ||
@pos.board["#{s_x}:#{s_y}"] == true ||
revealed?(g_x, g_y)
@pos.board.key?("#{s_x}:#{s_y}")
return false
end
(-1..1).each do |x|
@@ -58,6 +68,16 @@ class GameLogic
@pos.board["#{s_x}:#{s_y}"][l_x][l_y][1]
end
def flagged?(g_x, g_y)
l_x = ((g_x % 9) + 9) % 9
l_y = ((g_y % 9) + 9) % 9
s_x = (g_x / 9).floor
s_y = (g_y / 9).floor
return false if @pos.board.key?("#{s_x}:#{s_y}")
return true if @pos.board["#{s_x}:#{s_y}"] == true && mine?(g_x, g_y)
@pos.board["#{s_x}:#{s_y}"][l_x][l_y][2]
end
def reveal(g_x, g_y)
l_x = ((g_x % 9) + 9) % 9
l_y = ((g_y % 9) + 9) % 9
@@ -89,7 +109,7 @@ class GameLogic
l_y = ((g_y % 9) + 9) % 9
s_x = (g_x / 9).floor
s_y = (g_y / 9).floor
return if @pos.board["#{s_x}:#{s_y}"] == true
return if @pos.board["#{s_x}:#{s_y}"] == true || revealed?(g_x, g_y)
build_sector(s_x, s_y) if @pos.board["#{s_x}:#{s_y}"].nil?
@pos.board["#{s_x}:#{s_y}"][l_x][l_y][2] ^= true
end
@@ -103,12 +123,16 @@ class GameLogic
true
end
def count(g_x, g_y)
def count(type, g_x, g_y)
sum = 0
(-1..1).each do |x|
(-1..1).each do |y|
next if x.zero? && y.zero?
sum += 1 if mine?(g_x + x, g_y + y)
sum += 1 if case type
when :mines then mine?(g_x + x, g_y + y)
when :flags then flagged?(g_x + x, g_y + y)
else false
end
end
end
sum
@@ -122,7 +146,7 @@ class GameLogic
g_x = l_x + s_x * 9
g_y = l_y + s_y * 9
@pos.board["#{s_x}:#{s_y}"][l_x][l_y] = [
mine?(g_x, g_y) ? -1 : count(g_x, g_y),
mine?(g_x, g_y) ? -1 : count(:mines, g_x, g_y),
false, false,
]
end
@@ -139,7 +163,7 @@ class GameLogic
g_x = l_x + s_x * 9
g_y = l_y + s_y * 9
@pos.cache["#{s_x}:#{s_y}"][l_x][l_y] =
mine?(g_x, g_y) ? [-1, false, true] : [count(g_x, g_y), true, false]
mine?(g_x, g_y) ? [-1, false, true] : [count(:mines, g_x, g_y), true, false]
end
end
end