当前进度:只实现了单人作战
代码: terminate():
pygame.quit()
sys.exit()
# 初始化
pygame.init()
mainClock = pygame.time.Clock()
# 加载图片
boardImage = pygame.image.load(‘board.png‘)
boardRect = boardImage.get_rect()
blackImage = pygame.image.load(‘black.png‘)
blackRect = blackImage.get_rect()
whiteImage = pygame.image.load(‘white.png‘)
whiteRect = whiteImage.get_rect()
# 设置窗口
windowSurface = pygame.display.set_mode((boardRect.width, boardRect.height))
pygame.display.set_caption(‘黑白棋‘)
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
windowSurface.fill(BACKGROUNDCOLOR)
windowSurface.blit(boardImage, boardRect, boardRect)
pygame.display.update()
mainClock.tick(FPS)
CELLWIDTH = 50
CELLHEIGHT = 50
PIECEWIDTH = 47
PIECEHEIGHT = 47
BOARDX = 35
BOARDY = 35
# 重置棋盘
def resetBoard(board):
for x in range(8):
for y in range(8):
board[x][y] = ‘none‘
# Starting pieces:
board[3][3] = ‘black‘
board[3][4] = ‘white‘
board[4][3] = ‘white‘
board[4][4] = ‘black‘
# 开局时建立新棋盘
def getNewBoard():
board = []
for i in range(8):
board.append([‘none‘] * 8)
return board
mainBoard = getNewBoard()
resetBoard(mainBoard)
for x in range(8):
for y in range(8):
rectDst = pygame.Rect(BOARDX+x*CELLWIDTH+2, BOARDY+y*CELLHEIGHT+2, PIECEWIDTH, PIECEHEIGHT)
if mainBoard[x][y] == ‘black‘:
windowSurface.blit(blackImage, rectDst, blackRect)
elif mainBoard[x][y] == ‘white‘:
windowSurface.blit(whiteImage, rectDst, whiteRect)
# 谁先走
def whoGoesFirst():
if random.randint(0, 1) == 0:
return ‘computer‘
else:
return ‘player‘
turn = whoGoesFirst()
if turn == ‘player‘:
playerTile = ‘black‘
computerTile = ‘white‘
else:
playerTile = ‘white‘
computerTile = ‘black‘
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if turn == ‘player‘ and event.type == MOUSEBUTTONDOWN and event.button == 1:
x, y = pygame.mouse.get_pos()
col = int((x-BOARDX)/CELLWIDTH)
row = int((y-BOARDY)/CELLHEIGHT)
if makeMove(mainBoard, playerTile, col, row) == True:
if getValidMoves(mainBoard, computerTile) != []:
turn = ‘computer‘
windowSurface.fill(BACKGROUNDCOLOR)
windowSurface.blit(boardImage, boardRect, boardRect)
if (turn == ‘computer‘):
x, y = getComputerMove(mainBoard, computerTile)
makeMove(mainBoard, computerTile, x, y)
savex, savey = x, y
# 玩家没有可行的走法了
if getValidMoves(mainBoard, playerTile) != []:
turn = ‘player‘
windowSurface.fill(BACKGROUNDCOLOR)
windowSurface.blit(boardImage, boardRect, boardRect)
import pygame, sys, random
from pygame.locals import *
BACKGROUNDCOLOR = (255, 255, 255)
BLACK = (255, 255, 255)
BLUE = (0, 0, 255)
CELLWIDTH = 50
CELLHEIGHT = 50
PIECEWIDTH = 47
PIECEHEIGHT = 47
BOARDX = 35
BOARDY = 35
FPS = 40
# 退出
def terminate():
pygame.quit()
sys.exit()
# 重置棋盘
def resetBoard(board):
for x in range(8):
for y in range