|
|
import pygame as pg
|
|
|
|
|
|
#设置棋盘上的棋子
|
|
|
def set_chess(x, y, color):
|
|
|
if board[x][y] != ' ':
|
|
|
print('该位置已有棋子') #有了
|
|
|
return False
|
|
|
else:#没有棋子
|
|
|
board[x][y] = color
|
|
|
return True
|
|
|
|
|
|
#检查是否获胜
|
|
|
def check_win(board):
|
|
|
for list_str in board: #遍历棋盘的每一行
|
|
|
if ''.join(list_str).find('O'*5) != -1: #如果找到连续的五个'O',表示白棋获胜,并返回一个0表示白棋获胜
|
|
|
print('白棋获胜')
|
|
|
return 0
|
|
|
elif ''.join(list_str).find('X'*5) != -1:
|
|
|
print('黑棋获胜')
|
|
|
return 1
|
|
|
else:
|
|
|
return -1 #都没有获胜
|
|
|
|
|
|
#检查所有方向的获胜情况
|
|
|
def check_win_all(board):
|
|
|
board_c = [[] for line in range(29)] #水平方向的棋盘副本
|
|
|
for x in range(15):
|
|
|
for y in range(15):
|
|
|
board_c[x-y].append(board[x][y]) #根据斜线填充棋盘副本
|
|
|
board_d = [[] for line in range(29)] #反对角线方向的棋盘副本
|
|
|
for x in range(15):
|
|
|
for y in range(15):
|
|
|
board_d[x+y].append(board[x][y]) #根据反对角线填充棋盘副本
|
|
|
#返回四个方向的检查结果
|
|
|
return [check_win(board), check_win([list(l) for l in zip(*board)]), check_win(board_c), check_win(board_d)]
|
|
|
|
|
|
|
|
|
def main():
|
|
|
pg.init()
|
|
|
clock = pg.time.Clock()
|
|
|
screen = pg.display.set_mode((WIDTH, HEIGHT)) #设置显示模式
|
|
|
|
|
|
black = pg.image.load("data/storn_black.png").convert_alpha()
|
|
|
white = pg.image.load("data/storn_white.png").convert_alpha()
|
|
|
background = pg.image.load("data/bg.png").convert_alpha()
|
|
|
|
|
|
objects = [] #棋子列表
|
|
|
pg.display.set_caption("五子棋") #标题
|
|
|
flag = 0 #当前下棋的标记
|
|
|
going = True #游戏是否继续的标志
|
|
|
chess_list = [black, white] #黑棋和白棋的列表
|
|
|
letter_list = ['X', 'O'] #黑棋和白棋的标记列表
|
|
|
while going:
|
|
|
screen.blit(background, (0, 0))
|
|
|
for event in pg.event.get():
|
|
|
if event.type == pg.QUIT: #点击关闭窗口
|
|
|
going = False
|
|
|
elif event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE: #如果按下Esc键
|
|
|
going = False
|
|
|
elif event.type == pg.MOUSEBUTTONDOWN: #鼠标点击
|
|
|
pos = pg.mouse.get_pos() #获取位置
|
|
|
a, b = round((pos[0] - 27)/40), round((pos[1] - 27)/40) #计算棋盘坐标
|
|
|
x, y = max(0, a) if a < 0 else min(a, 14), max(0, b) if b < 0 else min(b, 14) #限制棋子棋盘内
|
|
|
if set_chess(x, y, letter_list[flag]): #成功放置棋子
|
|
|
objects.append([chess_list[flag], (9+x*40, 9+y*40)]) #将棋子添加到棋子列表
|
|
|
flag = [1, 0][flag] #转换下棋方
|
|
|
if 0 in check_win_all(board) or 1 in check_win_all(board): #检查是否有人获胜
|
|
|
going = False #有人获胜,结束游戏
|
|
|
for o in objects:
|
|
|
screen.blit(o[0], o[1])
|
|
|
clock.tick(60)
|
|
|
pg.display.update()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
WIDTH = 615
|
|
|
HEIGHT = 615
|
|
|
board = [[' ']*15 for line in range(15)]
|
|
|
main()
|
|
|
pg.quit() |