b3c7dd3ecdf86b50e6ab7647da807a828ad270b5
[progcomp2013.git] / qchess / src / game.py
1
2
3
4         
5
6 # A thread that runs the game
7 class GameThread(StoppableThread):
8         def __init__(self, board, players):
9                 StoppableThread.__init__(self)
10                 self.board = board
11                 self.players = players
12                 self.state = {"turn" : None} # The game state
13                 self.error = 0 # Whether the thread exits with an error
14                 self.lock = threading.RLock() #lock for access of self.state
15                 self.cond = threading.Condition() # conditional for some reason, I forgot
16                 self.final_result = ""
17                 
18                 
19
20         # Run the game (run in new thread with start(), run in current thread with run())
21         def run(self):
22                 result = ""
23                 while not self.stopped():
24                         
25                         for p in self.players:
26                                 with self.lock:
27                                         if isinstance(p, NetworkSender):
28                                                 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
29                                         else:
30                                                 self.state["turn"] = p
31                                 #try:
32                                 if True:
33                                         [x,y] = p.select() # Player selects a square
34                                         if self.stopped():
35                                                 break
36
37                                         
38                                                 
39
40                                         result = self.board.select(x, y, colour = p.colour)                             
41                                         for p2 in self.players:
42                                                 p2.update(result) # Inform players of what happened
43
44
45                                         log(result)
46
47                                         target = self.board.grid[x][y]
48                                         if isinstance(graphics, GraphicsThread):
49                                                 with graphics.lock:
50                                                         graphics.state["moves"] = self.board.possible_moves(target)
51                                                         graphics.state["select"] = target
52
53                                         time.sleep(turn_delay)
54
55
56                                         if len(self.board.possible_moves(target)) == 0:
57                                                 #print "Piece cannot move"
58                                                 target.deselect()
59                                                 if isinstance(graphics, GraphicsThread):
60                                                         with graphics.lock:
61                                                                 graphics.state["moves"] = None
62                                                                 graphics.state["select"] = None
63                                                                 graphics.state["dest"] = None
64                                                 continue
65
66                                         try:
67                                                 [x2,y2] = p.get_move() # Player selects a destination
68                                         except:
69                                                 self.stop()
70
71                                         if self.stopped():
72                                                 break
73
74                                         self.board.update_move(x, y, x2, y2)
75                                         result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
76                                         for p2 in self.players:
77                                                 p2.update(result) # Inform players of what happened
78
79                                         log(result)
80
81                                         if isinstance(graphics, GraphicsThread):
82                                                 with graphics.lock:
83                                                         graphics.state["moves"] = [[x2,y2]]
84
85                                         time.sleep(turn_delay)
86
87                                         if isinstance(graphics, GraphicsThread):
88                                                 with graphics.lock:
89                                                         graphics.state["select"] = None
90                                                         graphics.state["dest"] = None
91                                                         graphics.state["moves"] = None
92
93                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
94                         #       except Exception,e:
95                         #               result = e.message
96                         #               #sys.stderr.write(result + "\n")
97                         #               
98                         #               self.stop()
99                         #               with self.lock:
100                         #                       self.final_result = self.state["turn"].colour + " " + e.message
101
102                                 if self.board.king["black"] == None:
103                                         if self.board.king["white"] == None:
104                                                 with self.lock:
105                                                         self.final_result = self.state["turn"].colour + " DRAW"
106                                         else:
107                                                 with self.lock:
108                                                         self.final_result = "white"
109                                         self.stop()
110                                 elif self.board.king["white"] == None:
111                                         with self.lock:
112                                                 self.final_result = "black"
113                                         self.stop()
114                                                 
115
116                                 if self.stopped():
117                                         break
118
119
120                 for p2 in self.players:
121                         p2.quit(self.final_result)
122
123                 log(self.final_result)
124
125                 graphics.stop()
126
127         
128 # A thread that replays a log file
129 class ReplayThread(GameThread):
130         def __init__(self, players, src, end=False,max_lines=None):
131                 self.board = Board(style="empty")
132                 GameThread.__init__(self, self.board, players)
133                 self.src = src
134                 self.max_lines = max_lines
135                 self.line_number = 0
136                 self.end = end
137
138                 self.setup()
139
140         def setup(self):
141                 sys.stderr.write("setup called for ReplayThread\n")
142                 if True:
143                         while self.src.readline().strip(" \r\n") != "# Initial board":
144                                 self.line_number += 1
145                 
146                         line = self.src.readline().strip(" \r\n")
147                         
148                         while line != "# Start game":
149                                 #print "Reading line " + str(line)
150                                 self.line_number += 1
151                                 [x,y] = map(int, line.split("at")[1].strip(" \r\n").split(","))
152                                 colour = line.split(" ")[0]
153                                 current_type = line.split(" ")[1]
154                                 types = map(lambda e : e.strip(" [],'"), line.split(" ")[2:4])
155                                 p = Piece(colour, x, y, types)
156                                 if current_type != "unknown":
157                                         p.current_type = current_type
158                                         p.choice = types.index(current_type)
159
160                                 self.board.pieces[colour].append(p)
161                                 self.board.grid[x][y] = p
162                                 if current_type == "king":
163                                         self.board.king[colour] = p
164
165                                 line = self.src.readline().strip(" \r\n")
166                                 
167                 #except Exception, e:
168                 #       raise Exception("FILE line: " + str(self.line_number) + " \""+str(line)+"\"") #\n" + e.message)
169         
170         def run(self):
171                 i = 0
172                 phase = 0
173                 count = 0
174                 line = self.src.readline().strip(" \r\n")
175                 while line != "# EOF":
176                         sys.stderr.write(sys.argv[0] + " : " + str(self.__class__.__name__) + " read: " + str(line) + "\n")
177                         count += 1
178                         if self.max_lines != None and count > self.max_lines:
179                                 self.stop()
180
181                         if self.stopped():
182                                 break
183
184                         with self.lock:
185                                 self.state["turn"] = self.players[i]
186
187                         line = line.split(":")
188                         result = line[len(line)-1].strip(" \r\n")
189                         
190
191                         try:
192                                 self.board.update(result)
193                         except Exception, e:
194                                 sys.stderr.write("Exception! " + str(e.message) + "\n")
195                                 self.final_result = result
196                                 self.stop()
197                                 break
198
199                         log(result)
200
201                         [x,y] = map(int, result.split(" ")[0:2])
202                         target = self.board.grid[x][y]
203
204                         if isinstance(graphics, GraphicsThread):
205                                 if phase == 0:
206                                         with graphics.lock:
207                                                 graphics.state["moves"] = self.board.possible_moves(target)
208                                                 graphics.state["select"] = target
209
210                                         if self.end:
211                                                 time.sleep(turn_delay)
212
213                                 elif phase == 1:
214                                         [x2,y2] = map(int, result.split(" ")[3:5])
215                                         with graphics.lock:
216                                                 graphics.state["moves"] = [[x2,y2]]
217
218                                         if self.end:
219                                                 time.sleep(turn_delay)
220
221                                         with graphics.lock:
222                                                 graphics.state["select"] = None
223                                                 graphics.state["dest"] = None
224                                                 graphics.state["moves"] = None
225                                                 
226
227
228                         
229
230                         for p in self.players:
231                                 p.update(result)
232                         
233                         phase = (phase + 1) % 2
234                         if phase == 0:
235                                 i = (i + 1) % 2
236                         
237                         line = self.src.readline().strip(" \r\n")
238
239                 sys.stderr.write(sys.argv[0] + " : " + str(self.__class__.__name__) + " finished...\n")
240
241                 if self.max_lines != None and self.max_lines > count:
242                         sys.stderr.write(sys.argv[0] + " : Replaying from file; stopping at last line (" + str(count) + ")\n")
243                         sys.stderr.write(sys.argv[0] + " : (You requested line " + str(self.max_lines) + ")\n")
244
245                 if self.end and isinstance(graphics, GraphicsThread):
246                         #graphics.stop()
247                         pass # Let the user stop the display
248                 elif not self.end:
249                         global game
250                         game = GameThread(self.board, self.players)
251                         game.run()
252                 
253
254                 
255
256 def opponent(colour):
257         if colour == "white":
258                 return "black"
259         else:
260                 return "white"

UCC git Repository :: git.ucc.asn.au