-
Notifications
You must be signed in to change notification settings - Fork 1
/
AI.cs
264 lines (237 loc) · 10.7 KB
/
AI.cs
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
using System.Net;
using System.Net.Sockets;
namespace BombPlane
{
using State = HashSet<Plane>;
using StateSet = HashSet<HashSet<Plane>>;
using StateMapping = Dictionary<BombResult, HashSet<HashSet<Plane>>>;
public class AI
{
private static StateSet? _allState;
public static StateSet AllState
{
get
{
if (_allState is null)
{
_allState = new StateSet();
var planes = new List<Plane>(GridView.BoundedPlanes);
for (int i = 0; i < planes.Count; i++)
for (int j = i + 1; j < planes.Count; j++)
for (int k = j + 1; k < planes.Count; k++)
if (!planes[i].Conflict(planes[j]) && !planes[i].Conflict(planes[k]) && !planes[j].Conflict(planes[k]))
_allState.Add(new State(new Plane[] { planes[i], planes[j], planes[k] }));
}
return _allState;
}
}
private static StateMapping[,] _stateMapping;
public static StateMapping[,] StateMapping
{
get
{
if (_stateMapping == null)
{
_stateMapping = new StateMapping[GridView.ColumnCount, GridView.RowCount];
for (int x = 0; x < GridView.ColumnCount; x++)
{
for (int y = 0; y < GridView.RowCount; y++)
{
_stateMapping[x, y] = new();
_stateMapping[x, y][BombResult.none] = new StateSet();
_stateMapping[x, y][BombResult.body] = new StateSet();
_stateMapping[x, y][BombResult.head] = new StateSet();
}
}
foreach (var state in AllState)
{
HashSet<Point> points = GridView.Points;
foreach (var plane in state)
{
_stateMapping[plane.HeadPoint.X, plane.HeadPoint.Y][BombResult.head].Add(state);
foreach (var point in plane.BodyPoints)
_stateMapping[point.X, point.Y][BombResult.body].Add(state);
points.ExceptWith(plane.Points);
}
foreach (var point in points)
_stateMapping[point.X, point.Y][BombResult.none].Add(state);
}
}
return _stateMapping;
}
}
public AI(int port)
{
_port = port;
}
private int _port;
private Plane[]? _planes;
private Random random = new();
private int numOfHitPlane;
private Socket _socketListen = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //声明用于监听的套接字;
private Thread? _threadListen; //声明线程
private HashSet<Point> remainPoints;
private StateSet remianState;
private Point selectedPoint;
public void Start()
{
try
{
_socketListen.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, -300);
//1.绑定IP和Port
IPEndPoint iPEndPoint = new(IPAddress.Any, _port);
//2.使用Bind()进行绑定
_socketListen.Bind(iPEndPoint);
//3.开启监听
_socketListen.Listen(256); //Listen(int backlog); backlog:监听数量
//开启线程Accept进行通信的客户端socket
_threadListen = new Thread(Listen)
{
IsBackground = true //运行线程在后台执行
}; //线程绑定Listen函数
_threadListen.Start(); //Start里面的参数是Listen函数所需要的参数,这里传送的是用于通信的Socket对象
}
catch (SocketException)
{
MessageBox.Show("AI程序启动失败");
}
}
private void Listen() //建立与客户端的连接
{
List<Thread> threads = new();
try
{
while (true)
{
//4.阻塞到有client连接,得到用于socket的连接
Socket socketAccept = _socketListen.Accept();
//开启第二个线程接收客户端数据
/*
* tip:
* Accept会阻碍主线程的运行,一直在等待客户端的请求,
* 客户端如果不接入,它就会一直在这里等着,主线程卡死
* 所以开启一个新线程接收客户单请求
*/
Thread acceptThread = new(Accept)
{
IsBackground = true //运行线程在后台执行
}; //线程绑定Accept函数
acceptThread.Start(socketAccept); //Start里面的参数是Listen函数所需要的参数,这里传送的是用于通信的Socket对象
threads.Add(acceptThread);
}
}
catch (ThreadInterruptedException)
{
foreach (var thread in threads)
thread.Interrupt();
}
catch (SocketException) { }
}
private void Accept(object? socket) //接收客户端数据
{
Socket acceptSocket = socket as Socket;
try
{
while (true)
{
string command = Utility.Receive(acceptSocket);
string[] strs = command.Split(' ');
switch (strs[0])
{
case "StartGame":
Utility.Send(acceptSocket, "GameAccept");
break;
case "FinishPrepare":
Prepare();
Utility.Send(acceptSocket, "FinishPrepare");
break;
case "GetBombResult":
Point bombPoint = GridView.ConvertStringToPoint(strs[1]);
BombResult bombResult = Bomb(bombPoint);
Utility.Send(acceptSocket, "BombResult " + strs[1] + " " + bombResult.ToString());
SelectPoint();
string pos = GridView.ConvertPointToString(selectedPoint);
Utility.Send(acceptSocket, string.Format("GetBombResult {0}", pos));
break;
case "BombResult":
BombResult result = (BombResult)Enum.Parse(typeof(BombResult), strs[2], true);
StateSet states = StateMapping[selectedPoint.X, selectedPoint.Y][result];
remianState.IntersectWith(states);
if (result == BombResult.head)
numOfHitPlane++;
if (numOfHitPlane == GridView.NumOfPlane)
Utility.Send(acceptSocket, "GameOver");
break;
case "GameOver":
break;
case "GetName":
Utility.Send(acceptSocket, "AI");
break;
case "Connect":
Utility.Send(acceptSocket, "Accept");
break;
default:
break;
}
}
}
catch (ReceiveExpection) { }
}
private Point SelectPoint()
{
double maxGain = -1;
int remainStateCount = remianState.Count;
foreach (var point in remainPoints)
{
var noneStates = StateMapping[point.X, point.Y][BombResult.none];
var possibleNoneCount = remianState.Intersect(noneStates);
double p_none = (double)possibleNoneCount.Count() / remainStateCount;
var bodyStates = StateMapping[point.X, point.Y][BombResult.body];
var possibleBodyStates = remianState.Intersect(bodyStates);
double p_body = (double)possibleBodyStates.Count() / remainStateCount;
var headStates = StateMapping[point.X, point.Y][BombResult.none];
var possibleHeadStates = remianState.Intersect(headStates);
double p_head = (double)possibleHeadStates.Count() / remainStateCount;
double gain = 1 - p_none * p_none - p_body * p_body - p_head * p_head;
if (gain > maxGain)
{
maxGain = gain;
selectedPoint = point;
}
}
remainPoints.Remove(selectedPoint);
return selectedPoint;
}
public void Prepare()
{
int columnCount = GridView.ColumnCount;
int rowCount = GridView.RowCount;
_planes = new Plane[GridView.NumOfPlane] {
new Plane((Direction)random.Next(0, 3), random.Next(0, columnCount), random.Next(0, rowCount)),
new Plane((Direction)random.Next(0, 3), random.Next(0, columnCount), random.Next(0, rowCount)),
new Plane((Direction)random.Next(0, 3), random.Next(0, columnCount), random.Next(0, rowCount)),
};
int index = 0;
while (!GridView.CheckPlanesValid(_planes))
_planes[index++ % GridView.NumOfPlane] = new Plane((Direction)random.Next(0, 3), random.Next(0, columnCount), random.Next(0, rowCount));
remainPoints = new HashSet<Point>(GridView.Points);
remianState = new StateSet(AllState);
numOfHitPlane = 0;
}
public BombResult Bomb(Point point)
{
return Bomb(point.X, point.Y);
}
public BombResult Bomb(int X, int Y)
{
foreach (Plane plane in _planes)
if (X == plane.HeadX && Y == plane.HeadY)
return BombResult.head;
else
foreach (Point planePoint in plane.Points)
if (X == planePoint.X && Y == planePoint.Y)
return BombResult.body;
return BombResult.none;
}
}
}