-
Notifications
You must be signed in to change notification settings - Fork 0
/
Game.java
404 lines (337 loc) · 11.3 KB
/
Game.java
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.TimerTask;
public class Game {
/*
* Game describing variables
*/
private String blue;
private String white;
private int blueScore=0;
private int whiteScore=0;
private int blueTeamLeader;
private int whiteTeamLeader;
private String uwRef1;
private String uwRef2;
private String gameLeader;
private boolean stoppingTime;
private long halfTimesDuration;
private int halfTimesCount;
/*
* Internal state variables
*/
private Date start = null;
private int currentHalfTime = 0;
private boolean nonStoppingTimeGameIsRunning = false;
private boolean gameIsFinished;
private GameLog gameLog;
private Date clockStoppedAt;
private long timeWasStoppedFor = 0;
private Runnable gameTimeRunnable;
private ScheduledFuture<?> gameTimeRunnableFuture;
private long penaltyThrowDuration = 45000;
private boolean penaltyThrowOnResume = false;
private Date penaltyThrowStartedAt;
private Runnable penaltyThrowRunnable;
private ScheduledFuture<?> penaltyThrowRunnableFuture;
public LinkedList<TwoMinutePenaltyRunnable> twoMinutePenaltyRunnables = new LinkedList<TwoMinutePenaltyRunnable>();
//assuming max 8 suspended players, 1 penalty throw, 1 time measurement => each needs its own thread in worst case!
final private ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(10, new DaemonThreadFactory());
private class DaemonThreadFactory implements ThreadFactory{
public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; }
}
private class TwoMinutePenaltyRunnable implements Runnable{
int playerNumber;
Game.Colors team;
long startedAt;
boolean isCancelled = false;
public TwoMinutePenaltyRunnable(int playerNumber, Game.Colors team, long startedAt){
super();
this.playerNumber = playerNumber;
this.team = team;
this.startedAt = startedAt;
}
private long getRestTimeMillis(){
return 120*1000-(getCurrentGameTimeMillis()-startedAt);
}
public int getRestTime(){
return (int) getRestTimeMillis()/1000;
}
//TODO: Cacnel auch ueber die Future machen
public void cancel(){
isCancelled = true;
}
public void allowPlayerBackIn(){
//TODO: Spieler wieder reinstellen
System.out.println(new Date()+" Spieler "+playerNumber+" von Team "+team+" darf wieder mitspielen");
twoMinutePenaltyRunnables.remove(this);
cancel();
}
public void run(){
if(isCancelled){
return;
}
long restTime = getRestTimeMillis();
if(restTime<=0){
allowPlayerBackIn();
}else{
timer.schedule(this, restTime, TimeUnit.MILLISECONDS);
System.err.println(new Date()+" Player "+playerNumber+" of team "+team+" would be allowed in, but game has been stopped. Rechecking in "+restTime);
}
}
}
public enum GameAction {
UNDEFINED, MISTAKE, GOAL, FREE_THROW, WARNING, TEAM_WARNING, TWO_MINUTES, PENALTY_THROW, EXCHANGE
}
public enum Colors {
UNDEFINED, BLUE, WHITE
}
/*
* Constructor and overrides start here
*/
public Game(String blue, String white, String uwRef1, String uwRef2, String gameLeader,
int halfTimesDuration, int halfTimesCount, boolean stoppingTime){
this.blue = blue;
this.white = white;
this.uwRef1 = uwRef1;
this.uwRef2 = uwRef2;
this.gameLeader = gameLeader;
this.halfTimesDuration = halfTimesDuration*1000*60;
this.halfTimesCount = halfTimesCount;
this.stoppingTime = stoppingTime;
this.gameLog = new GameLog();
}
public String toString(){
int curTime=getCurrentGameTime();
return blue+" vs "+white+": "+blueScore+" - "+whiteScore+" The game is currently "+(!isStarted() || isStopped()?"stopped":"running")+
" at "+(curTime/60)+"m"+(curTime%60)+"s in halftime #"+currentHalfTime+".";
}
/*
* Game time related stuff from here on
*/
public void start(){
if(gameIsFinished){
System.out.println("Spiel zu Ende - alle Halbzeiten gespielt.");
return;
}
start = new Date();
currentHalfTime++;
gameTimeRunnable = new Runnable(){
public void run(){
boolean penaltyThrowRunning = penaltyThrowRunning();
if(!penaltyThrowRunning && getCurrentGameTimeMillis()>=halfTimesDuration){
//TODO abhupen
start = null;
timeWasStoppedFor = 0;
unsuspendAllPlayers();
gameIsFinished = currentHalfTime == halfTimesCount;
System.out.println(new Date()+" Halbzeit zu ende! ");
}else if(penaltyThrowRunning){
timer.schedule(this, penaltyThrowDuration-getCurrentPenaltyThrowTimeMillis(), TimeUnit.MILLISECONDS);
System.err.println(new Date()+" Halbzeit zu ende, aber Strafwurf laeuft noch! => Warte "+penaltyThrowDuration+"-"+getCurrentPenaltyThrowTimeMillis());
}else{
timer.schedule(this, halfTimesDuration-getCurrentGameTimeMillis(), TimeUnit.MILLISECONDS);
System.err.println(new Date()+" Halbzeit zu ende, aber Zeit war "+timeWasStoppedFor+"ms angehalten! Warte "+halfTimesDuration+" - "+getCurrentGameTimeMillis());
}
}
};
gameTimeRunnableFuture = timer.schedule(gameTimeRunnable, halfTimesDuration, TimeUnit.MILLISECONDS);
}
public boolean isStarted(){
return start != null;
}
public void reset(){
start = null;
currentHalfTime = 0;
gameTimeRunnableFuture.cancel(false);//TODO: Wirft das nicht ne NPE?
penaltyThrowRunnableFuture.cancel(false);//TODO: Wirft das nicht ne NPE?
unsuspendAllPlayers();
//todo clear log
}
public void stopClock(){
clockStoppedAt = new Date();
}
public boolean isStopped(){
return start != null && clockStoppedAt != null;
}
public void resumeClock(){
timeWasStoppedFor += new Date().getTime()-clockStoppedAt.getTime();
clockStoppedAt = null;
}
public int getCurrentGameTime(){
return (int) getCurrentGameTimeMillis()/1000;
}
private long getCurrentGameTimeMillis(){
if(isStarted()){
if(isStopped()){
return clockStoppedAt.getTime()-start.getTime()-timeWasStoppedFor;
}else{
return new Date().getTime()-start.getTime()-timeWasStoppedFor;
}
}
return 0;
}
public boolean isFinished(){
return gameIsFinished;
}
/*
* Interaktion with referee from here on
*/
public void refereeInteraktion(){
if(!isStarted()){
start();
return;
}
if(stoppingTime){
if(!isStopped()){
gameLog.createNewLogEntry(getCurrentGameTime());
stopClock();
}else{
resumeClock();
}
}else if(nonStoppingTimeGameIsRunning){
nonStoppingTimeGameIsRunning = !nonStoppingTimeGameIsRunning;
gameLog.createNewLogEntry(getCurrentGameTime());
}
if(penaltyThrowRunning()){
cancelPenaltyThrow();
}
if(penaltyThrowOnResume){
startPenaltyThrow();
}
}
public void decision(Game.Colors team, int player, Game.GameAction incident, String comment){
if(incident == GameAction.MISTAKE){
gameLog.deleteNewestIncident();
}
gameLog.logNewestIncident(team, player, incident, comment);
switch(incident){
case PENALTY_THROW:
if(!isStopped()){
System.err.println("Warning: Free throw given AFTER game was resumed.");
stopClock();
startWithPenaltyThrow();
resumeClock();
}
startWithPenaltyThrow();
break;
case TWO_MINUTES:
suspendPlayer(player, team);
break;
case GOAL:
if(team == Colors.WHITE){
whiteScore++;
unsuspendPlayer(Colors.BLUE);
}else{
blueScore++;
unsuspendPlayer(Colors.WHITE);
}
}
}
/*
* Penalty throw related stuff from here on
*/
public void startPenaltyThrow(){
penaltyThrowOnResume = false;
penaltyThrowStartedAt = new Date();
penaltyThrowRunnable = new Runnable(){
public void run(){
//TODO: Abhupen
System.out.println(new Date()+" Strafwurf zu ende!");
cancelPenaltyThrow();
}
};
penaltyThrowRunnableFuture = timer.schedule(penaltyThrowRunnable, penaltyThrowDuration, TimeUnit.MILLISECONDS);
}
public void cancelPenaltyThrow(){
penaltyThrowStartedAt = null;
penaltyThrowRunnableFuture.cancel(false);
}
public void startWithPenaltyThrow(){
penaltyThrowOnResume = true;
}
public boolean penaltyThrowRunning(){
return penaltyThrowStartedAt != null;
}
private long getCurrentPenaltyThrowTimeMillis(){
if(!penaltyThrowRunning())
return penaltyThrowDuration;
return new Date().getTime()-penaltyThrowStartedAt.getTime();
}
/*
* 2 minute suspension related stuff from here on
*/
public void suspendPlayer(int playerNumber, Game.Colors team){
TwoMinutePenaltyRunnable task = new TwoMinutePenaltyRunnable(playerNumber, team, getCurrentGameTimeMillis());
twoMinutePenaltyRunnables.add(task);
timer.schedule(task, 2*60*1000, TimeUnit.MILLISECONDS);
}
public void unsuspendPlayer(Game.Colors team){
int i=-1;
try{
while(twoMinutePenaltyRunnables.get(++i).team!=team);
}catch(IndexOutOfBoundsException e){
return;
}
TwoMinutePenaltyRunnable task = twoMinutePenaltyRunnables.get(i);
task.allowPlayerBackIn();
}
private void unsuspendAllPlayers(){
for(TwoMinutePenaltyRunnable task: twoMinutePenaltyRunnables){
task.cancel();
task.allowPlayerBackIn();
}
twoMinutePenaltyRunnables.clear();
}
/*
* Some basic testing from here on
*/
public static void main(String[] args) throws IOException{
System.out.println(new Date()+" Starting a test game of 2 times 3 Minute with stopping time.");
System.out.println(new Date()+" Honk via <ENTER>.");
System.out.println(new Date()+" Decisions via: <P(B|W)> Penalty throw against B or W.");
System.out.println(new Date()+" <T(B|W)#> two Minutes against B or W, # is playerno (one digit).");
System.out.println(new Date()+" <G(B|W)#> Goal for B or W, # is scorerno (one digit)");
System.out.println(new Date()+" <X(B|W)##> exchange in Team B or W. First # is playerno in, second is out.\n");
Game g = new Game("Bamberg1", "Bamberg2", "foo", "bar", "bla", 3, 2, true);
System.out.println("Start: "+g);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null){
if(g.isFinished()){
System.out.println("\n-----------------------------\nGame has finished. Printing game log.");
g.gameLog.printToConsole();
return;
}
if(s.length() == 0){
g.refereeInteraktion();
System.out.println(new Date()+" Honking. Game state: "+g);
}else
try{
switch(s.charAt(0)){
case 'P':
g.decision(s.charAt(1)=='W'?Colors.WHITE:Colors.BLUE, -1, GameAction.PENALTY_THROW, "");
break;
case 'T':
g.decision(s.charAt(1)=='W'?Colors.WHITE:Colors.BLUE, s.charAt(2)-'0', GameAction.TWO_MINUTES, "");
break;
case 'G':
g.decision(s.charAt(1)=='W'?Colors.WHITE:Colors.BLUE, s.charAt(2)-'0', GameAction.GOAL, "");
break;
case 'X':
g.gameLog.createNewExchange(g.getCurrentGameTime(),s.charAt(1)=='W'?Colors.WHITE:Colors.BLUE, s.charAt(2)-'0', s.charAt(3)-'0', "");
}
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
System.out.println("Please honk before filing a decision and make sure you didn't mistype!");
}
}
}
}