You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
3.5 KiB

import pygame
pygame.init() #初始化
screen = pygame.display.set_mode((600, 600)) #窗口长宽
pygame.display.set_caption('五子棋') #窗口名
flag = 1 # 1黑 2白
space = 20 #四周边距
cell_size = 40 #格子大小
cell_num = 15 #线条数
chess_arr = []# 落子位置
game_state = 1 #游戏状态1.正常进行 2.白胜 3.黑胜
def get_one_dire_num(lx, ly, dx, dy, m):# 判断连子情况
tx = lx
ty = ly
s = 0
while True: #判断各个方向
tx += dx
ty += dy
if tx < 0 or tx >= cell_num or ty < 0 or ty >= cell_num or m[ty][tx] == 0:
return s
s+=1 #连子累加1
def check_win(chess_arr, flag):
m = [[0] * cell_num for i in range(cell_num)] #定义15*15的全0的数组
for x, y, c in chess_arr:
if c == flag:
m[y][x] = 1 # 上面有棋则标1
lx = chess_arr[-1][0] # 最后一个子的x
ly = chess_arr[-1][1] # 最后一个子的y
dire_arr = [[(-1, 0), (1, 0)], [(0, -1), (0, 1)], [(-1, -1), (1, 1)],[(-1, 1), (1, -1)]] # 4个方向数组
for dire1, dire2 in dire_arr:
dx, dy = dire1
num1 = get_one_dire_num(lx, ly, dx, dy, m)
dx, dy = dire2
num2 = get_one_dire_num(lx, ly, dx, dy, m)#连子数为5的获胜
if num1 + num2 + 1 >= 5: return True
return False
while True: #死循环保持窗口显示
for event in pygame.event.get(): #遍历所有事件
if event.type == pygame.QUIT: #如果单击关闭
pygame.quit() #关闭pygame
exit() #结束程序
if game_state == 1 and event.type == pygame.MOUSEBUTTONUP: #鼠标弹起
x, y = pygame.mouse.get_pos() #获取鼠标位置
xi = int(round((x - space) * 1.0 / cell_size)) #x坐标
yi = int(round((y - space) * 1.0 / cell_size)) #y坐标
if 0<=xi<cell_num and 0<=yi<cell_num and (xi,yi) not in chess_arr: #边界&判重
chess_arr.append((xi,yi,flag))
if check_win(chess_arr, flag): #如果获胜
game_state = 2 if flag == 1 else 3
else: #修改黑/白
if flag == 1:
flag=2
else:
flag=1
screen.fill((204, 153, 102)) #设置棕色界面
for x in range(0, cell_size * cell_num, cell_size): #竖线
pygame.draw.line(screen, (200, 200, 200), (x + space, 0 + space),(x + space, cell_size * (cell_num - 1) + space), 1)
for y in range(0, cell_size * cell_num, cell_size): #横线
pygame.draw.line(screen, (200, 200, 200), (0 + space, y + space),(cell_size * (cell_num - 1) + space, y + space), 1)
for i,j in [(4,4),(10,10),(10,4),(4,10),(7,7)]:#五个点
if (i,j,i) not in chess_arr and (i,j,2) not in chess_arr:
pygame.draw.circle(screen, (0, 0, 0), (cell_size * i + space, cell_size * j + space), 5, 1)
for x,y,c in chess_arr:
if c==1:# 设置颜色
chess_color = (30, 30, 30)
else:
chess_color = (225, 225, 225)
pygame.draw.circle(screen,chess_color, [x*cell_size+space, y*cell_size+space], 16,16)# 落子
if game_state != 1:# 显示获胜文字
myfont = pygame.font.Font(None,60)
white = 210,210,0
win_text = "%s Win!"%('Black' if game_state == 2 else 'White')
textImage = myfont.render(win_text, True, white)
screen.blit(textImage, (260,320))
pygame.display.update() #绘图显示