-
Notifications
You must be signed in to change notification settings - Fork 0
/
chess.py
712 lines (647 loc) · 27.2 KB
/
chess.py
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
# Daniel Garcia
# gamda_yo@csu.fullerton.edu
# Assignment 6
# Game of Chess
# view - Pygame
# This file contains the main user interaction, the "view"
import pygame, sys
import pickle
import socket
from pygame.locals import *
from button import button
from board import board
from move import move
import chessLocals
import square
import pieces
import dialog
pygame.init()
# set up fonts
basicFont = pygame.font.SysFont(None, 40)
infoFont = pygame.font.SysFont(None,20)
# window size
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 570
SQR_WIDTH = 65
SQR_HEIGHT = 65
MARGIN = 25
###### INITIALIZE DISPLAY #######
windowSurface = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT),0,32)
pygame.display.set_caption( 'Chess!' )
###### MAIN WINDOW COMPONENTS
### Window sections, board and info area
boardRect = pygame.Rect(0,0,WINDOW_WIDTH,WINDOW_HEIGHT)
boardColor = (218,160,20)
infoRect = pygame.Rect(WINDOW_HEIGHT,0,
WINDOW_WIDTH-WINDOW_HEIGHT,WINDOW_HEIGHT)
infoColor = (228,170,30)# a little lighter than board
### Project info
daniel = pygame.image.load('img\\myInfo.png')
myPos = ( WINDOW_HEIGHT+15,245)
### Who's turn:
# get a rect to display to screen
turnRect = pygame.Rect(WINDOW_HEIGHT+80,10,200,60)
pieceRect = pygame.Rect(WINDOW_HEIGHT+15,10,SQR_WIDTH,SQR_HEIGHT)
# ^ to display color of who's turn it is
turnTxt = pygame.image.load('img\\turnTxt.png')
turnTxt.set_colorkey((255,255,255))
### BUTTONS
btnNames = ['btnMusicOn','btnMusicOff','btnNewGame',
'btnSaveGame','btnUndo','btnQuit']
disabledForNetwork = ['btnNewGame','btnSaveGame','btnUndo']
path, suffix = 'img/', '.png'
active, disabled = 'Active','Disabled'
xstart, ystart = WINDOW_HEIGHT+15, 330
buttons = {}
btnRects = {}
firstPass = True # to have both music buttons on the same pos
for name in btnNames:
buttons[name] = button(name,path+name+suffix,
path+name+active+suffix,path+name+disabled+suffix)
if not firstPass:
# only one music square
btnRects[name] = buttons[name].get_rect((xstart,ystart))
# only add after the first pass, means first 2 have same pos
ystart = ystart + 45
firstPass = False
### Promotion
# special rect to hold the 4 possibilities for pawn promotion
# it will be placed starting around (c,3)
promoRect = pygame.Rect(MARGIN+2*SQR_WIDTH-10,\
MARGIN+3*SQR_WIDTH-10,\
4*SQR_WIDTH+20,SQR_HEIGHT+20)
promoRow = 5
promoSqrs = [ (chessLocals.c,promoRow) , (chessLocals.d,promoRow) ,\
(chessLocals.e,promoRow) , (chessLocals.f,promoRow) ]
promoPcs = [ chessLocals.QUEEN, chessLocals.BISHOP,\
chessLocals.KNIGHT, chessLocals.ROOK ]
### Drag piece support
# special rect to hold the active piece
activePieceSqr = pygame.Rect(0,0,SQR_WIDTH,SQR_HEIGHT)
################# SPRITES
### squares
lightSqrImage = pygame.image.load('img\lightSqr.png').convert()
darkSqrImage = pygame.image.load('img\darkSqr.png').convert()
highlightSqr = pygame.image.load('img\highlightSqr.png').convert()
highlightSqr.set_colorkey((255,255,255))
# make them right size
lightSqrImage = pygame.transform.scale(lightSqrImage,(SQR_WIDTH,SQR_HEIGHT))
darkSqrImage = pygame.transform.scale(darkSqrImage,(SQR_WIDTH,SQR_HEIGHT))
highlightSqr = pygame.transform.scale(highlightSqr,(SQR_WIDTH,SQR_HEIGHT))
### white pieces
wb = pygame.image.load('img\wb.png')
wk = pygame.image.load('img\wk.png')
wn = pygame.image.load('img\wn.png')
wp = pygame.image.load('img\wp.png')
wq = pygame.image.load('img\wq.png')
wr = pygame.image.load('img\wr.png')
### black pieces
bb = pygame.image.load('img\\bb.png')
bk = pygame.image.load('img\\bk.png')
bn = pygame.image.load('img\\bn.png')
bp = pygame.image.load('img\\bp.png')
bq = pygame.image.load('img\\bq.png')
br = pygame.image.load('img\\br.png')
### game state
checkmate = pygame.image.load('img\checkMate.png')
stalemate = pygame.image.load('img\staleMate.png')
check = pygame.image.load('img\check.png')
#check.set_colorkey((255,255,255))
# check needs its own rect, it is not displayed like the other 2
checkRect = pygame.Rect(WINDOW_HEIGHT+15,80,100,35)
##### GAME VARIABLES
class gameVars:
def __init__( self , network , sidePlayed = chessLocals.WHITE , \
server = False , ip = None ):
# game-state variables
self.startPos = None
self.endPos = None
self.pieceSelected = False
self.pieceDragged = False
self.changedPiece = False
self.waitingForPromotion = False
# program variables
self.saved = False
self.musicPlaying = True
self.networkGame = network
self.iAmServer = server
self.connectTo = None
self.ip = ip
self.playerSide = sidePlayed
PORT = 5050
def mainMenu( windowSurface ):
"""Initail display. Gets user input to determine the game type. Return
value is a tuple: ( gameType , playerSide ). gameType can be any of
three values: True, when joining a network game; False when playing
a local game; and it will return the local machine's IP address if
a new network game will be selected. When creating a new network
game, the user will be prompted to choose a side; this selection is
the second value of the tuple. If joining a game, the return value
is False and this info should be received from server. If a local
game is being started, chessLocals.WHITE will be returned."""
# button texts
strings = ["New Local Game","New Network Game","Join Game",\
"Load Game","Quit"]
texts = []
rects = []
x = 400
y = 200
for i in range(len(strings)):
texts.append(basicFont.render( strings[i], True,(0,0,0),infoColor))
rects.append(texts[i].get_rect(topleft=(x,y)))
y = y + 40
# draw to the screen
pygame.draw.rect(windowSurface, boardColor, infoRect)
pygame.draw.rect(windowSurface, boardColor, boardRect)
for i in range(len(strings)):
windowSurface.blit(texts[i],rects[i])
pygame.display.update()
while True:
for event in pygame.event.get():
# check for QUIT event
if event.type == QUIT:
exitGame( )
if event.type == MOUSEBUTTONUP:
# a click happened
#-----------------
for i in range(len(rects)):
if( rects[i].collidepoint( event.pos ) ):
# i is in [0,3]
if( i == 0 ):
# new local game
return( False, chessLocals.WHITE )
elif( i == 1 ):
# network game
return( socket.gethostbyname_ex(\
socket.gethostname())[2][0],\
chooseSide(windowSurface) )
# ^ returns local machines ip address and
# selection of piece color
elif( i == 2 ):
# join game
return( True, None )
elif( i == 3 ):
# load game
return( False, False )
else:
exitGame()
def chooseSide( windowSurface ):
# button texts
strings = ["Play White","Play Black"]
texts = []
rects = []
x = 400
y = 200
for i in range(len(strings)):
texts.append(basicFont.render( strings[i], True,(0,0,0),infoColor))
rects.append(texts[i].get_rect(topleft=(x,y)))
y = y + 40
# choose color texts
playWhiteTxt = basicFont.render( "White", True,(0,0,0),infoColor)
playBlackTxt = basicFont.render( "Black", True,(0,0,0),infoColor)
# draw to the screen
pygame.draw.rect(windowSurface, boardColor, infoRect)
pygame.draw.rect(windowSurface, boardColor, boardRect)
for i in range(len(strings)):
windowSurface.blit(texts[i],rects[i])
pygame.display.update()
while True:
for event in pygame.event.get():
# check for QUIT event
if event.type == QUIT:
exitGame( )
if event.type == MOUSEBUTTONUP:
# a click happened
#-----------------
for i in range(len(rects)):
if( rects[i].collidepoint( event.pos ) ):
if( i == 0 ):
return chessLocals.WHITE
else:
return chessLocals.BLACK
def main( ):
gameType = mainMenu( windowSurface )
currentGame = None
prevGame = None
if( gameType[0] == False ):
#local game
currentGame = gameVars( False )
if( gameType[1] == False ):
# load game
# see if there's a saved game
try:
oldGame = open('promo.pkl','rb')
except IOError:
oldGame = None
prevGame = savedGame( oldGame )
elif( gameType[0] == True ):
# join game
currentGame = gameVars( True )
else: # it is local ip
currentGame = gameVars( True , gameType[1] , True , gameType[0] )
### BOARD
if( prevGame != None and not currentGame.networkGame ):
# saved game exists
Board = prevGame
currentGame.saved = True
else:#if( gameType[0] == chessLocals.WHITE ):
# new game
Board = board()
### NETWORK
connection = None
currentGame.ip = socket.gethostbyname_ex(socket.gethostname())[2][0]
# ^ [2] to access list of ip addresses returned by gethostbyname_ex()
# [0] to retrieve the first ip address on the list
if( currentGame.networkGame ):
connection = socket.socket ( socket.AF_INET, socket.SOCK_DGRAM )
if( currentGame.iAmServer ):
# show waiting message and ip
pygame.draw.rect(windowSurface, boardColor, infoRect)
pygame.draw.rect(windowSurface, boardColor, boardRect)
waiting = basicFont.render('Waiting for opponent',True,
(0,0,0),infoColor)
windowSurface.blit(waiting, (100,100))
myIP = basicFont.render( 'IP: '+currentGame.ip,True,
(0,0,0),infoColor)
windowSurface.blit(myIP, (100,200))
pygame.display.update()
connection.bind( ( currentGame.ip , PORT+3 ) )
data,client = connection.recvfrom(1000)
print 'data from',client
print data
currentGame.connectTo = client
# send side info
connection.sendto( currentGame.playerSide, client )
else:
currentGame.ip = dialog.getIP()
# show waiting message
pygame.draw.rect(windowSurface, boardColor, infoRect)
pygame.draw.rect(windowSurface, boardColor, boardRect)
waiting = basicFont.render('Waiting for opponent',True,
(0,0,0),infoColor)
windowSurface.blit(waiting, (100,100))
pygame.display.update()
connection.connect( ( currentGame.ip,PORT+3 ) )
connection.send('connected')
# receive side info
data, server = connection.recvfrom(1000)
currentGame.connectTo = server
print 'data from',server
print data
if( data == chessLocals.WHITE ):
currentGame.playerSide = chessLocals.BLACK
else:
currentGame.playerSide = chessLocals.WHITE
### MUSIC
pygame.mixer.music.load('04 5.mp3')
pygame.mixer.music.play(-1,.2)
### SETUP BOARD SQUARES ###
# create square dictionary
drawX, drawY = 25,25
squares = {}# pygame.rect objects
if( currentGame.playerSide == chessLocals.WHITE ):
# reverse number list so we get (letter,8) on top
# and (letter,1) on the bottom
chessLocals.numberCoords.reverse()
# else, we want black on the bottom
for i in chessLocals.numberCoords:
for j in chessLocals.letterCoords:
newPos = (j,i)
squares[newPos] = pygame.Rect(drawX,drawY,SQR_WIDTH,SQR_HEIGHT)
drawX += SQR_WIDTH
drawY += SQR_HEIGHT
drawX = 25
if( currentGame.playerSide == chessLocals.WHITE ):
chessLocals.numberCoords.reverse()
#### GAME LOOP ####
# make socket non-blocking
if( currentGame.networkGame ):
connection.setblocking(0)
while True:
### Receive network move
if( currentGame.networkGame ):
data = receiveMove( connection , currentGame )
if( Board.whitesTurn ):
if( currentGame.playerSide != chessLocals.WHITE ):
# data received is move already validated, so make it
# in local board
if not( ( data == None) or ( data == 'quit' ) ):
Board.makeMove( pickle.loads(data) )
#else, local player's turn. pass
else:
if not( currentGame.playerSide == chessLocals.BLACK ):
# data received is move already validated, so make it
# in local board
if not( ( data == None) or ( data == 'quit' ) ):
Board.makeMove( pickle.loads(data) )
#else, local player's turn. pass
for event in pygame.event.get():
# check for QUIT event
if event.type == QUIT:
exitGame( currentGame , connection)
# if a piece is clicked, but mouse is not up, move piece
if event.type == MOUSEBUTTONDOWN:
# find piece clicked
coordClicked = posClicked( event.pos , squares )
if( coordClicked ):# coordClicked != None
# square was clicked
if ( coordClicked in Board.allies() ):
############## Unselect Piece ##############
if ( currentGame.pieceSelected == coordClicked ):
currentGame.changedPiece = False
else:
currentGame.changedPiece = True
############################################
# a team piece was clicked, attach it to mouse position
currentGame.pieceSelected = coordClicked
currentGame.pieceDragged = True
else:
# empty square or enemy was clicked
if not currentGame.pieceDragged:
currentGame.pieceSelected = None
currentGame.pieceDragged = False
if( ( currentGame.playerSide !=
Board.squares[coordClicked].contentColor ) and
currentGame.networkGame ):
# player is trying to move opposite pieces in a
# network game
currentGame.pieceSelected = None
currentGame.pieceDragged = False
if event.type == MOUSEBUTTONUP:
# a click happened
#-----------------
####################### BUTTONS
for btn,rect in btnRects.iteritems():
if( rect.collidepoint( event.pos ) ):
if( btn == 'btnMusicOff' ):
if currentGame.musicPlaying:
# turn off music
pygame.mixer.music.stop()
else:
# turn on music
pygame.mixer.music.play(-1,.2)
currentGame.musicPlaying = \
not currentGame.musicPlaying
if not currentGame.networkGame:
if( btn == 'btnNewGame' ):
Board.reset()
currentGame.startPos = None
currentGame.endPos = None
if( btn == 'btnSaveGame' ):
saveGame( Board , currentGame )
if( btn == 'btnUndo' ):
Board.undo( )
if( btn == 'btnQuit' ):
exitGame( currentGame , connection)
####################### SQUARES
coordClicked = posClicked( event.pos , squares )
moved = False
if( coordClicked ):
############## Unselect Piece ##############
if not( currentGame.changedPiece ):
currentGame.pieceSelected = None
############## Pawn promotion ##############
if currentGame.waitingForPromotion:
if coordClicked in promoSqrs:
Board.promote( promoPcs[\
promoSqrs.index(coordClicked)] )
currentGame.waitingForPromotion = False
############## Select and Move ##############
if( currentGame.pieceDragged ):
# a piece dragged was put down, if move is valid, make it
if( currentGame.pieceSelected ):
# ^ pieceSelected != None
currentGame.startPos = currentGame.pieceSelected
currentGame.endPos = coordClicked
moved = movePiece( Board, currentGame, connection )
else:# only a click, however piece already found by
# MOUSEBUTTONDOWN
if( currentGame.startPos == None ):
currentGame.startPos = currentGame.pieceSelected
else: # start pos already, get endpos and move
currentGame.endPos = coordClicked
moved = movePiece( Board, currentGame, connection )
if moved:
currentGame.startPos = None
currentGame.endPos = None
currentGame.pieceDragged = False
currentGame.pieceSelected = None
else:
currentGame.startPos = currentGame.pieceSelected
currentGame.endPos = None
currentGame.pieceDragged = False
#pieceSelected = pieceSelected
# update screen after events
updateScreen( Board , windowSurface , squares, currentGame,\
pygame.mouse.get_pos() )
def receiveMove( connection , currentGame ):
try:
data,client = connection.recvfrom(1000)
except:
data = None
if( data == 'quit' ):
connection.sendto( 'ok', client )
currentGame.networkGame = False
return data
def saveGame( Board , currentGame ):
"""Save current game state."""
currentGame.saved = True
output = open('saved.pkl','wb')
pickle.dump( Board , output )
output.close()
def movePiece( Board, currentGame, connection ):
nxtMove = move( currentGame.startPos,currentGame.endPos )
if Board.makeMove(nxtMove):
currentGame.waitingForPromotion = Board.canPromote()
if( currentGame.networkGame ):
connection.sendto( pickle.dumps(nxtMove), currentGame.connectTo )
currentGame.saved = False
return True
else:
return False
def posClicked( clickpos , squares ):
"""This function takes the position where the click occured and the
square dictionary as parameter. It's return value is the position
tuple corresponding to the square where the click happened. If no
square was clicked, it returns None."""
for pos, sqr in squares.iteritems():
if sqr.collidepoint(clickpos):
return pos
return None
def updateScreen( Board , windowSurface , squares , currentGame , mousepos):
# draw background
pygame.draw.rect(windowSurface, boardColor, boardRect )
drawPieces( Board , windowSurface , squares , \
currentGame.pieceSelected , currentGame.pieceDragged ,\
mousepos )
# promotion area
if( currentGame.waitingForPromotion ):
pygame.draw.rect( windowSurface, boardColor , promoRect )
xstart = promoRect.left+10
ystart = promoRect.top+10
if not Board.whitesTurn:
promoPieces = [wq,wb,wn,wr]
else:
promoPieces = [bq,bb,bn,br]
for i in promoPieces:
activePieceSqr.topleft = (xstart,ystart)
windowSurface.blit(i,activePieceSqr)
xstart = xstart + SQR_WIDTH
# info area
pygame.draw.rect(windowSurface, infoColor, infoRect)
windowSurface.blit(daniel,myPos)
# is game over?
gameStatus = Board.gameState()
if( gameStatus == chessLocals.CHECK ):
windowSurface.blit( check , checkRect )
elif( gameStatus == chessLocals.CHECKMATE ):
pygame.draw.rect( windowSurface, boardColor , promoRect )
windowSurface.blit( checkmate , promoRect )
elif( gameStatus == chessLocals.STALEMATE ):
pygame.draw.rect( windowSurface, boardColor , promoRect )
windowSurface.blit( stalemate , promoRect )
else: #( gameStatus == chessLocals.NOT_DONE ):
# game not done
if currentGame.networkGame:
ipTxt = basicFont.render( 'IP:'+currentGame.ip, \
True,(0,0,0),boardColor)
windowSurface.blit(ipTxt,(585,200))
# buttons
hovered = activeSqr( mousepos )
for name,btn in btnRects.iteritems():
### music case is special because both buttons
# share a square
if( name == 'btnMusicOff' ):
if currentGame.musicPlaying:
btn = buttons[name]
else:
btn = buttons['btnMusicOn']
### if not music btn, nothing special
else:
btn = buttons[name]
### now get proper state given the button status
if currentGame.networkGame and( name in disabledForNetwork ):
img = btn.disabled()
elif( name == hovered ):
# this button has mouse over it, make it active
img = btn.active()
else:
img = btn.normal()
### save button should be disabled if game has been saved
if( name == 'btnSaveGame' and currentGame.saved ):
img = btn.disabled()
if img:
if( btn.name() == 'btnMusicOn' ):
windowSurface.blit(img,btnRects['btnMusicOff'])
else:
windowSurface.blit(img,btnRects[btn.name()])
# who's turn
windowSurface.blit( turnTxt , turnRect )
if( Board.whitesTurn ):
windowSurface.blit( wp , pieceRect )
else:
windowSurface.blit( bp , pieceRect )
pygame.display.update()
def activeSqr( eventpos ):
"""Returns the name of menu sqr that is being hovered over.
If no square is found, returns None."""
# if hovering over buttons, make them active
for btn,rect in btnRects.iteritems():
if( rect.collidepoint( eventpos ) ):
return btn
return None
def drawPieces( Board, windowSurface, squares , \
pieceSelected , pieceDragged, mousepos ):
# draw squares to wipe out board
drawSquares( windowSurface, squares )
# now pieces
for pos, piece in Board.pieces.copy().iteritems():
# find the type of piece
color = piece.color
pieceType = piece.iAm
if( color == chessLocals.WHITE ):
if( pieceType == chessLocals.PAWN ):
pic = wp
if( pieceType == chessLocals.ROOK ):
pic = wr
if( pieceType == chessLocals.KNIGHT ):
pic = wn
if( pieceType == chessLocals.BISHOP ):
pic = wb
if( pieceType == chessLocals.QUEEN ):
pic = wq
if( pieceType == chessLocals.KING ):
pic = wk
else: # color == chessLocals.BLACK
if( pieceType == chessLocals.PAWN ):
pic = bp
if( pieceType == chessLocals.ROOK ):
pic = br
if( pieceType == chessLocals.KNIGHT ):
pic = bn
if( pieceType == chessLocals.BISHOP ):
pic = bb
if( pieceType == chessLocals.QUEEN ):
pic = bq
if( pieceType == chessLocals.KING ):
pic = bk
# move piece that was clicked to mouse position
if( pieceSelected == pos ):
# highlight square with piece currently on
windowSurface.blit(highlightSqr,squares[pieceSelected])
# highlight squares with possible moves
for validPos in Board.validPieceMoves(pos):
windowSurface.blit(highlightSqr,squares[validPos])
#### check for castle options
if( piece.iAm == chessLocals.KING and not piece.hasMoved ):
y = piece.pos[1]# 1 if white, 8 if black
if( Board.canCastleRight() ):
windowSurface.blit(highlightSqr,\
squares[(chessLocals.g,y)])
if( Board.canCastleLeft() ):
windowSurface.blit(highlightSqr,\
squares[(chessLocals.c,y)])
if pieceDragged:
activePieceSqr.center = mousepos
windowSurface.blit(pic,activePieceSqr)
else:
windowSurface.blit(pic,squares[pos])
else:
windowSurface.blit(pic,squares[pos])
def drawSquares( windowSurface , squares ):
# chessLocals.a = ord('a') = 97
# chessLocals.h = ord('h') = 104
# I want (a,1) to be dark square...(odd letter,odd number) = dark
for (x,y),rect in squares.iteritems():
# x is the letter, y is the number
if( x % 2 == 1):# odd letter: a,c,e,g
if( y % 2 == 1):# odd number: 1,3,5,7
windowSurface.blit(darkSqrImage,squares[(x,y)])
else: # even number: 2,4,6,8
windowSurface.blit(lightSqrImage,squares[(x,y)])
else: # even letter: b,d,f,h
if( y % 2 == 1):# odd number: 1,3,5,7
windowSurface.blit(lightSqrImage,squares[(x,y)])
else: # even number: 2,4,6,8
windowSurface.blit(darkSqrImage,squares[(x,y)])
def savedGame( fileToRead ):
try:
return pickle.load( fileToRead )
except:
return None
def exitGame( currentGame , connection ):
if( currentGame.networkGame ):
quitStr = 'quit'
connection.sendto( quitStr , currentGame.connectTo )
connection.setblocking(1)
data,client = connection.recvfrom(1000)
print data
#connection.shutdown(SHUT_RDWR)
connection.close()
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()
## for i in buttons:
## print i.name(),i.normalPath
## print i.normal()