-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
111 lines (86 loc) · 2.36 KB
/
Copy pathProgram.cs
File metadata and controls
111 lines (86 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System;
class Program
{
static char[,] board = new char[8, 8];
static void Main()
{
SetupBoard();
while (true)
{
PrintBoard();
Console.WriteLine("Move (example: e2 e4):");
string input = Console.ReadLine();
if (!TryParseMove(input, out int fx, out int fy, out int tx, out int ty))
{
Console.WriteLine("Bad input");
continue;
}
if (IsValidPawnMove(fx, fy, tx, ty))
{
board[tx, ty] = board[fx, fy];
board[fx, fy] = '.';
}
else
{
Console.WriteLine("Illegal move (only basic pawn rules)");
}
}
}
static void SetupBoard()
{
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
board[i, j] = '.';
for (int i = 0; i < 8; i++)
{
board[1, i] = 'P';
board[6, i] = 'p';
}
}
static void PrintBoard()
{
Console.WriteLine();
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
Console.Write(board[i, j] + " ");
Console.WriteLine();
}
Console.WriteLine();
}
static bool TryParseMove(string input, out int fx, out int fy, out int tx, out int ty)
{
fx = fy = tx = ty = 0;
if (string.IsNullOrWhiteSpace(input))
return false;
var parts = input.Split(' ');
if (parts.Length != 2)
return false;
return ParseSquare(parts[0], out fx, out fy) &&
ParseSquare(parts[1], out tx, out ty);
}
static bool ParseSquare(string s, out int x, out int y)
{
x = y = 0;
if (s.Length != 2)
return false;
char file = s[0];
char rank = s[1];
y = file - 'a';
x = 8 - (rank - '0');
return x >= 0 && x < 8 && y >= 0 && y < 8;
}
static bool IsValidPawnMove(int fx, int fy, int tx, int ty)
{
char piece = board[fx, fy];
if (piece == 'P')
{
return fx + 1 == tx && fy == ty && board[tx, ty] == '.';
}
if (piece == 'p')
{
return fx - 1 == tx && fy == ty && board[tx, ty] == '.';
}
return false;
}
}