Created
September 8, 2021 22:46
-
-
Save twofingerrightclick/30dd5619d22510c42e2ffdea7ce025dc to your computer and use it in GitHub Desktop.
Listing 12.2: Supporting Undo in a Program Similar to an Etch A Sketch Toy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
class Program | |
{ | |
// ... | |
public void Sketch() | |
{ | |
Stack path = new Stack(); | |
Cell currentPosition; | |
ConsoleKeyInfo key; // Added in C# 2.0 | |
do | |
{ | |
// Etch in the direction indicated by the | |
// arrow keys that the user enters | |
key = Move(); | |
switch (key.Key) | |
{ | |
case ConsoleKey.Z: | |
// Undo the previous Move | |
if (path.Count >= 1) | |
{ | |
currentPosition = (Cell)path.Pop(); | |
Console.SetCursorPosition( | |
currentPosition.X, currentPosition.Y); | |
Undo(); | |
} | |
break; | |
case ConsoleKey.DownArrow: | |
case ConsoleKey.UpArrow: | |
case ConsoleKey.LeftArrow: | |
case ConsoleKey.RightArrow: | |
// SaveState() | |
currentPosition = new Cell( | |
Console.CursorLeft, Console.CursorTop); | |
path.Push(currentPosition); | |
break; | |
default: | |
Console.Beep(); // Added in C# 2.0 | |
break; | |
} | |
} | |
while (key.Key != ConsoleKey.X); // Use X to quit | |
} | |
} | |
public struct Cell | |
{ | |
// Use read-only field prior to C# 6.0 | |
public int X { get; } | |
public int Y { get; } | |
public Cell(int x, int y) | |
{ | |
X = x; | |
Y = y; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment