├── screenshots ├── minesweeper1.png ├── minesweeper2.png ├── minesweeper3.png └── minesweeper4.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── src ├── main │ └── kotlin │ │ └── minesweeper │ │ ├── Difficulty.kt │ │ ├── HighScore.kt │ │ ├── GameViewModel.kt │ │ ├── Board.kt │ │ └── Main.kt └── test │ └── kotlin │ └── minesweeper │ └── BoardTest.kt ├── high_scores.json ├── README.md ├── gradlew.bat ├── minesweeper-rules.md └── gradlew /screenshots/minesweeper1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonarhipov/minesweeper-with-compose/HEAD/screenshots/minesweeper1.png -------------------------------------------------------------------------------- /screenshots/minesweeper2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonarhipov/minesweeper-with-compose/HEAD/screenshots/minesweeper2.png -------------------------------------------------------------------------------- /screenshots/minesweeper3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonarhipov/minesweeper-with-compose/HEAD/screenshots/minesweeper3.png -------------------------------------------------------------------------------- /screenshots/minesweeper4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonarhipov/minesweeper-with-compose/HEAD/screenshots/minesweeper4.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/antonarhipov/minesweeper-with-compose/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | .vscode 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### IntelliJ IDEA ### 9 | .idea 10 | *.iws 11 | *.iml 12 | *.ipr 13 | out/ 14 | !**/src/main/**/out/ 15 | !**/src/test/**/out/ 16 | 17 | ### Mac OS ### 18 | .DS_Store 19 | 20 | -------------------------------------------------------------------------------- /src/main/kotlin/minesweeper/Difficulty.kt: -------------------------------------------------------------------------------- 1 | package minesweeper 2 | 3 | import kotlinx.serialization.Serializable 4 | 5 | @Serializable 6 | enum class Difficulty( 7 | val width: Int, 8 | val height: Int, 9 | val mines: Int, 10 | val displayName: String 11 | ) { 12 | EASY(9, 9, 10, "Easy"), // 12.35% density 13 | MEDIUM(10, 10, 15, "Medium"), // 15% density 14 | HARD(11, 11, 20, "Hard") // 16.53% density 15 | } 16 | -------------------------------------------------------------------------------- /high_scores.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "Anton", 4 | "timeInSeconds": 22, 5 | "difficulty": "EASY" 6 | }, 7 | { 8 | "name": "Anton", 9 | "timeInSeconds": 35, 10 | "difficulty": "EASY" 11 | }, 12 | { 13 | "name": "Anton", 14 | "timeInSeconds": 42, 15 | "difficulty": "EASY" 16 | }, 17 | { 18 | "name": "Anton", 19 | "timeInSeconds": 46, 20 | "difficulty": "EASY" 21 | }, 22 | { 23 | "name": "Anton", 24 | "timeInSeconds": 55, 25 | "difficulty": "MEDIUM" 26 | }, 27 | { 28 | "name": "Anton", 29 | "timeInSeconds": 66, 30 | "difficulty": "MEDIUM" 31 | } 32 | ] -------------------------------------------------------------------------------- /src/main/kotlin/minesweeper/HighScore.kt: -------------------------------------------------------------------------------- 1 | package minesweeper 2 | 3 | import kotlinx.serialization.Serializable 4 | import kotlinx.serialization.encodeToString 5 | import kotlinx.serialization.json.Json 6 | import java.io.File 7 | 8 | @Serializable 9 | data class HighScore( 10 | val name: String, 11 | val timeInSeconds: Int, 12 | val difficulty: Difficulty 13 | ) 14 | 15 | class HighScoreManager { 16 | private val scoresFile = File("high_scores.json") 17 | private val json = Json { prettyPrint = true } 18 | 19 | fun getTopScores(difficulty: Difficulty, limit: Int = 10): List { 20 | if (!scoresFile.exists()) return emptyList() 21 | 22 | return try { 23 | val scores = json.decodeFromString>(scoresFile.readText()) 24 | scores.filter { it.difficulty == difficulty } 25 | .sortedBy { it.timeInSeconds } 26 | .take(limit) 27 | } catch (_: Exception) { 28 | emptyList() 29 | } 30 | } 31 | 32 | fun addScore(score: HighScore) { 33 | val currentScores = if (scoresFile.exists()) { 34 | try { 35 | json.decodeFromString>(scoresFile.readText()) 36 | } catch (_: Exception) { 37 | emptyList() 38 | } 39 | } else { 40 | emptyList() 41 | } 42 | 43 | val newScores = (currentScores + score) 44 | .groupBy { it.difficulty } 45 | .flatMap { (_, scores) -> 46 | scores.sortedBy { it.timeInSeconds }.take(10) 47 | } 48 | 49 | scoresFile.writeText(json.encodeToString(newScores)) 50 | } 51 | 52 | fun wouldBeTopScore(timeInSeconds: Int, difficulty: Difficulty): Int? { 53 | val topScores = getTopScores(difficulty) 54 | if (topScores.size < 10) return topScores.size 55 | 56 | return topScores.indexOfFirst { it.timeInSeconds > timeInSeconds } 57 | .takeIf { it >= 0 } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/test/kotlin/minesweeper/BoardTest.kt: -------------------------------------------------------------------------------- 1 | package minesweeper 2 | 3 | import org.junit.jupiter.api.Test 4 | import org.assertj.core.api.Assertions.assertThat 5 | import org.junit.jupiter.api.assertThrows 6 | 7 | class BoardTest { 8 | 9 | @Test 10 | fun `board initialization with valid parameters creates correct size board`() { 11 | val board = Board(width = 9, height = 9, mineCount = 10) 12 | 13 | assertThat(board.width).isEqualTo(9) 14 | assertThat(board.height).isEqualTo(9) 15 | assertThat(board.mineCount).isEqualTo(10) 16 | assertThat(board.grid.size).isEqualTo(9) 17 | assertThat(board.grid[0].size).isEqualTo(9) 18 | } 19 | 20 | @Test 21 | fun `board initialization places correct number of mines`() { 22 | val board = Board(width = 9, height = 9, mineCount = 10) 23 | 24 | val mineCount = board.grid.sumOf { row -> 25 | row.count { it.hasMine } 26 | } 27 | 28 | assertThat(mineCount).isEqualTo(10) 29 | } 30 | 31 | @Test 32 | fun `board initialization with invalid mine count throws exception`() { 33 | assertThrows { 34 | Board(width = 9, height = 9, mineCount = 82) // More mines than cells 35 | } 36 | 37 | assertThrows { 38 | Board(width = 9, height = 9, mineCount = -1) 39 | } 40 | } 41 | 42 | @Test 43 | fun `board initialization calculates adjacent mine counts correctly`() { 44 | val board = Board(width = 3, height = 3, mineCount = 1) 45 | // Force mine placement for testing 46 | board.setMineForTesting(1, 1) 47 | 48 | // Check all surrounding cells have adjacentMines = 1 49 | for (x in 0..2) { 50 | for (y in 0..2) { 51 | if (x == 1 && y == 1) continue // Skip the mine cell 52 | assertThat(board.grid[x][y].adjacentMines).isEqualTo(1) 53 | } 54 | } 55 | } 56 | 57 | @Test 58 | fun `cell revelation updates cell state`() { 59 | val board = Board(width = 3, height = 3, mineCount = 0) 60 | 61 | board.revealCell(1, 1) 62 | 63 | assertThat(board.grid[1][1].state).isEqualTo(CellState.REVEALED) 64 | } 65 | 66 | @Test 67 | fun `revealing mine cell results in game over`() { 68 | val board = Board(width = 3, height = 3, mineCount = 1) 69 | board.setMineForTesting(1, 1) 70 | 71 | board.revealCell(1, 1) 72 | 73 | assertThat(board.getGameState()).isEqualTo(GameState.LOST) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Minesweeper 2 | 3 | A modern implementation of the classic Minesweeper game using Kotlin and Compose Desktop. 4 | 5 | ## Features 6 | 7 | - 🎮 Classic Minesweeper gameplay 8 | - 🎯 Three difficulty levels: Beginner, Intermediate, and Expert 9 | - ⏱️ Game timer that starts on first move 10 | - 🏆 High scores system with persistent storage 11 | - 📱 Mobile-friendly vertical layout 12 | - 🖱️ Intuitive controls: 13 | - Left click to reveal cells 14 | - Long press to flag/unflag cells 15 | - Automatic flood fill for empty cells 16 | - 🎨 Modern UI with: 17 | - Hover effects for cells 18 | - Color-coded numbers 19 | - Emoji indicators 20 | - Dynamic cell sizing 21 | - Responsive layout 22 | 23 | ## Screenshots 24 | 25 | Here are some screenshots of the game in action: 26 | 27 | 28 | | ![Minesweeper 1](screenshots/minesweeper1.png) | ![Minesweeper 2](screenshots/minesweeper2.png) | ![Minesweeper 3](screenshots/minesweeper3.png) | ![Minesweeper 4](screenshots/minesweeper4.png) | 29 | |------------------------------------------------|------------------------------------------------|------------------------------------------------|------------------------------------------------| 30 | 31 | 32 | These screenshots showcase the modern UI and gameplay experience. 33 | 34 | 35 | 36 | ### Building 37 | 38 | ```bash 39 | ./gradlew build 40 | ``` 41 | 42 | ### Running 43 | 44 | ```bash 45 | ./gradlew run 46 | ``` 47 | 48 | ## How to Play 49 | 50 | 1. Start the game by clicking any cell 51 | 2. Left click to reveal a cell 52 | 3. Long press to place/remove a flag 53 | 4. Numbers indicate adjacent mines 54 | 5. Flag all mines or reveal all safe cells to win 55 | 6. Beat the timer to get on the high scores list! 56 | 57 | ## Game Rules 58 | 59 | - Each cell can be either empty, contain a mine, or show a number 60 | - Numbers indicate how many mines are in the adjacent cells 61 | - Use these numbers to deduce where mines are located 62 | - Flag cells you believe contain mines 63 | - Reveal all non-mine cells to win 64 | - If you reveal a mine, game over! 65 | 66 | ## High Scores 67 | 68 | - Top 10 scores are saved for each difficulty level 69 | - Scores are based on completion time 70 | - Enter your name when you achieve a high score 71 | - Scores are saved between sessions 72 | - High scores are stored in `high_scores.json` 73 | 74 | ## Technical Details 75 | 76 | ### Built With 77 | 78 | - Kotlin 1.9.20 79 | - Compose Desktop 1.5.11 80 | - Material Design 3 81 | - Kotlinx Serialization 82 | 83 | ### Project Structure 84 | 85 | ``` 86 | src/main/kotlin/minesweeper/ 87 | ├── Main.kt # UI and game rendering 88 | ├── Board.kt # Game logic and state 89 | ├── GameViewModel.kt # Game state management 90 | ├── HighScore.kt # High score handling 91 | └── Difficulty.kt # Game difficulty settings 92 | ``` 93 | 94 | ## License 95 | 96 | This project is open source and available under the MIT License. 97 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /minesweeper-rules.md: -------------------------------------------------------------------------------- 1 | # Minesweeper Implementation Guide 2 | 3 | This document outlines the step-by-step implementation plan for creating a Minesweeper game in Kotlin. 4 | 5 | ## Step 1: Data Structure Design 6 | 7 | ### Cell State Enumeration 8 | ```kotlin 9 | enum class CellState { 10 | HIDDEN, // Initial state of cell 11 | REVEALED, // Cell has been clicked and revealed 12 | FLAGGED // Cell has been flagged as potential mine 13 | } 14 | ``` 15 | 16 | ### Cell Data Structure 17 | ```kotlin 18 | data class Cell( 19 | val hasMine: Boolean, // Whether cell contains a mine 20 | val state: CellState, // Current state of the cell 21 | val adjacentMines: Int // Number of adjacent mines (0-8) 22 | ) 23 | ``` 24 | 25 | ### Game Board Structure 26 | ```kotlin 27 | class Board( 28 | val width: Int, // Board width 29 | val height: Int, // Board height 30 | val mineCount: Int, // Total number of mines 31 | val grid: Array> // 2D array of cells 32 | ) 33 | ``` 34 | 35 | ## Step 2: Board Initialization 36 | 37 | 1. Board Creation: 38 | - Initialize empty grid with specified dimensions 39 | - Randomly distribute mines across the board 40 | - Calculate adjacent mine counts for each cell 41 | 42 | 2. Adjacent Mines Calculation: 43 | - For each non-mine cell, check all 8 surrounding positions 44 | - Count and store the number of adjacent mines 45 | 46 | ## Step 3: Game Logic Implementation 47 | 48 | ### Cell Revelation Logic 49 | - Reveal single cell 50 | - Implement flood fill algorithm for empty cells 51 | - Check for game-over condition 52 | 53 | ### Flagging System 54 | - Toggle flag state on cells 55 | - Track number of placed flags 56 | - Validate against total mine count 57 | 58 | ### Win Condition Verification 59 | - Check if all non-mine cells are revealed 60 | - Alternatively, verify all mines are correctly flagged 61 | 62 | ## Step 4: Game State Management 63 | 64 | ### Game State Enumeration 65 | ```kotlin 66 | enum class GameState { 67 | ONGOING, // Game is in progress 68 | WON, // Player has won 69 | LOST // Player has hit a mine 70 | } 71 | ``` 72 | 73 | ### State Tracking 74 | - Update game state after each move 75 | - Handle game over scenarios 76 | - Special handling for first move 77 | 78 | ## Step 5: Helper Functions 79 | 80 | ### Coordinate Validation 81 | - Verify coordinates are within board boundaries 82 | - Validate move legality 83 | 84 | ### Neighbor Cell Operations 85 | - Get all valid adjacent cells 86 | - Handle edge and corner cases properly 87 | 88 | ## Step 6: Game Actions API 89 | 90 | ### Public Interface 91 | ```kotlin 92 | interface MinesweeperGame { 93 | fun revealCell(x: Int, y: Int): Boolean 94 | fun toggleFlag(x: Int, y: Int): Boolean 95 | fun getGameState(): GameState 96 | fun getCellState(x: Int, y: Int): CellState 97 | } 98 | ``` 99 | 100 | ## Step 7: First Move Safety 101 | 102 | ### First Move Guarantee 103 | - Ensure first revealed cell is safe 104 | - Relocate mine if necessary 105 | - Recalculate adjacent mine counts 106 | 107 | ## Step 8: Board Difficulty Presets 108 | 109 | ### Difficulty Settings 110 | ```kotlin 111 | enum class Difficulty(val width: Int, val height: Int, val mines: Int) { 112 | BEGINNER(9, 9, 10), 113 | INTERMEDIATE(16, 16, 40), 114 | EXPERT(30, 16, 99) 115 | } 116 | ``` 117 | 118 | ## Step 9: Game Reset and State Management 119 | 120 | ### Reset Functionality 121 | - Clear all cells 122 | - Redistribute mines 123 | - Reset game state to initial 124 | 125 | ## Step 10: Utility Functions 126 | 127 | ### Board Representation 128 | - String representation for debugging 129 | - Game state visualization 130 | - Statistics tracking 131 | 132 | ## Implementation Notes 133 | 134 | ### Best Practices 135 | 1. Use pure functions when possible 136 | 2. Implement immutable data structures where appropriate 137 | 3. Include proper error handling 138 | 4. Add comprehensive documentation 139 | 140 | ### Kotlin-Specific Guidelines 141 | 1. Utilize data classes for value objects 142 | 2. Use nullable types appropriately 143 | 3. Implement sealed classes for state management 144 | 4. Follow Kotlin coding conventions 145 | 146 | ### Example Usage 147 | ```kotlin 148 | // Game initialization 149 | val game = MinesweeperGame(Difficulty.BEGINNER) 150 | 151 | // Game actions 152 | game.revealCell(0, 0) // Returns success/failure 153 | game.toggleFlag(1, 1) // Returns success/failure 154 | 155 | // State checking 156 | val state = game.getGameState() // Returns current game state 157 | ``` 158 | -------------------------------------------------------------------------------- /src/main/kotlin/minesweeper/GameViewModel.kt: -------------------------------------------------------------------------------- 1 | package minesweeper 2 | 3 | import androidx.compose.runtime.* 4 | import kotlinx.coroutines.* 5 | import java.util.Timer 6 | import kotlin.concurrent.fixedRateTimer 7 | 8 | class GameViewModel( 9 | difficulty: Difficulty = Difficulty.EASY, 10 | private val highScoreManager: HighScoreManager = HighScoreManager() 11 | ) { 12 | var currentDifficulty by mutableStateOf(difficulty) 13 | private set 14 | 15 | var board by mutableStateOf(Board(difficulty.width, difficulty.height, difficulty.mines)) 16 | private set 17 | 18 | var gameState by mutableStateOf(GameState.ONGOING) 19 | private set 20 | 21 | var remainingFlags by mutableStateOf(difficulty.mines) 22 | private set 23 | 24 | var elapsedSeconds by mutableStateOf(0) 25 | private set 26 | 27 | var showHighScoreDialog by mutableStateOf(false) 28 | private set 29 | 30 | var topScores by mutableStateOf>(emptyList()) 31 | private set 32 | 33 | private var timer: Timer? = null 34 | private var isFirstClick = true 35 | 36 | init { 37 | loadTopScores() 38 | } 39 | 40 | private fun startTimer() { 41 | timer?.cancel() 42 | elapsedSeconds = 0 43 | timer = fixedRateTimer(period = 1000L) { 44 | if (gameState == GameState.ONGOING) { 45 | elapsedSeconds++ 46 | } 47 | } 48 | } 49 | 50 | private fun loadTopScores() { 51 | topScores = highScoreManager.getTopScores(currentDifficulty) 52 | } 53 | 54 | fun changeDifficulty(newDifficulty: Difficulty) { 55 | if (gameState == GameState.ONGOING && !isFirstClick) { 56 | // Don't allow changing difficulty during an active game 57 | return 58 | } 59 | 60 | currentDifficulty = newDifficulty 61 | resetGame() 62 | loadTopScores() 63 | } 64 | 65 | fun onCellClick(x: Int, y: Int) { 66 | if (gameState != GameState.ONGOING) return 67 | 68 | val cell = board.grid[x][y] 69 | if (cell.state == CellState.FLAGGED) return 70 | 71 | if (isFirstClick) { 72 | isFirstClick = false 73 | startTimer() 74 | } 75 | 76 | board.revealCell(x, y) 77 | gameState = board.getGameState() 78 | 79 | if (gameState == GameState.WON) { 80 | timer?.cancel() 81 | val position = highScoreManager.wouldBeTopScore(elapsedSeconds, currentDifficulty) 82 | if (position != null) { 83 | showHighScoreDialog = true 84 | } 85 | } else if (gameState == GameState.LOST) { 86 | timer?.cancel() 87 | } 88 | } 89 | 90 | fun onCellRightClick(x: Int, y: Int) { 91 | if (gameState != GameState.ONGOING) return 92 | 93 | val cell = board.grid[x][y] 94 | if (cell.state == CellState.REVEALED) return 95 | 96 | if (isFirstClick) { 97 | isFirstClick = false 98 | startTimer() 99 | } 100 | 101 | if (cell.state == CellState.HIDDEN && remainingFlags > 0) { 102 | board.toggleFlag(x, y) 103 | remainingFlags-- 104 | } else if (cell.state == CellState.FLAGGED) { 105 | board.toggleFlag(x, y) 106 | remainingFlags++ 107 | } 108 | 109 | gameState = board.getGameState() 110 | if (gameState == GameState.WON) { 111 | timer?.cancel() 112 | val position = highScoreManager.wouldBeTopScore(elapsedSeconds, currentDifficulty) 113 | if (position != null) { 114 | showHighScoreDialog = true 115 | } 116 | } 117 | } 118 | 119 | fun addHighScore(name: String) { 120 | val score = HighScore(name, elapsedSeconds, currentDifficulty) 121 | highScoreManager.addScore(score) 122 | loadTopScores() 123 | showHighScoreDialog = false 124 | } 125 | 126 | fun dismissHighScoreDialog() { 127 | showHighScoreDialog = false 128 | } 129 | 130 | fun resetGame() { 131 | board = Board(currentDifficulty.width, currentDifficulty.height, currentDifficulty.mines) 132 | gameState = GameState.ONGOING 133 | remainingFlags = currentDifficulty.mines 134 | showHighScoreDialog = false 135 | isFirstClick = true 136 | timer?.cancel() 137 | elapsedSeconds = 0 138 | } 139 | 140 | fun formatTime(seconds: Int): String { 141 | val minutes = seconds / 60 142 | val remainingSeconds = seconds % 60 143 | return "%02d:%02d".format(minutes, remainingSeconds) 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/main/kotlin/minesweeper/Board.kt: -------------------------------------------------------------------------------- 1 | package minesweeper 2 | 3 | import androidx.compose.runtime.getValue 4 | import androidx.compose.runtime.mutableStateOf 5 | import androidx.compose.runtime.setValue 6 | import kotlin.random.Random 7 | 8 | enum class CellState { 9 | HIDDEN, 10 | REVEALED, 11 | FLAGGED 12 | } 13 | 14 | enum class GameState { 15 | ONGOING, 16 | WON, 17 | LOST 18 | } 19 | 20 | data class Cell( 21 | val hasMine: Boolean = false, 22 | val state: CellState = CellState.HIDDEN, 23 | val adjacentMines: Int = 0 24 | ) 25 | 26 | class Board( 27 | val width: Int, 28 | val height: Int, 29 | val mineCount: Int 30 | ) { 31 | private var gameState = GameState.ONGOING 32 | private var _grid by mutableStateOf>>(Array(width) { Array(height) { Cell() } }) 33 | val grid: Array> get() = _grid 34 | 35 | init { 36 | require(mineCount >= 0) { "Mine count must be non-negative" } 37 | require(mineCount < width * height) { "Mine count must be less than total number of cells" } 38 | 39 | // Place mines randomly 40 | placeMines() 41 | 42 | // Calculate adjacent mines 43 | calculateAdjacentMines() 44 | } 45 | 46 | private fun placeMines(random: Random = Random) { 47 | val totalCells = width * height 48 | val availablePositions = (0 until totalCells).toMutableList() 49 | var remainingMines = mineCount 50 | 51 | while (remainingMines > 0) { 52 | val position = getRandomPosition(availablePositions, random) 53 | val (x, y) = calculateCoordinates(position) 54 | updateCell(x, y) { it.copy(hasMine = true) } 55 | remainingMines-- 56 | } 57 | } 58 | 59 | private fun getRandomPosition(positions: MutableList, random: Random): Int { 60 | val index = random.nextInt(positions.size) 61 | return positions.removeAt(index) 62 | } 63 | 64 | private fun calculateCoordinates(position: Int): Pair { 65 | val x = position / height 66 | val y = position % height 67 | return Pair(x, y) 68 | } 69 | 70 | private fun calculateAdjacentMines() { 71 | getNonMineCells() 72 | .forEach { (x, y) -> 73 | updateCellAdjacentMines(x, y) 74 | } 75 | } 76 | 77 | private fun getNonMineCells(): Sequence> = sequence { 78 | for (x in 0 until width) { 79 | for (y in 0 until height) { 80 | if (!grid[x][y].hasMine) { 81 | yield(x to y) 82 | } 83 | } 84 | } 85 | } 86 | 87 | private fun updateCellAdjacentMines(x: Int, y: Int) { 88 | val adjacentMinesCount = countAdjacentMines(x, y) 89 | updateCell(x, y) { it.copy(adjacentMines = adjacentMinesCount) } 90 | } 91 | 92 | private fun countAdjacentMines(x: Int, y: Int): Int { 93 | val adjacentOffsets = sequenceOf( 94 | -1 to -1, -1 to 0, -1 to 1, 95 | 0 to -1, 0 to 1, 96 | 1 to -1, 1 to 0, 1 to 1 97 | ) 98 | 99 | return adjacentOffsets 100 | .map { (deltaX, deltaY) -> Coordinate(x + deltaX, y + deltaY) } 101 | .filter { (adjacentX, adjacentY) -> isValidPosition(adjacentX, adjacentY) } 102 | .count { (adjacentX, adjacentY) -> grid[adjacentX][adjacentY].hasMine } 103 | } 104 | 105 | private fun isValidPosition(x: Int, y: Int): Boolean { 106 | return x in 0 until width && y in 0 until height 107 | } 108 | 109 | private fun updateCell(x: Int, y: Int, update: (Cell) -> Cell) { 110 | val newGrid = _grid.map { it.clone() }.toTypedArray() 111 | newGrid[x][y] = update(newGrid[x][y]) 112 | _grid = newGrid 113 | 114 | // Check win condition after every cell update 115 | checkWinCondition() 116 | } 117 | 118 | fun revealCell(x: Int, y: Int): Boolean { 119 | require(isValidPosition(x, y)) { "Invalid position" } 120 | 121 | if (grid[x][y].state != CellState.HIDDEN) return false 122 | 123 | updateCell(x, y) { it.copy(state = CellState.REVEALED) } 124 | 125 | if (grid[x][y].hasMine) { 126 | gameState = GameState.LOST 127 | revealAllMines() 128 | return true 129 | } 130 | 131 | if (grid[x][y].adjacentMines == 0) { 132 | // Reveal adjacent cells (flood fill) 133 | revealAdjacentCells(x, y) 134 | } 135 | 136 | return true 137 | } 138 | 139 | private fun revealAdjacentCells(x: Int, y: Int) { 140 | getAdjacentCoordinates(x, y) 141 | .filter { (newX, newY) -> isValidPosition(newX, newY) } 142 | .filter { (newX, newY) -> grid[newX][newY].state == CellState.HIDDEN } 143 | .forEach { (newX, newY) -> revealCell(newX, newY) } 144 | } 145 | 146 | private fun getAdjacentCoordinates(x: Int, y: Int): Sequence = sequence { 147 | for (dx in -1..1) { 148 | for (dy in -1..1) { 149 | if (dx == 0 && dy == 0) continue 150 | yield(Coordinate(x + dx, y + dy)) 151 | } 152 | } 153 | } 154 | 155 | private fun revealAllMines() { 156 | grid.asSequence() 157 | .flatMapIndexed { x, column -> 158 | column.mapIndexed { y, cell -> 159 | Coordinate(x, y) to cell 160 | } 161 | } 162 | .filter { (_, cell) -> cell.hasMine } 163 | .forEach { (coordinate, _) -> 164 | updateCell(coordinate.x, coordinate.y) { 165 | it.revealed() 166 | } 167 | } 168 | } 169 | 170 | private data class Coordinate(val x: Int, val y: Int) 171 | 172 | private fun Cell.revealed() = copy(state = CellState.REVEALED) 173 | 174 | private fun checkWinCondition() { 175 | // Game is won when: 176 | // 1. All non-mine cells are revealed 177 | // 2. All mine cells are either hidden or flagged 178 | val allNonMinesRevealed = grid.all { row -> 179 | row.all { cell -> 180 | (cell.hasMine && (cell.state == CellState.HIDDEN || cell.state == CellState.FLAGGED)) || 181 | (!cell.hasMine && cell.state == CellState.REVEALED) 182 | } 183 | } 184 | 185 | if (allNonMinesRevealed) { 186 | gameState = GameState.WON 187 | } 188 | } 189 | 190 | fun getGameState(): GameState = gameState 191 | 192 | // Test helper function 193 | internal fun setMineForTesting(x: Int, y: Int) { 194 | // Clear all mines first 195 | for (i in 0 until width) { 196 | for (j in 0 until height) { 197 | updateCell(i, j) { it.copy(hasMine = false, adjacentMines = 0) } 198 | } 199 | } 200 | // Set the specified mine 201 | updateCell(x, y) { it.copy(hasMine = true) } 202 | // Recalculate adjacent mines 203 | calculateAdjacentMines() 204 | } 205 | 206 | fun toggleFlag(x: Int, y: Int) { 207 | require(isValidPosition(x, y)) { "Invalid position" } 208 | val cell = grid[x][y] 209 | 210 | if (cell.state == CellState.REVEALED) return 211 | 212 | updateCell(x, y) { 213 | it.copy(state = if (it.state == CellState.FLAGGED) CellState.HIDDEN else CellState.FLAGGED) 214 | } 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /src/main/kotlin/minesweeper/Main.kt: -------------------------------------------------------------------------------- 1 | package minesweeper 2 | 3 | import androidx.compose.foundation.background 4 | import androidx.compose.foundation.border 5 | import androidx.compose.foundation.layout.* 6 | import androidx.compose.foundation.hoverable 7 | import androidx.compose.foundation.interaction.MutableInteractionSource 8 | import androidx.compose.foundation.interaction.collectIsHoveredAsState 9 | import androidx.compose.material3.* 10 | import androidx.compose.runtime.* 11 | import androidx.compose.ui.Alignment 12 | import androidx.compose.ui.ExperimentalComposeUiApi 13 | import androidx.compose.ui.Modifier 14 | import androidx.compose.ui.graphics.Color 15 | import androidx.compose.ui.input.pointer.* 16 | import androidx.compose.foundation.gestures.detectTapGestures 17 | import androidx.compose.foundation.lazy.LazyColumn 18 | import androidx.compose.foundation.lazy.itemsIndexed 19 | import androidx.compose.ui.text.font.FontWeight 20 | import androidx.compose.ui.unit.dp 21 | import androidx.compose.ui.unit.sp 22 | import androidx.compose.ui.window.Dialog 23 | import androidx.compose.ui.window.Window 24 | import androidx.compose.ui.window.application 25 | import androidx.compose.ui.window.WindowState 26 | import androidx.compose.ui.window.rememberWindowState 27 | 28 | private val UnrevealedCellColor = Color(0xFFBDBDBD) 29 | private val UnrevealedCellBorderColor = Color(0xFF9E9E9E) 30 | private val RevealedCellColor = Color(0xFFE0E0E0) 31 | private val RevealedCellBorderColor = Color(0xFFBDBDBD) 32 | private val HoverCellColor = Color(0xFFCFCFCF) 33 | 34 | @Composable 35 | fun HighScoreDialog( 36 | scores: List, 37 | currentTime: Int, 38 | onDismiss: () -> Unit, 39 | onSubmit: (String) -> Unit 40 | ) { 41 | var playerName by remember { mutableStateOf("") } 42 | 43 | fun formatTime(seconds: Int): String { 44 | val minutes = seconds / 60 45 | val remainingSeconds = seconds % 60 46 | return "%02d:%02d".format(minutes, remainingSeconds) 47 | } 48 | 49 | Dialog(onDismissRequest = onDismiss) { 50 | Surface( 51 | modifier = Modifier.padding(16.dp), 52 | shape = MaterialTheme.shapes.medium, 53 | color = MaterialTheme.colorScheme.surface 54 | ) { 55 | Column( 56 | modifier = Modifier 57 | .padding(16.dp) 58 | .width(300.dp) 59 | ) { 60 | Text( 61 | "Congratulations! New High Score!", 62 | style = MaterialTheme.typography.headlineSmall, 63 | modifier = Modifier.padding(bottom = 8.dp) 64 | ) 65 | 66 | Text( 67 | "Your time: ${formatTime(currentTime)}", 68 | style = MaterialTheme.typography.bodyLarge, 69 | modifier = Modifier.padding(bottom = 16.dp) 70 | ) 71 | 72 | Text( 73 | "Top Scores:", 74 | style = MaterialTheme.typography.titleMedium, 75 | modifier = Modifier.padding(bottom = 8.dp) 76 | ) 77 | 78 | LazyColumn( 79 | modifier = Modifier 80 | .weight(1f) 81 | .padding(bottom = 16.dp) 82 | ) { 83 | itemsIndexed(scores) { index, score -> 84 | Row( 85 | modifier = Modifier 86 | .fillMaxWidth() 87 | .padding(vertical = 4.dp), 88 | horizontalArrangement = Arrangement.SpaceBetween, 89 | verticalAlignment = Alignment.CenterVertically 90 | ) { 91 | Text( 92 | "${index + 1}.", 93 | modifier = Modifier.width(32.dp) 94 | ) 95 | Text( 96 | score.name, 97 | modifier = Modifier.weight(1f) 98 | ) 99 | Text(formatTime(score.timeInSeconds)) 100 | } 101 | } 102 | } 103 | 104 | OutlinedTextField( 105 | value = playerName, 106 | onValueChange = { playerName = it }, 107 | modifier = Modifier.fillMaxWidth(), 108 | label = { Text("Enter your name") }, 109 | singleLine = true 110 | ) 111 | 112 | Row( 113 | modifier = Modifier 114 | .fillMaxWidth() 115 | .padding(top = 16.dp), 116 | horizontalArrangement = Arrangement.End 117 | ) { 118 | TextButton(onClick = onDismiss) { 119 | Text("Cancel") 120 | } 121 | Spacer(Modifier.width(8.dp)) 122 | Button( 123 | onClick = { onSubmit(playerName) }, 124 | enabled = playerName.isNotBlank() 125 | ) { 126 | Text("Submit") 127 | } 128 | } 129 | } 130 | } 131 | } 132 | } 133 | 134 | @OptIn(ExperimentalComposeUiApi::class) 135 | @Composable 136 | fun GameBoard(viewModel: GameViewModel) { 137 | Column( 138 | modifier = Modifier 139 | .fillMaxSize() 140 | .padding(16.dp), 141 | horizontalAlignment = Alignment.CenterHorizontally 142 | ) { 143 | // Game header with status 144 | Text( 145 | when (viewModel.gameState) { 146 | GameState.ONGOING -> "Game in Progress" 147 | GameState.WON -> "You Won! 🎉" 148 | GameState.LOST -> "Game Over! 💣" 149 | }, 150 | color = when (viewModel.gameState) { 151 | GameState.ONGOING -> Color.Black 152 | GameState.WON -> Color(0xFF4CAF50) 153 | GameState.LOST -> Color(0xFFF44336) 154 | }, 155 | fontWeight = if (viewModel.gameState != GameState.ONGOING) FontWeight.Bold else FontWeight.Normal, 156 | fontSize = if (viewModel.gameState != GameState.ONGOING) 24.sp else 18.sp, 157 | modifier = Modifier.padding(bottom = 8.dp) 158 | ) 159 | 160 | // Game info 161 | Row( 162 | modifier = Modifier 163 | .fillMaxWidth() 164 | .padding(bottom = 16.dp), 165 | horizontalArrangement = Arrangement.SpaceEvenly, 166 | verticalAlignment = Alignment.CenterVertically 167 | ) { 168 | Column( 169 | horizontalAlignment = Alignment.CenterHorizontally 170 | ) { 171 | Text("Flags", style = MaterialTheme.typography.titleSmall) 172 | Text( 173 | "${viewModel.remainingFlags}", 174 | style = MaterialTheme.typography.titleLarge, 175 | fontWeight = FontWeight.Bold 176 | ) 177 | } 178 | 179 | Column( 180 | horizontalAlignment = Alignment.CenterHorizontally 181 | ) { 182 | Text("Time", style = MaterialTheme.typography.titleSmall) 183 | Text( 184 | viewModel.formatTime(viewModel.elapsedSeconds), 185 | style = MaterialTheme.typography.titleLarge, 186 | fontWeight = FontWeight.Bold 187 | ) 188 | } 189 | 190 | Column( 191 | horizontalAlignment = Alignment.CenterHorizontally 192 | ) { 193 | Text("Mode", style = MaterialTheme.typography.titleSmall) 194 | Box { 195 | var expanded by remember { mutableStateOf(false) } 196 | 197 | Button( 198 | onClick = { expanded = true }, 199 | colors = ButtonDefaults.buttonColors( 200 | containerColor = when (viewModel.currentDifficulty) { 201 | Difficulty.EASY -> Color(0xFF4CAF50) 202 | Difficulty.MEDIUM -> Color(0xFFFFA000) 203 | Difficulty.HARD -> Color(0xFFF44336) 204 | } 205 | ), 206 | modifier = Modifier.padding(vertical = 4.dp) 207 | ) { 208 | Text(viewModel.currentDifficulty.displayName) 209 | } 210 | 211 | DropdownMenu( 212 | expanded = expanded, 213 | onDismissRequest = { expanded = false } 214 | ) { 215 | Difficulty.entries.forEach { difficulty -> 216 | DropdownMenuItem( 217 | text = { Text(difficulty.displayName) }, 218 | onClick = { 219 | viewModel.changeDifficulty(difficulty) 220 | expanded = false 221 | }, 222 | colors = MenuDefaults.itemColors( 223 | textColor = when (difficulty) { 224 | Difficulty.EASY -> Color(0xFF4CAF50) 225 | Difficulty.MEDIUM -> Color(0xFFFFA000) 226 | Difficulty.HARD -> Color(0xFFF44336) 227 | } 228 | ) 229 | ) 230 | } 231 | } 232 | } 233 | } 234 | } 235 | 236 | // Game grid 237 | Box( 238 | modifier = Modifier 239 | .weight(1f) 240 | .fillMaxWidth(), 241 | contentAlignment = Alignment.Center 242 | ) { 243 | val cellSize = remember { 244 | mutableStateOf(32.dp) 245 | } 246 | 247 | LaunchedEffect(viewModel.board.width, viewModel.board.height) { 248 | // Calculate cell size based on available space 249 | val screenWidth = 320.dp // Approximate minimum screen width 250 | val screenHeight = 480.dp // Approximate minimum screen height 251 | val horizontalCells = viewModel.board.width 252 | val verticalCells = viewModel.board.height 253 | 254 | cellSize.value = minOf( 255 | (screenWidth - 32.dp) / horizontalCells, 256 | (screenHeight - 200.dp) / verticalCells 257 | ) 258 | } 259 | 260 | Column { 261 | for (x in 0 until viewModel.board.width) { 262 | Row { 263 | for (y in 0 until viewModel.board.height) { 264 | val cell = viewModel.board.grid[x][y] 265 | val interactionSource = remember { MutableInteractionSource() } 266 | val isHovered by interactionSource.collectIsHoveredAsState() 267 | 268 | Box( 269 | modifier = Modifier 270 | .size(cellSize.value) 271 | .hoverable(interactionSource) 272 | .border( 273 | width = 0.5.dp, 274 | color = if (cell.state == CellState.REVEALED) 275 | RevealedCellBorderColor 276 | else 277 | UnrevealedCellBorderColor 278 | ) 279 | .background( 280 | when { 281 | isHovered && cell.state != CellState.REVEALED -> HoverCellColor 282 | cell.state == CellState.REVEALED -> RevealedCellColor 283 | else -> UnrevealedCellColor 284 | } 285 | ) 286 | .padding(1.dp) 287 | .pointerInput(Unit) { 288 | detectTapGestures( 289 | onTap = { viewModel.onCellClick(x, y) }, 290 | onLongPress = { viewModel.onCellRightClick(x, y) } 291 | ) 292 | } 293 | ) { 294 | when { 295 | cell.state == CellState.FLAGGED -> { 296 | Text( 297 | "🚩", 298 | modifier = Modifier.align(Alignment.Center), 299 | fontSize = (cellSize.value.value * 0.6f).sp 300 | ) 301 | } 302 | cell.state == CellState.REVEALED && cell.hasMine -> { 303 | Text( 304 | "💣", 305 | modifier = Modifier.align(Alignment.Center), 306 | fontSize = (cellSize.value.value * 0.6f).sp 307 | ) 308 | } 309 | cell.state == CellState.REVEALED && cell.adjacentMines > 0 -> { 310 | Text( 311 | text = cell.adjacentMines.toString(), 312 | modifier = Modifier.align(Alignment.Center), 313 | fontSize = (cellSize.value.value * 0.7f).sp, 314 | color = when (cell.adjacentMines) { 315 | 1 -> Color.Blue 316 | 2 -> Color.Green 317 | 3 -> Color.Red 318 | else -> Color.Black 319 | } 320 | ) 321 | } 322 | } 323 | } 324 | } 325 | } 326 | } 327 | } 328 | } 329 | 330 | // Game controls 331 | Button( 332 | onClick = { viewModel.resetGame() }, 333 | modifier = Modifier.padding(top = 16.dp), 334 | colors = ButtonDefaults.buttonColors( 335 | containerColor = when (viewModel.gameState) { 336 | GameState.WON -> Color(0xFF4CAF50) 337 | GameState.LOST -> Color(0xFFF44336) 338 | else -> MaterialTheme.colorScheme.primary 339 | } 340 | ) 341 | ) { 342 | Text( 343 | when (viewModel.gameState) { 344 | GameState.WON -> "Play Again! 🎮" 345 | GameState.LOST -> "Try Again! 🔄" 346 | else -> "Reset Game" 347 | }, 348 | color = Color.White 349 | ) 350 | } 351 | } 352 | 353 | if (viewModel.showHighScoreDialog) { 354 | HighScoreDialog( 355 | scores = viewModel.topScores, 356 | currentTime = viewModel.elapsedSeconds, 357 | onDismiss = { viewModel.dismissHighScoreDialog() }, 358 | onSubmit = { name -> viewModel.addHighScore(name) } 359 | ) 360 | } 361 | } 362 | 363 | fun main() = application { 364 | val viewModel = remember { GameViewModel() } 365 | 366 | Window( 367 | onCloseRequest = ::exitApplication, 368 | title = "Minesweeper", 369 | state = rememberWindowState( 370 | width = 400.dp, 371 | height = 600.dp 372 | ) 373 | ) { 374 | MaterialTheme { 375 | GameBoard(viewModel) 376 | } 377 | } 378 | } 379 | --------------------------------------------------------------------------------