跳至正文
View Categories

1 min read

python开发五子棋2 #

  1. 设定五子棋初始化参数
  2. 画出五子棋棋盘

收获 #

了解五子棋人人交战背后的python原理,通过PyGame实践学会独立建立和更新项目,完成五子棋游戏开发

设定五子棋初始化参数 #

结合上一节课pygame的最小开发框架,本小节为设定游戏屏幕的初始化设置

import pygame
import sys
from pygame.locals import *

SCREEN_WIDTH = 200
SCREEN_HEIGHT = 100

def main():
    pygame.init() #初始化pygame
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) #获取对显示系统的访问,并创建一个窗口screen
    pygame.display.set_caption('五子棋')

    while True:#不断训练刷新画布
        for event in pygame.event.get():#获取事件,如果鼠标点击右上角关闭按钮,关闭
            if event.type == QUIT:
                sys.exit()

        pygame.display.flip()

if __name__ == '__main__':
    main()

画出五子棋棋盘 #

本小节为五子棋棋盘的绘制方法,包括填充棋盘背景色,画棋盘网格线外的边框,画出网格线、画星位和天元.

######################这部分可添加在设定五子棋初始化参数 SCREEN_HEIGHT = 100 的下一行########################
SIZE = 30  # 棋盘每个点时间的间隔
Line_Points = 19  # 棋盘每行/每列点数
Outer_Width = 20  # 棋盘外宽度
Border_Width = 4  # 边框宽度
Inside_Width = 4  # 边框跟实际的棋盘之间的间隔
Border_Length = SIZE * (Line_Points - 1) + Inside_Width * 2 + Border_Width  # 边框线的长度
Start_X = Start_Y = Outer_Width + int(Border_Width / 2) + Inside_Width  # 网格线起点(左上角)坐标
SCREEN_HEIGHT = SIZE * (Line_Points - 1) + Outer_Width * 2 + Border_Width + Inside_Width * 2  # 游戏屏幕的高
SCREEN_WIDTH = SCREEN_HEIGHT + 200  # 游戏屏幕的宽

Checkerboard_Color = (0xE3, 0x92, 0x65)  # 棋盘颜色
BLACK_COLOR = (0, 0, 0)


###############################在 main主函数的前面 添加以下代码作为新的功能函数#############################
# 画棋盘
def _draw_checkerboard(screen):
    # 填充棋盘背景色
    screen.fill(Checkerboard_Color)
    # 画棋盘网格线外的边框
    pygame.draw.rect(screen, BLACK_COLOR, (Outer_Width, Outer_Width, Border_Length, Border_Length), Border_Width)
    # 画网格线
    for i in range(Line_Points):
        pygame.draw.line(screen, BLACK_COLOR,
                         (Start_Y, Start_Y + SIZE * i),
                         (Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i),
                         1)
    for j in range(Line_Points):
        pygame.draw.line(screen, BLACK_COLOR,
                         (Start_X + SIZE * j, Start_X),
                         (Start_X + SIZE * j, Start_X + SIZE * (Line_Points - 1)),
                         1)
    # 画星位和天元
    for i in (3, 9, 15):
        for j in (3, 9, 15):
            if i == j == 9:
                radius = 5
            else:
                radius = 3
            # pygame.draw.circle(screen, BLACK, (Start_X + SIZE * i, Start_Y + SIZE * j), radius)
            pygame.gfxdraw.aacircle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)
            pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)

小结 #

本节介绍了五子棋人人交战的初始化方法以及棋盘的画法,需要掌握pygame的调用方法,以及五子棋棋盘的画法