mirror of
https://github.com/coding-horror/basic-computer-games.git
synced 2025-12-12 15:50:20 -08:00
Add main game logic
This commit is contained in:
@@ -3,6 +3,13 @@ namespace Cube;
|
||||
internal class Game
|
||||
{
|
||||
private const int _initialBalance = 500;
|
||||
private readonly IEnumerable<(int, int, int)> _seeds = new List<(int, int, int)>
|
||||
{
|
||||
(3, 2, 3), (1, 3, 3), (3, 3, 2), (3, 2, 3), (3, 1, 3)
|
||||
};
|
||||
private readonly (float, float, float) _startLocation = (1, 1, 1);
|
||||
private readonly (float, float, float) _goalLocation = (3, 3, 3);
|
||||
|
||||
private readonly IReadWrite _io;
|
||||
private readonly IRandom _random;
|
||||
|
||||
@@ -51,6 +58,47 @@ internal class Game
|
||||
|
||||
private bool PlayGame()
|
||||
{
|
||||
var mineLocations = _seeds.Select(seed => _random.NextLocation(seed)).ToHashSet();
|
||||
var currentLocation = _startLocation;
|
||||
var prompt = Prompts.YourMove;
|
||||
|
||||
while (true)
|
||||
{
|
||||
var newLocation = _io.Read3Numbers(prompt);
|
||||
|
||||
if (!MoveIsLegal(currentLocation, newLocation)) { return Lose(Streams.IllegalMove); }
|
||||
|
||||
currentLocation = newLocation;
|
||||
|
||||
if (currentLocation == _goalLocation) { return Win(Streams.Congratulations); }
|
||||
|
||||
if (mineLocations.Contains(currentLocation)) { return Lose(Streams.Bang); }
|
||||
|
||||
prompt = Prompts.NextMove;
|
||||
}
|
||||
}
|
||||
|
||||
private bool Lose(Stream text)
|
||||
{
|
||||
_io.Write(text);
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool Win(Stream text)
|
||||
{
|
||||
_io.Write(text);
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool MoveIsLegal((float, float, float) from, (float, float, float) to)
|
||||
=> (to.Item1 - from.Item1, to.Item2 - from.Item2, to.Item3 - from.Item3) switch
|
||||
{
|
||||
( > 1, _, _) => false,
|
||||
(_, > 1, _) => false,
|
||||
(_, _, > 1) => false,
|
||||
(1, 1, _) => false,
|
||||
(1, _, 1) => false,
|
||||
(_, 1, 1) => false,
|
||||
_ => true
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,4 +17,4 @@ internal static class IOExtensions
|
||||
prompt = Prompts.BetAgain;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
14
30_Cube/csharp/RandomExtensions.cs
Normal file
14
30_Cube/csharp/RandomExtensions.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace Cube;
|
||||
|
||||
internal static class RandomExtensions
|
||||
{
|
||||
internal static (float, float, float) NextLocation(this IRandom random, (int, int, int) bias)
|
||||
=> (random.NextCoordinate(bias.Item1), random.NextCoordinate(bias.Item2), random.NextCoordinate(bias.Item3));
|
||||
|
||||
private static float NextCoordinate(this IRandom random, int bias)
|
||||
{
|
||||
var value = random.Next(3);
|
||||
if (value == 0) { value = bias; }
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
Next move:
|
||||
Next move:
|
||||
Reference in New Issue
Block a user