This commit is contained in:
rbamforth
2021-04-18 21:19:22 +01:00
37 changed files with 644 additions and 199 deletions

View File

@@ -90,6 +90,7 @@ One could go many directions with this game:
game_number = 0
move_count = 0
losing_book = []
n = 0
MAX_HISTORY = 9
LOSING_BOOK_SIZE = 50

View File

@@ -0,0 +1,175 @@
/**
* Game of Calendar
* <p>
* Based on the BASIC game of Calendar here
* https://github.com/coding-horror/basic-computer-games/blob/main/21%20Calendar/calendar.bas
* <p>
* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing
* new features - no additional text, error checking, etc has been added.
*
* Converted from BASIC to Java by Darren Cardenas.
*/
public class Calendar {
private static final int NUM_WEEK_ROWS = 6;
private static final int NUM_DAYS_PER_WEEK = 7;
private static final int NUM_MONTHS_PER_YEAR = 12;
private static final int[] daysPerMonth = { 0, 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
public void play() {
showIntro();
startGame();
} // End of method play
private static void showIntro() {
System.out.println(" ".repeat(31) + "CALENDAR");
System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
System.out.println("\n\n");
} // End of method showIntro
private void startGame() {
int dayOfMonth = 0;
int dayOfWeek = 0;
int dayOfYear = 0;
int daysTotal = 0;
int index = 0;
int month = 0;
int row = 0;
String lineContent = "";
for (index = 1; index <= 6; index++) {
System.out.println("");
}
daysTotal = -1;
dayOfYear = 0;
System.out.println("");
// Begin loop through all months
for (month = 1; month <= NUM_MONTHS_PER_YEAR; month++) {
System.out.println("");
dayOfYear = dayOfYear + daysPerMonth[month - 1];
lineContent = String.format("** %-3d" + "*".repeat(18), dayOfYear);
switch (month) {
case 1:
lineContent += " JANUARY ";
break;
case 2:
lineContent += " FEBRUARY";
break;
case 3:
lineContent += " MARCH ";
break;
case 4:
lineContent += " APRIL ";
break;
case 5:
lineContent += " MAY ";
break;
case 6:
lineContent += " JUNE ";
break;
case 7:
lineContent += " JULY ";
break;
case 8:
lineContent += " AUGUST ";
break;
case 9:
lineContent += "SEPTEMBER";
break;
case 10:
lineContent += " OCTOBER ";
break;
case 11:
lineContent += " NOVEMBER";
break;
case 12:
lineContent += " DECEMBER";
break;
default:
break;
}
lineContent += "*".repeat(18) + " " + (365 - dayOfYear) + "**";
System.out.println(lineContent);
System.out.println("");
System.out.print(" S M T W");
System.out.println(" T F S");
System.out.println("");
System.out.println("*".repeat(59));
// Begin loop through each week row
for (row = 1; row <= NUM_WEEK_ROWS; row++) {
System.out.println("");
lineContent = " ";
// Begin loop through days of the week
for (dayOfWeek = 1; dayOfWeek <= NUM_DAYS_PER_WEEK; dayOfWeek++) {
daysTotal++;
dayOfMonth = daysTotal - dayOfYear;
if (dayOfMonth > daysPerMonth[month]) {
row = 6;
break;
}
if (dayOfMonth > 0) {
lineContent += dayOfMonth;
}
while (lineContent.length() < (4 + 8 * dayOfWeek)) {
lineContent += " ";
}
} // End loop through days of the week
if (dayOfMonth == daysPerMonth[month]) {
row = 6;
daysTotal += dayOfWeek;
System.out.println(lineContent);
break;
}
System.out.println(lineContent);
} // End loop through each week row
daysTotal -= dayOfWeek;
} // End loop through all months
for (index = 1; index <= 6; index++) {
System.out.println("");
}
} // End of method startGame
public static void main(String[] args) {
Calendar game = new Calendar();
game.play();
} // End of method main
} // End of class Calendar

View File

@@ -0,0 +1,242 @@
import java.util.Scanner;
import java.lang.Math;
/**
* Game of Reverse
* <p>
* Based on the BASIC game of Reverse here
* https://github.com/coding-horror/basic-computer-games/blob/main/73%20Reverse/reverse.bas
* <p>
* Note: The idea was to create a version of the 1970's BASIC game in Java, without introducing
* new features - no additional text, error checking, etc has been added.
*
* Converted from BASIC to Java by Darren Cardenas.
*/
public class Reverse {
private final int NUMBER_COUNT = 9;
private final Scanner scan; // For user input
private enum Step {
INITIALIZE, PERFORM_REVERSE, TRY_AGAIN, END_GAME
}
public Reverse() {
scan = new Scanner(System.in);
} // End of constructor Reverse
public void play() {
showIntro();
startGame();
} // End of method play
private static void showIntro() {
System.out.println(" ".repeat(31) + "REVERSE");
System.out.println(" ".repeat(14) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY");
System.out.println("\n\n");
System.out.println("REVERSE -- A GAME OF SKILL");
System.out.println("");
} // End of method showIntro
private void startGame() {
int index = 0;
int numMoves = 0;
int numReverse = 0;
int tempVal = 0;
int[] numList = new int[NUMBER_COUNT + 1];
Step nextStep = Step.INITIALIZE;
String userResponse = "";
System.out.print("DO YOU WANT THE RULES? ");
userResponse = scan.nextLine();
if (!userResponse.toUpperCase().equals("NO")) {
this.printRules();
}
// Begin outer while loop
while (true) {
// Begin outer switch
switch (nextStep) {
case INITIALIZE:
// Make a random list of numbers
numList[1] = (int)((NUMBER_COUNT - 1) * Math.random() + 2);
for (index = 2; index <= NUMBER_COUNT; index++) {
// Keep generating lists if there are duplicates
while (true) {
numList[index] = (int)(NUMBER_COUNT * Math.random() + 1);
// Search for duplicates
if (!this.findDuplicates(numList, index)) {
break;
}
}
}
System.out.println("");
System.out.println("HERE WE GO ... THE LIST IS:");
numMoves = 0;
this.printBoard(numList);
nextStep = Step.PERFORM_REVERSE;
break;
case PERFORM_REVERSE:
System.out.print("HOW MANY SHALL I REVERSE? ");
numReverse = Integer.parseInt(scan.nextLine());
if (numReverse == 0) {
nextStep = Step.TRY_AGAIN;
} else if (numReverse > NUMBER_COUNT) {
System.out.println("OOPS! TOO MANY! I CAN REVERSE AT MOST " + NUMBER_COUNT);
nextStep = Step.PERFORM_REVERSE;
} else {
numMoves++;
for (index = 1; index <= (int)(numReverse / 2.0); index++) {
tempVal = numList[index];
numList[index] = numList[numReverse - index + 1];
numList[numReverse - index + 1] = tempVal;
}
this.printBoard(numList);
nextStep = Step.TRY_AGAIN;
// Check for a win
for (index = 1; index <= NUMBER_COUNT; index++) {
if (numList[index] != index) {
nextStep = Step.PERFORM_REVERSE;
}
}
if (nextStep == Step.TRY_AGAIN) {
System.out.println("YOU WON IT IN " + numMoves + " MOVES!!!");
System.out.println("");
}
}
break;
case TRY_AGAIN:
System.out.println("");
System.out.print("TRY AGAIN (YES OR NO)? ");
userResponse = scan.nextLine();
if (userResponse.toUpperCase().equals("YES")) {
nextStep = Step.INITIALIZE;
} else {
nextStep = Step.END_GAME;
}
break;
case END_GAME:
System.out.println("");
System.out.println("O.K. HOPE YOU HAD FUN!!");
return;
default:
System.out.println("INVALID STEP");
break;
} // End outer switch
} // End outer while loop
} // End of method startGame
public boolean findDuplicates(int[] board, int length) {
int index = 0;
for (index = 1; index <= length - 1; index++) {
// Identify duplicates
if (board[length] == board[index]) {
return true; // Found a duplicate
}
}
return false; // No duplicates found
} // End of method findDuplicates
public void printBoard(int[] board) {
int index = 0;
System.out.println("");
for (index = 1; index <= NUMBER_COUNT; index++) {
System.out.format("%2d", board[index]);
}
System.out.println("\n");
} // End of method printBoard
public void printRules() {
System.out.println("");
System.out.println("THIS IS THE GAME OF 'REVERSE'. TO WIN, ALL YOU HAVE");
System.out.println("TO DO IS ARRANGE A LIST OF NUMBERS (1 THROUGH " + NUMBER_COUNT + ")");
System.out.println("IN NUMERICAL ORDER FROM LEFT TO RIGHT. TO MOVE, YOU");
System.out.println("TELL ME HOW MANY NUMBERS (COUNTING FROM THE LEFT) TO");
System.out.println("REVERSE. FOR EXAMPLE, IF THE CURRENT LIST IS:");
System.out.println("");
System.out.println("2 3 4 5 1 6 7 8 9");
System.out.println("");
System.out.println("AND YOU REVERSE 4, THE RESULT WILL BE:");
System.out.println("");
System.out.println("5 4 3 2 1 6 7 8 9");
System.out.println("");
System.out.println("NOW IF YOU REVERSE 5, YOU WIN!");
System.out.println("");
System.out.println("1 2 3 4 5 6 7 8 9");
System.out.println("");
System.out.println("NO DOUBT YOU WILL LIKE THIS GAME, BUT");
System.out.println("IF YOU WANT TO QUIT, REVERSE 0 (ZERO).");
System.out.println("");
} // End of method printRules
public static void main(String[] args) {
Reverse game = new Reverse();
game.play();
} // End of method main
} // End of class Reverse

View File

@@ -4,7 +4,6 @@ using SuperStarTrek.Resources;
using SuperStarTrek.Space;
using SuperStarTrek.Systems;
using SuperStarTrek.Systems.ComputerFunctions;
using static System.StringComparison;
namespace SuperStarTrek
{
@@ -22,17 +21,18 @@ namespace SuperStarTrek
private int _initialKlingonCount;
private Enterprise _enterprise;
public Game()
internal Game(Output output, Input input, Random random)
{
_output = new Output();
_input = new Input(_output);
_random = new Random();
_output = output;
_input = input;
_random = random;
}
public float Stardate => _currentStardate;
public float StardatesRemaining => _finalStarDate - _currentStardate;
internal float Stardate => _currentStardate;
public void DoIntroduction()
internal float StardatesRemaining => _finalStarDate - _currentStardate;
internal void DoIntroduction()
{
_output.Write(Strings.Title);
@@ -44,16 +44,13 @@ namespace SuperStarTrek
}
}
public void Play()
internal void Play()
{
Initialise();
var gameOver = false;
var newQuadrantText = Strings.StartText;
while (!gameOver)
{
_enterprise.Quadrant.Display(Strings.NowEntering);
var command = _input.GetCommand();
var result = _enterprise.Execute(command);
@@ -120,7 +117,7 @@ namespace SuperStarTrek
private Quadrant BuildCurrentQuadrant() =>
new Quadrant(_galaxy[_currentQuadrant], _enterprise, _random, _galaxy, _input, _output);
public bool Replay() => _galaxy.StarbaseCount > 0 && _input.GetString(Strings.ReplayPrompt, "Aye");
internal bool Replay() => _galaxy.StarbaseCount > 0 && _input.GetString(Strings.ReplayPrompt, "Aye");
private bool CheckIfStranded()
{

View File

@@ -10,24 +10,24 @@ namespace SuperStarTrek
{
private readonly Output _output;
public Input(Output output)
internal Input(Output output)
{
_output = output;
}
public void WaitForAnyKeyButEnter(string prompt)
internal void WaitForAnyKeyButEnter(string prompt)
{
_output.Write($"Hit any key but Enter {prompt} ");
while (Console.ReadKey(intercept: true).Key == ConsoleKey.Enter);
}
public string GetString(string prompt)
internal string GetString(string prompt)
{
_output.Prompt(prompt);
return Console.ReadLine();
}
public float GetNumber(string prompt)
internal float GetNumber(string prompt)
{
_output.Prompt(prompt);
@@ -44,24 +44,24 @@ namespace SuperStarTrek
}
}
public (float X, float Y) GetCoordinates(string prompt)
internal (float X, float Y) GetCoordinates(string prompt)
{
_output.Prompt($"{prompt} (X,Y)");
var responses = ReadNumbers(2);
return (responses[0], responses[1]);
}
public bool TryGetNumber(string prompt, float minValue, float maxValue, out float value)
internal bool TryGetNumber(string prompt, float minValue, float maxValue, out float value)
{
value = GetNumber($"{prompt} ({minValue}-{maxValue})");
return value >= minValue && value <= maxValue;
}
internal bool GetString(string replayPrompt, string trueValue)
=> GetString(replayPrompt).Equals(trueValue, InvariantCultureIgnoreCase);
internal bool GetString(string replayPrompt, string trueValue) =>
GetString(replayPrompt).Equals(trueValue, InvariantCultureIgnoreCase);
public Command GetCommand()
internal Command GetCommand()
{
while(true)
{
@@ -82,7 +82,7 @@ namespace SuperStarTrek
}
}
public bool TryGetCourse(string prompt, string officer, out Course course)
internal bool TryGetCourse(string prompt, string officer, out Course course)
{
if (!TryGetNumber(prompt, 1, 9, out var direction))
{
@@ -95,7 +95,7 @@ namespace SuperStarTrek
return true;
}
public bool GetYesNo(string prompt, YesNoMode mode)
internal bool GetYesNo(string prompt, YesNoMode mode)
{
_output.Prompt($"{prompt} (Y/N)");
var response = Console.ReadLine().ToUpperInvariant();
@@ -150,7 +150,7 @@ namespace SuperStarTrek
return numbers;
}
public enum YesNoMode
internal enum YesNoMode
{
TrueOnY,
FalseOnN

View File

@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperStarTrek.Commands;
using SuperStarTrek.Resources;
using SuperStarTrek.Space;
@@ -31,22 +30,33 @@ namespace SuperStarTrek.Objects
_input = input;
}
public Quadrant Quadrant => _quadrant;
public Coordinates QuadrantCoordinates => _quadrant.Coordinates;
public Coordinates SectorCoordinates { get; private set; }
internal Quadrant Quadrant => _quadrant;
public string Condition => GetCondition();
public LibraryComputer Computer => (LibraryComputer)_commandExecutors[Command.COM];
public ShieldControl ShieldControl => (ShieldControl)_commandExecutors[Command.SHE];
public float Energy => TotalEnergy - ShieldControl.ShieldEnergy;
public float TotalEnergy { get; private set; }
public int DamagedSystemCount => _systems.Count(s => s.IsDamaged);
public IEnumerable<Subsystem> Systems => _systems;
public PhotonTubes PhotonTubes => (PhotonTubes)_commandExecutors[Command.TOR];
public bool IsDocked => _quadrant.EnterpriseIsNextToStarbase;
public bool IsStranded => TotalEnergy < 10 || Energy < 10 && ShieldControl.IsDamaged;
internal Coordinates QuadrantCoordinates => _quadrant.Coordinates;
public Enterprise Add(Subsystem system)
internal Coordinates SectorCoordinates { get; private set; }
internal string Condition => GetCondition();
internal LibraryComputer Computer => (LibraryComputer)_commandExecutors[Command.COM];
internal ShieldControl ShieldControl => (ShieldControl)_commandExecutors[Command.SHE];
internal float Energy => TotalEnergy - ShieldControl.ShieldEnergy;
internal float TotalEnergy { get; private set; }
internal int DamagedSystemCount => _systems.Count(s => s.IsDamaged);
internal IEnumerable<Subsystem> Systems => _systems;
internal PhotonTubes PhotonTubes => (PhotonTubes)_commandExecutors[Command.TOR];
internal bool IsDocked => _quadrant.EnterpriseIsNextToStarbase;
internal bool IsStranded => TotalEnergy < 10 || Energy < 10 && ShieldControl.IsDamaged;
internal Enterprise Add(Subsystem system)
{
_systems.Add(system);
_commandExecutors[system.Command] = system;
@@ -54,38 +64,29 @@ namespace SuperStarTrek.Objects
return this;
}
public void StartIn(Quadrant quadrant)
internal void StartIn(Quadrant quadrant)
{
_quadrant = quadrant;
quadrant.Display(Strings.StartText);
}
private string GetCondition() =>
(_quadrant.HasKlingons, Energy / _maxEnergy) switch
IsDocked switch
{
(true, _) => "*Red*",
(_, < 0.1f) => "Yellow",
_ => "Green"
true => "Docked",
false when _quadrant.HasKlingons => "*Red*",
false when Energy / _maxEnergy < 0.1f => "Yellow",
false => "Green"
};
public CommandResult Execute(Command command)
internal CommandResult Execute(Command command)
{
if (command == Command.XXX) { return CommandResult.GameOver; }
return _commandExecutors[command].ExecuteCommand(_quadrant);
}
public void Refuel() => TotalEnergy = _maxEnergy;
internal bool Recognises(string command)
{
throw new NotImplementedException();
}
internal string GetCommandList()
{
throw new NotImplementedException();
}
internal void Refuel() => TotalEnergy = _maxEnergy;
public override string ToString() => "<*>";

View File

@@ -7,19 +7,20 @@ namespace SuperStarTrek.Objects
{
private readonly Random _random;
public Klingon(Coordinates sector, Random random)
internal Klingon(Coordinates sector, Random random)
{
Sector = sector;
_random = random;
Energy = _random.GetFloat(100, 300);
}
public float Energy { get; private set; }
public Coordinates Sector { get; private set; }
internal float Energy { get; private set; }
internal Coordinates Sector { get; private set; }
public override string ToString() => "+K+";
public CommandResult FireOn(Enterprise enterprise)
internal CommandResult FireOn(Enterprise enterprise)
{
var attackStrength = _random.GetFloat();
var distanceToEnterprise = Sector.GetDistanceTo(enterprise.SectorCoordinates);

View File

@@ -9,7 +9,7 @@ namespace SuperStarTrek.Objects
private readonly Output _output;
private readonly float _repairDelay;
public Starbase(Coordinates sector, Random random, Input input, Output output)
internal Starbase(Coordinates sector, Random random, Input input, Output output)
{
Sector = sector;
_repairDelay = random.GetFloat() * 0.5f;
@@ -18,6 +18,7 @@ namespace SuperStarTrek.Objects
}
internal Coordinates Sector { get; }
public override string ToString() => ">!<";
internal bool TryRepair(Enterprise enterprise, out float repairTime)

View File

@@ -4,33 +4,33 @@ namespace SuperStarTrek
{
internal class Output
{
public Output Write(string text)
internal Output Write(string text)
{
Console.Write(text);
return this;
}
public Output Write(string format, params object[] args)
internal Output Write(string format, params object[] args)
{
Console.Write(format, args);
return this;
}
public Output WriteLine(string text = "")
internal Output WriteLine(string text = "")
{
Console.WriteLine(text);
return this;
}
public Output NextLine()
internal Output NextLine()
{
Console.WriteLine();
return this;
}
public Output Prompt(string text = "")
internal Output Prompt(string text = "")
{
Console.Write($"{text}? ");
return this;

View File

@@ -29,8 +29,11 @@ namespace SuperStarTrek
{
static void Main()
{
var foo = Utils.DirectionAndDistance.From(1,1).To(4,5);
var game = new Game();
var output = new Output();
var input = new Input(output);
var random = new Random();
var game = new Game(output, input, random);
game.DoIntroduction();

View File

@@ -4,22 +4,22 @@ namespace SuperStarTrek
{
internal class Random
{
private static readonly System.Random _random = new();
private readonly System.Random _random = new();
public Coordinates GetCoordinate() => new Coordinates(Get1To8Inclusive() - 1, Get1To8Inclusive() - 1);
internal Coordinates GetCoordinate() => new Coordinates(Get1To8Inclusive() - 1, Get1To8Inclusive() - 1);
// Duplicates the algorithm used in the original code to get an integer value from 1 to 8, inclusive:
// 475 DEF FNR(R)=INT(RND(R)*7.98+1.01)
// Returns a value from 1 to 8, inclusive.
// Note there's a slight bias away from the extreme values, 1 and 8.
public int Get1To8Inclusive() => (int)(GetFloat() * 7.98 + 1.01);
internal int Get1To8Inclusive() => (int)(GetFloat() * 7.98 + 1.01);
public int GetInt(int inclusiveMinValue, int exclusiveMaxValue) =>
internal int GetInt(int inclusiveMinValue, int exclusiveMaxValue) =>
_random.Next(inclusiveMinValue, exclusiveMaxValue);
public float GetFloat() => (float)_random.NextDouble();
internal float GetFloat() => (float)_random.NextDouble();
public float GetFloat(float inclusiveMinValue, float exclusiveMaxValue)
internal float GetFloat(float inclusiveMinValue, float exclusiveMaxValue)
=> GetFloat() * (exclusiveMaxValue - inclusiveMinValue) + inclusiveMinValue;
}
}

View File

@@ -1,9 +0,0 @@
Functions available from Library-Computer:
0 = Cumulative galactic record
1 = Status report
2 = Photon torpedo data
3 = Starbase nav data
4 = Direction/distance calculator
5 = Galaxy 'region name' map

View File

@@ -1,2 +1,3 @@
Now entering {0} quadrant . . .

View File

@@ -0,0 +1,2 @@
Deflector control room report:
'Shields now at {0} units per your command.'

View File

@@ -6,38 +6,60 @@ namespace SuperStarTrek.Resources
{
internal static class Strings
{
public static string CombatArea => GetResource();
public static string ComputerFunctions => GetResource();
public static string Congratulations => GetResource();
public static string CourtMartial => GetResource();
public static string Destroyed => GetResource();
public static string EndOfMission => GetResource();
public static string Enterprise => GetResource();
public static string Instructions => GetResource();
public static string LowShields => GetResource();
public static string NoEnemyShips => GetResource();
public static string NoStarbase => GetResource();
public static string NowEntering => GetResource();
public static string Orders => GetResource();
public static string PermissionDenied => GetResource();
public static string Protected => GetResource();
public static string RegionNames => GetResource();
public static string RelievedOfCommand => GetResource();
public static string RepairEstimate => GetResource();
public static string RepairPrompt => GetResource();
public static string ReplayPrompt => GetResource();
public static string ShieldsDropped => GetResource();
public static string ShortRangeSensorsOut => GetResource();
public static string StartText => GetResource();
public static string Stranded => GetResource();
public static string Title => GetResource();
internal static string CombatArea => GetResource();
internal static string Congratulations => GetResource();
internal static string CourtMartial => GetResource();
internal static string Destroyed => GetResource();
internal static string EndOfMission => GetResource();
internal static string Enterprise => GetResource();
internal static string Instructions => GetResource();
internal static string LowShields => GetResource();
internal static string NoEnemyShips => GetResource();
internal static string NoStarbase => GetResource();
internal static string NowEntering => GetResource();
internal static string Orders => GetResource();
internal static string PermissionDenied => GetResource();
internal static string Protected => GetResource();
internal static string RegionNames => GetResource();
internal static string RelievedOfCommand => GetResource();
internal static string RepairEstimate => GetResource();
internal static string RepairPrompt => GetResource();
internal static string ReplayPrompt => GetResource();
internal static string ShieldsDropped => GetResource();
internal static string ShieldsSet => GetResource();
internal static string ShortRangeSensorsOut => GetResource();
internal static string StartText => GetResource();
internal static string Stranded => GetResource();
internal static string Title => GetResource();
private static string GetResource([CallerMemberName] string name = "")
{
var streamName = $"SuperStarTrek.Resources.{name}.txt";
using var stream = Assembly
.GetExecutingAssembly()
.GetManifestResourceStream(streamName);
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(streamName);
using var reader = new StreamReader(stream);
return reader.ReadToEnd();

View File

@@ -7,7 +7,7 @@ namespace SuperStarTrek.Space
// Note that the origin is top-left, x increase downwards, and y increases to the right.
internal record Coordinates
{
public Coordinates(int x, int y)
internal Coordinates(int x, int y)
{
X = Validated(x, nameof(x));
Y = Validated(y, nameof(y));
@@ -16,12 +16,15 @@ namespace SuperStarTrek.Space
SubRegionIndex = Y % 4;
}
public int X { get; }
public int Y { get; }
public int RegionIndex { get; }
public int SubRegionIndex { get; }
internal int X { get; }
private int Validated(int value, string argumentName)
internal int Y { get; }
internal int RegionIndex { get; }
internal int SubRegionIndex { get; }
private static int Validated(int value, string argumentName)
{
if (value >= 0 && value <= 7) { return value; }

View File

@@ -46,6 +46,7 @@ namespace SuperStarTrek.Space
}
internal float DeltaX { get; }
internal float DeltaY { get; }
internal IEnumerable<Coordinates> GetSectorsFrom(Coordinates start)
@@ -74,16 +75,16 @@ namespace SuperStarTrek.Space
return (xComplete && yComplete, new Coordinates(quadrantX, quadrantY), new Coordinates(sectorX, sectorY));
}
private (bool, int, int) GetNewCoordinate(int quadrant, int sector, float sectorsTravelled)
private static (bool, int, int) GetNewCoordinate(int quadrant, int sector, float sectorsTravelled)
{
var galacticCoordinate = quadrant * 8 + sector + sectorsTravelled;
var newQuadrant = (int)(galacticCoordinate / 8);
var newSector = (int)(galacticCoordinate - newQuadrant * 8);
if (newSector == -1)
if (newSector < 0)
{
newQuadrant -= 1;
newSector = 7;
newSector += 8;
}
return newQuadrant switch

View File

@@ -1,7 +1,5 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using SuperStarTrek.Objects;
using SuperStarTrek.Resources;
using static System.StringSplitOptions;
@@ -13,7 +11,6 @@ namespace SuperStarTrek.Space
private static readonly string[] _regionNames;
private static readonly string[] _subRegionIdentifiers;
private readonly QuadrantInfo[][] _quadrants;
private readonly Random _random;
static Galaxy()
{
@@ -21,16 +18,14 @@ namespace SuperStarTrek.Space
_subRegionIdentifiers = new[] { "I", "II", "III", "IV" };
}
public Galaxy(Random random)
internal Galaxy(Random random)
{
_random = random;
_quadrants = Enumerable
.Range(0, 8)
.Select(x => Enumerable
.Range(0, 8)
.Select(y => new Coordinates(x, y))
.Select(c => QuadrantInfo.Create(c, GetQuadrantName(c)))
.Select(c => QuadrantInfo.Create(c, GetQuadrantName(c), random))
.ToArray())
.ToArray();
@@ -46,16 +41,18 @@ namespace SuperStarTrek.Space
}
}
public QuadrantInfo this[Coordinates coordinate] => _quadrants[coordinate.X][coordinate.Y];
internal QuadrantInfo this[Coordinates coordinate] => _quadrants[coordinate.X][coordinate.Y];
public int KlingonCount => _quadrants.SelectMany(q => q).Sum(q => q.KlingonCount);
public int StarbaseCount => _quadrants.SelectMany(q => q).Count(q => q.HasStarbase);
public IEnumerable<IEnumerable<QuadrantInfo>> Quadrants => _quadrants;
internal int KlingonCount => _quadrants.SelectMany(q => q).Sum(q => q.KlingonCount);
internal int StarbaseCount => _quadrants.SelectMany(q => q).Count(q => q.HasStarbase);
internal IEnumerable<IEnumerable<QuadrantInfo>> Quadrants => _quadrants;
private static string GetQuadrantName(Coordinates coordinates) =>
$"{_regionNames[coordinates.RegionIndex]} {_subRegionIdentifiers[coordinates.SubRegionIndex]}";
public IEnumerable<IEnumerable<QuadrantInfo>> GetNeighborhood(Quadrant quadrant) =>
internal IEnumerable<IEnumerable<QuadrantInfo>> GetNeighborhood(Quadrant quadrant) =>
Enumerable.Range(-1, 3)
.Select(dx => dx + quadrant.Coordinates.X)
.Select(x => GetNeighborhoodRow(quadrant, x));

View File

@@ -14,9 +14,9 @@ namespace SuperStarTrek.Space
private readonly Dictionary<Coordinates, object> _sectors;
private readonly Enterprise _enterprise;
private readonly Output _output;
private bool _displayed = false;
private bool _entered = false;
public Quadrant(
internal Quadrant(
QuadrantInfo info,
Enterprise enterprise,
Random random,
@@ -39,13 +39,19 @@ namespace SuperStarTrek.Space
PositionObject(_ => new Star(), _info.StarCount);
}
public Coordinates Coordinates => _info.Coordinates;
public bool HasKlingons => _info.KlingonCount > 0;
public int KlingonCount => _info.KlingonCount;
public bool HasStarbase => _info.HasStarbase;
public Starbase Starbase { get; }
internal Coordinates Coordinates => _info.Coordinates;
internal bool HasKlingons => _info.KlingonCount > 0;
internal int KlingonCount => _info.KlingonCount;
internal bool HasStarbase => _info.HasStarbase;
internal Starbase Starbase { get; }
internal Galaxy Galaxy { get; }
public bool EnterpriseIsNextToStarbase =>
internal bool EnterpriseIsNextToStarbase =>
_info.HasStarbase &&
Math.Abs(_enterprise.SectorCoordinates.X - Starbase.Sector.X) <= 1 &&
Math.Abs(_enterprise.SectorCoordinates.Y - Starbase.Sector.Y) <= 1;
@@ -71,9 +77,11 @@ namespace SuperStarTrek.Space
internal void Display(string textFormat)
{
if (_displayed) { return; }
if (!_entered)
{
_output.Write(textFormat, this);
_entered = true;
}
if (_info.KlingonCount > 0)
{
@@ -82,8 +90,6 @@ namespace SuperStarTrek.Space
}
_enterprise.Execute(Command.SRS);
_displayed = true;
}
internal bool HasObjectAt(Coordinates coordinates) => _sectors.ContainsKey(coordinates);
@@ -166,10 +172,10 @@ namespace SuperStarTrek.Space
}
}
public IEnumerable<string> GetDisplayLines() => Enumerable.Range(0, 8).Select(x => GetDisplayLine(x));
internal IEnumerable<string> GetDisplayLines() => Enumerable.Range(0, 8).Select(x => GetDisplayLine(x));
private string GetDisplayLine(int x)
=> string.Join(
private string GetDisplayLine(int x) =>
string.Join(
" ",
Enumerable
.Range(0, 8)

View File

@@ -1,5 +1,3 @@
using SuperStarTrek.Objects;
namespace SuperStarTrek.Space
{
internal class QuadrantInfo
@@ -15,15 +13,18 @@ namespace SuperStarTrek.Space
HasStarbase = hasStarbase;
}
public Coordinates Coordinates { get; }
public string Name { get; }
public int KlingonCount { get; private set; }
public bool HasStarbase { get; private set; }
public int StarCount { get; }
internal Coordinates Coordinates { get; }
public static QuadrantInfo Create(Coordinates coordinates, string name)
internal string Name { get; }
internal int KlingonCount { get; private set; }
internal bool HasStarbase { get; private set; }
internal int StarCount { get; }
internal static QuadrantInfo Create(Coordinates coordinates, string name, Random random)
{
var random = new Random();
var klingonCount = random.GetFloat() switch
{
> 0.98f => 3,

View File

@@ -11,6 +11,7 @@ namespace SuperStarTrek.Systems.ComputerFunctions
}
internal string Description { get; }
protected Output Output { get; }
internal abstract void Execute(Quadrant quadrant);

View File

@@ -1,6 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using SuperStarTrek.Objects;
using SuperStarTrek.Space;
@@ -11,8 +8,8 @@ namespace SuperStarTrek.Systems.ComputerFunctions
private readonly Enterprise _enterprise;
private readonly Input _input;
public DirectionDistanceCalculator(Enterprise enterprise, Output output, Input input)
: base("Starbase nav data", output)
internal DirectionDistanceCalculator(Enterprise enterprise, Output output, Input input)
: base("Direction/distance calculator", output)
{
_enterprise = enterprise;
_input = input;

View File

@@ -6,7 +6,7 @@ namespace SuperStarTrek.Systems.ComputerFunctions
{
internal abstract class GalacticReport : ComputerFunction
{
public GalacticReport(string description, Output output, Galaxy galaxy)
internal GalacticReport(string description, Output output, Galaxy galaxy)
: base(description, output)
{
Galaxy = galaxy;

View File

@@ -8,7 +8,7 @@ namespace SuperStarTrek.Systems.ComputerFunctions
{
private readonly Enterprise _enterprise;
public StarbaseDataCalculator(Enterprise enterprise, Output output)
internal StarbaseDataCalculator(Enterprise enterprise, Output output)
: base("Starbase nav data", output)
{
_enterprise = enterprise;

View File

@@ -10,7 +10,7 @@ namespace SuperStarTrek.Systems.ComputerFunctions
private readonly Galaxy _galaxy;
private readonly Enterprise _enterprise;
public StatusReport(Game game, Galaxy galaxy, Enterprise enterprise, Output output)
internal StatusReport(Game game, Galaxy galaxy, Enterprise enterprise, Output output)
: base("Status report", output)
{
_game = game;

View File

@@ -8,7 +8,7 @@ namespace SuperStarTrek.Systems.ComputerFunctions
{
private readonly Enterprise _enterprise;
public TorpedoDataCalculator(Enterprise enterprise, Output output)
internal TorpedoDataCalculator(Enterprise enterprise, Output output)
: base("Photon torpedo data", output)
{
_enterprise = enterprise;

View File

@@ -9,7 +9,7 @@ namespace SuperStarTrek.Systems
private readonly Enterprise _enterprise;
private readonly Output _output;
public DamageControl(Enterprise enterprise, Output output)
internal DamageControl(Enterprise enterprise, Output output)
: base("Damage Control", Command.DAM, output)
{
_enterprise = enterprise;
@@ -40,7 +40,7 @@ namespace SuperStarTrek.Systems
return CommandResult.Ok;
}
public void WriteDamageReport()
internal void WriteDamageReport()
{
_output.NextLine().WriteLine("Device State of Repair");
foreach (var system in _enterprise.Systems)

View File

@@ -10,7 +10,7 @@ namespace SuperStarTrek.Systems
private readonly Input _input;
private readonly ComputerFunction[] _functions;
public LibraryComputer(Output output, Input input, params ComputerFunction[] functions)
internal LibraryComputer(Output output, Input input, params ComputerFunction[] functions)
: base("Library-Computer", Command.COM, output)
{
_output = output;

View File

@@ -1,10 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using SuperStarTrek.Commands;
using SuperStarTrek.Objects;
using SuperStarTrek.Resources;
using SuperStarTrek.Space;
namespace SuperStarTrek.Systems
@@ -14,7 +9,7 @@ namespace SuperStarTrek.Systems
private readonly Galaxy _galaxy;
private readonly Output _output;
public LongRangeSensors(Galaxy galaxy, Output output)
internal LongRangeSensors(Galaxy galaxy, Output output)
: base("Long Range Sensors", Command.LRS, output)
{
_galaxy = galaxy;

View File

@@ -13,7 +13,7 @@ namespace SuperStarTrek.Systems
private readonly Input _input;
private readonly Random _random;
public PhaserControl(Enterprise enterprise, Output output, Input input, Random random)
internal PhaserControl(Enterprise enterprise, Output output, Input input, Random random)
: base("Phaser Control", Command.PHA, output)
{
_enterprise = enterprise;

View File

@@ -11,7 +11,7 @@ namespace SuperStarTrek.Systems
private readonly Output _output;
private readonly Input _input;
public PhotonTubes(int tubeCount, Enterprise enterprise, Output output, Input input)
internal PhotonTubes(int tubeCount, Enterprise enterprise, Output output, Input input)
: base("Photon Tubes", Command.TOR, output)
{
TorpedoCount = _tubeCount = tubeCount;
@@ -20,7 +20,7 @@ namespace SuperStarTrek.Systems
_input = input;
}
public int TorpedoCount { get; private set; }
internal int TorpedoCount { get; private set; }
protected override bool CanExecuteCommand() => HasTorpedoes() && IsOperational("{name} are not operational");

View File

@@ -1,5 +1,6 @@
using SuperStarTrek.Commands;
using SuperStarTrek.Objects;
using SuperStarTrek.Resources;
using SuperStarTrek.Space;
namespace SuperStarTrek.Systems
@@ -10,7 +11,7 @@ namespace SuperStarTrek.Systems
private readonly Output _output;
private readonly Input _input;
public ShieldControl(Enterprise enterprise, Output output, Input input)
internal ShieldControl(Enterprise enterprise, Output output, Input input)
: base("Shield Control", Command.SHE, output)
{
_enterprise = enterprise;
@@ -18,7 +19,7 @@ namespace SuperStarTrek.Systems
_input = input;
}
public float ShieldEnergy { get; set; }
internal float ShieldEnergy { get; set; }
protected override bool CanExecuteCommand() => IsOperational("{name} inoperable");
@@ -30,6 +31,7 @@ namespace SuperStarTrek.Systems
if (Validate(requested))
{
ShieldEnergy = requested;
_output.Write(Strings.ShieldsSet, requested);
}
else
{

View File

@@ -16,7 +16,7 @@ namespace SuperStarTrek.Systems
private readonly Game _game;
private readonly Output _output;
public ShortRangeSensors(Enterprise enterprise, Galaxy galaxy, Game game, Output output)
internal ShortRangeSensors(Enterprise enterprise, Galaxy galaxy, Game game, Output output)
: base("Short Range Sensors", Command.SRS, output)
{
_enterprise = enterprise;
@@ -47,7 +47,7 @@ namespace SuperStarTrek.Systems
return CommandResult.Ok;
}
public IEnumerable<string> GetStatusLines()
internal IEnumerable<string> GetStatusLines()
{
yield return $"Stardate {_game.Stardate}";
yield return $"Condition {_enterprise.Condition}";

View File

@@ -1,4 +1,3 @@
using System;
using SuperStarTrek.Commands;
using SuperStarTrek.Space;
@@ -16,10 +15,13 @@ namespace SuperStarTrek.Systems
_output = output;
}
public string Name { get; }
public float Condition { get; private set; }
public bool IsDamaged => Condition < 0;
public Command Command { get; }
internal string Name { get; }
internal float Condition { get; private set; }
internal bool IsDamaged => Condition < 0;
internal Command Command { get; }
protected virtual bool CanExecuteCommand() => true;
@@ -34,12 +36,12 @@ namespace SuperStarTrek.Systems
return true;
}
public CommandResult ExecuteCommand(Quadrant quadrant)
internal CommandResult ExecuteCommand(Quadrant quadrant)
=> CanExecuteCommand() ? ExecuteCommandCore(quadrant) : CommandResult.Ok;
protected abstract CommandResult ExecuteCommandCore(Quadrant quadrant);
public virtual void Repair()
internal virtual void Repair()
{
if (IsDamaged)
{
@@ -47,7 +49,7 @@ namespace SuperStarTrek.Systems
}
}
public virtual bool Repair(float repairWorkDone)
internal virtual bool Repair(float repairWorkDone)
{
if (IsDamaged)
{

View File

@@ -1,6 +1,7 @@
using System;
using SuperStarTrek.Commands;
using SuperStarTrek.Objects;
using SuperStarTrek.Resources;
using SuperStarTrek.Space;
namespace SuperStarTrek.Systems
@@ -11,7 +12,7 @@ namespace SuperStarTrek.Systems
private readonly Output _output;
private readonly Input _input;
public WarpEngines(Enterprise enterprise, Output output, Input input)
internal WarpEngines(Enterprise enterprise, Output output, Input input)
: base("Warp Engines", Command.NAV, output)
{
_enterprise = enterprise;
@@ -39,6 +40,8 @@ namespace SuperStarTrek.Systems
_enterprise.PhotonTubes.ReplenishTorpedoes();
}
_enterprise.Quadrant.Display(Strings.NowEntering);
return CommandResult.Elapsed(timeElapsed);
}

View File

@@ -14,13 +14,13 @@ namespace SuperStarTrek.Utils
_fromY = fromY;
}
public static DirectionAndDistance From(Coordinates coordinates) => From(coordinates.X, coordinates.Y);
internal static DirectionAndDistance From(Coordinates coordinates) => From(coordinates.X, coordinates.Y);
public static DirectionAndDistance From(float x, float y) => new DirectionAndDistance(x, y);
internal static DirectionAndDistance From(float x, float y) => new DirectionAndDistance(x, y);
public (float Direction, float Distance) To(Coordinates coordinates) => To(coordinates.X, coordinates.Y);
internal (float Direction, float Distance) To(Coordinates coordinates) => To(coordinates.X, coordinates.Y);
public (float Direction, float Distance) To(float x, float y)
internal (float Direction, float Distance) To(float x, float y)
{
var deltaX = x - _fromX;
var deltaY = y - _fromY;
@@ -45,7 +45,7 @@ namespace SuperStarTrek.Utils
// 8430 PRINT"DIRECTION =";C1+(((ABS(X)-ABS(A))+ABS(X))/ABS(X)):GOTO8460
// 8450 PRINT"DIRECTION =";C1+(ABS(X)/ABS(A))
// 8460 PRINT"DISTANCE =";SQR(X^2+A^2):IFH8=1THEN1990
private float GetDirection(float deltaX, float deltaY)
private static float GetDirection(float deltaX, float deltaY)
{
var deltaXDominant = Math.Abs(deltaX) > Math.Abs(deltaY);
var fractionalPart = deltaXDominant ? deltaY / deltaX : -deltaX / deltaY;
@@ -59,7 +59,7 @@ namespace SuperStarTrek.Utils
return direction < 1 ? direction + 8 : direction;
}
private float GetDistance(float deltaX, float deltaY) =>
private static float GetDistance(float deltaX, float deltaY) =>
(float)Math.Sqrt(Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2));
}
}