on master help sign in
124 lines 3.3 kB history raw
1using System;
2using static System.Console;
4namespace Cars {
6 /// <summary>
7 /// A generic car.
8 /// </summary>
9 public abstract class Car {
11 /// <summary>
12 /// A random number generator.
13 /// </summary>
14 protected static Random rand = new Random();
16 /// <summary>
17 /// The field storing x.
18 /// </summary>
19 private int _x = 1;
21 /// <summary>
22 /// The x position of the car. Must be >= 1.
23 /// </summary>
24 /// <value>x.</value>
25 public int X {
26 get => _x;
27 set {
28 if (value < 1) {
29 throw new Exception("X must be larger than 1");
30 }
31 _x = value;
32 }
33 }
35 /// <summary>
36 /// The name of the car.
37 /// </summary>
38 /// <value>The name.</value>
39 public string Name { get; set; }
41 /// <summary>
42 /// The symbol represnting the car on screen.
43 /// </summary>
44 /// <value>The symbol.</value>
45 public abstract Char Symbol { get; }
47 /// <summary>
48 /// Moves the car a set random number of units.
49 /// </summary>
50 public abstract void Step();
52 /// <summary>
53 /// Prints the car to the console.
54 /// </summary>
55 /// <param name="width">The width of the road.</param>
56 public void PrintOnMap(int width) {
57 if (width < 0) {
58 throw new Exception("Width can not be negative");
59 }
60 var map = $"{Name}:\t [";
61 for (var i = 0; i < width; i++) {
62 if (i == X - 1) {
63 map += Symbol;
64 } else {
65 map += '-';
66 }
67 }
68 map += ']';
69 WriteLine(map);
70 }
71 }
73 /// <summary>
74 /// a speed car.
75 /// </summary>
76 public class SpeedCar: Car {
77 /// <summary>
78 /// The symbol represnting the car on screen.
79 /// </summary>
80 /// <value>The symbol.</value>
81 public override char Symbol => '>';
83 /// <summary>
84 /// Moves the car form 3 to 5 units in the positive x direction.
85 /// </summary>
86 public override void Step() {
87 X += rand.Next(3, 6);
88 }
90 /// <summary>
91 /// Initializes a new instance of the <see cref="T:Cars.SpeedCar"/> class.
92 /// </summary>
93 /// <param name="name">Name.</param>
94 public SpeedCar(string name) {
95 this.Name = name;
96 }
97 }
99 /// <summary>
100 /// A slow car.
101 /// </summary>
102 public class SlowCar: Car {
103 /// <summary>
104 /// The symbol represnting the car on screen.
105 /// </summary>
106 /// <value>The symbol.</value>
107 public override char Symbol => 'o';
109 /// <summary>
110 /// Moves the car form 0 to 2 units in the positive x direction.
111 /// </summary>
112 public override void Step() {
113 X += rand.Next(0, 3);
114 }
116 /// <summary>
117 /// Initializes a new instance of the <see cref="T:Cars.SlowCar"/> class.
118 /// </summary>
119 /// <param name="name">Name.</param>
120 public SlowCar(string name) {
121 this.Name = name;
122 }
123 }