Compare commits

..

No commits in common. "21af99f8aecb564e0a3819a92e537e9b25982636" and "d74b7a9413093110496b08e5d9cbf3005103e291" have entirely different histories.

8 changed files with 37 additions and 143 deletions

View File

@ -5,6 +5,7 @@
public string Value = " ";
public bool IsMine;
public bool IsMarked;
public Cell(bool mine)
{
if (mine)

View File

@ -1,44 +0,0 @@
using System.Text.Json;
namespace MineSweeper
{
internal class Database
{
private readonly string path;
private class PlayerData
{
public string name { get; set; }
public int wins { get; set; } = 0;
public int loses { get; set; } = 0;
}
private record Root(List<PlayerData> players);
private readonly Root root;
public Database()
{
path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MineSweeper by H1K0");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
path = Path.Combine(path, "db.json");
if (!File.Exists(path))
File.WriteAllText(path, "{\"players\":[]}");
root = JsonSerializer.Deserialize<Root>(File.ReadAllText(path));
}
public int PlayersCount() { return root.players.Count; }
public int FindPlayer(string name) { return root.players.FindIndex(p => p.name == name); }
public void AddPlayer(string name)
{
PlayerData newplayer = new();
newplayer.name = name;
root.players.Add(newplayer);
}
public int[] Stats(int playerId) { return new int[] { root.players[playerId].wins, root.players[playerId].loses }; }
public void AddGame(int playerId, bool win)
{
if (win)
root.players[playerId].wins++;
else
root.players[playerId].loses++;
}
public void Update() { File.WriteAllText(path, JsonSerializer.Serialize(root)); }
}
}

View File

@ -5,10 +5,9 @@
private readonly int width = 0;
private readonly int height = 0;
private readonly int size = 0;
private int nmines = 0;
private readonly List<Cell> cells = new();
private readonly List<Cell> opened = new();
public Field(int input_width, int input_height, int input_nmines)
public Field(int input_width, int input_height, int nmines)
{
if (input_width < 0 || input_height < 0)
throw new ArgumentException("Field dimensions must be natural numbers.");
@ -20,11 +19,12 @@
throw new ArgumentException("The number of mines can not be negative.");
if (nmines > input_width * input_height)
throw new ArgumentException("The number of mines can not be greater than the number of all cells.");
(width, height, nmines) = (input_width, input_height, input_nmines);
width = input_width;
height = input_height;
size = width * height;
cells = new List<Cell>();
for (int i = 0; i < size; i++)
cells.Add(new Cell(input_nmines-- > 0));
cells.Add(new Cell(nmines-- > 0));
Random rnd = new();
for (int i = 0; i < size; i++)
{
@ -78,7 +78,7 @@
{
Console.Write(" " + ((opened.Contains(cells[y * width + x]) || cells[y * width + x].IsMarked) ? cells[y * width + x].Show() : "■"));
}
Console.WriteLine(" ║ " + (char)('A' + y));
Console.WriteLine(" ║");
}
Console.Write(" ╚");
for (int i = 0; i < 2 * width + 1; i++)
@ -86,21 +86,15 @@
Console.Write("═");
}
Console.WriteLine("╝");
Console.Write(" ");
for (int i = 0; i < width;)
{
Console.Write(" " + ++i);
}
Console.WriteLine($"\n\nRemaining mines: {nmines}.");
}
public bool Open(int y, int x)
{
if (y < 0 || y >= height || x < 0 || x >= width)
throw new Exception("Coordinates out of the field!");
if (cells[y * width + x].IsMarked)
return false;
if (cells[y * width + x].IsMine)
return true;
if (cells[y * width + x].IsMarked)
return false;
if (!opened.Contains(cells[y * width + x]))
{
opened.Add(cells[y * width + x]);
@ -156,7 +150,7 @@
}
return false;
}
public void OpenAll(bool automark)
public void OpenAll()
{
for (int i = 0; i < size; i++)
{
@ -164,27 +158,14 @@
opened.Add(cells[i]);
if (cells[i].IsMarked && !cells[i].IsMine)
cells[i].SetWrong();
if (automark && cells[i].IsMine)
{
cells[i].Mark();
nmines = 0;
}
}
this.Draw();
}
public void Mark(int y, int x)
{
if (!opened.Contains(cells[y * width + x]))
{
cells[y * width + x].Mark();
nmines--;
}
}
public void Unmark(int y, int x)
{
cells[y * width + x].Unmark();
nmines++;
}
public void Unmark(int y, int x) { cells[y * width + x].Unmark(); }
public bool Check()
{
for (int i = 0; i < size; i++)

31
Game.cs
View File

@ -14,40 +14,35 @@
while (true)
{
Console.Clear();
field.Draw();
if (field.Check())
{
field.OpenAll(true);
return true;
}
field.Draw();
Console.Write("Enter your command: ");
try
{
command = Console.ReadLine().ToUpper().Split();
if (command.Length == 1)
{
int x = Convert.ToInt16(command[0][1..]) - 1;
int x = Convert.ToInt16(command[0].Substring(1)) - 1;
int y = command[0].First() - 'A';
if (field.Open(y, x))
{
Console.Clear();
field.OpenAll(false);
this.Finish();
return false;
}
}
else if (command.Length > 1)
else if (command.Length == 2)
{
if (command[0] != "M" && command[0] != "U")
throw new Exception("Invalid command.");
for (int i = 1; i < command.Length; i++)
{
int x = Convert.ToInt16(command[i][1..]) - 1;
int y = command[i].First() - 'A';
if (command[0] == "M")
field.Mark(y, x);
else
field.Unmark(y, x);
}
int x = Convert.ToInt16(command[1].Substring(1)) - 1;
int y = command[1].First() - 'A';
if (command[0] == "M")
field.Mark(y, x);
else
field.Unmark(y, x);
}
}
catch (Exception ex)
@ -57,5 +52,11 @@
}
}
}
private void Finish()
{
field.OpenAll();
Console.Clear();
field.Draw();
}
}
}

46
Main.cs
View File

@ -5,41 +5,17 @@
public static void Main(string[] args)
{
Game game;
Database database = new();
int PlayerId;
string PlayerName = "";
Console.Title = "MineSweeper by H1K0";
Console.WriteLine("(C) Masahiko AMANO a.k.a. H1K0, 2022\n\n" +
"Hey! Let's play the MineSweeper game!\nPress any button for help or Enter to log in.");
while (Console.ReadKey(true).Key != ConsoleKey.Enter)
Console.WriteLine("\nThe game follows the classic rules.\n" +
"Target cell coordinates are represented this way: A1, F5, I8. Case insensitive.\n" +
"Type coordinates of the cell to open it or use prefixes: \"M\" to mark or \"U\" to unmark the cell.\n" +
"For example: \"B9\", \"M D7\".\n" +
"Press any button to see help again or just press Enter to start the game.");
while (true)
{
Console.Write("\nYour name: ");
PlayerName = Console.ReadLine();
PlayerId = database.FindPlayer(PlayerName);
if (PlayerId == -1 || PlayerName == "")
{
Console.WriteLine("Could not find a player with the name \"" + PlayerName + "\". Press Enter to add new or any other button to re-enter.");
if (Console.ReadKey(true).Key == ConsoleKey.Enter)
{
database.AddPlayer(PlayerName);
PlayerId = database.PlayersCount() - 1;
break;
}
}
else
break;
}
Console.WriteLine("You logged in as \"" + PlayerName + "\".\nYour stats:");
Console.WriteLine($"Wins: {database.Stats(PlayerId)[0]}\nLoses: {database.Stats(PlayerId)[1]}");
while (true)
{
Console.Write("\nOkay, let's play!\nEnter field width, height and number of mines separated with a space: ");
Console.WriteLine("(C) Masahiko AMANO a.k.a. H1K0, 2022\n\n" +
"Hey! Let's play the MineSweeper game!\nType anything for help or just press Enter to start the game.");
while (Console.ReadLine().Length != 0)
Console.WriteLine("\nThe game follows the classic rules.\n" +
"Target cell coordinates are represented this way: A1, F5, I8. Case insensitive.\n" +
"Type coordinates of the cell to open it or use prefixes: \"M\" to mark or \"U\" to unmark the cell.\n" +
"For example: \"B9\", \"M D7\".\n" +
"Type anything to see help again or just press Enter to start the game.\n");
Console.Write("Okay, let's go!\nEnter field width, height and number of mines separated with a space: ");
while (true)
{
try
@ -59,14 +35,12 @@
Console.WriteLine("You win! Congratulations!");
else
Console.WriteLine("You lose!");
database.AddGame(PlayerId, result);
database.Update();
Console.WriteLine("Press Enter to play again or Escape to exit.");
ConsoleKey key;
bool exit = false;
while (true)
{
key = Console.ReadKey(true).Key;
key = Console.ReadKey().Key;
if (key == ConsoleKey.Enter)
{
Console.Clear();

View File

@ -1,29 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RepositoryUrl>https://github.com/H1K0/MineSweeper.git</RepositoryUrl>
<Copyright>Masahiko AMANO a.k.a. H1K0</Copyright>
<Authors>H1K0</Authors>
<StartupObject>MineSweeper.Program</StartupObject>
<PackageProjectUrl>https://github.com/H1K0/MineSweeper</PackageProjectUrl>
<ApplicationIcon>favicon.ico</ApplicationIcon>
<Description>Console MineSweeper game on C#</Description>
<PackageIcon>favicon.png</PackageIcon>
</PropertyGroup>
<ItemGroup>
<Content Include="favicon.ico" />
</ItemGroup>
<ItemGroup>
<None Update="favicon.png">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>
</Project>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB