跳至正文
View Categories

1 min read

python开发五子棋4 #

  1. 画出棋子
  2. 落子动作函数的实现

收获 #

了解python类函数的定义方法和原理,完成五子棋棋子的绘制、交互动作的实现和游戏中棋子的更新。

画出棋子 #

本小节为五子棋棋子的绘制方法和对应位置信息的实现.

#######################在五子棋2的from pygame.locals import *后面添加以下代码########
import pygame.gfxdraw
from checkerboard import Checkerboard, BLACK_CHESSMAN, WHITE_CHESSMAN, Point

Stone_Radius = SIZE // 2 - 3  # 棋子半径
Stone_Radius2 = SIZE // 2 + 3
Checkerboard_Color = (0xE3, 0x92, 0x65)  # 棋盘颜色
BLACK_COLOR = (0, 0, 0)
WHITE_COLOR = (255, 255, 255)
RED_COLOR = (200, 30, 30)
BLUE_COLOR = (30, 30, 200)
BLACK_STONE_COLOR = (45, 45, 45)
WHITE_STONE_COLOR = (219, 219, 219)

RIGHT_INFO_POS_X = SCREEN_HEIGHT + Stone_Radius2 * 2 + 10

#######################在五子棋2的_draw_checkerboard()函数后面添加以下代码作为新的功能函数########
# 画棋子
def _draw_chessman(screen, point, stone_color):
    # pygame.draw.circle(screen, stone_color, (Start_X + SIZE * point.X, Start_Y + SIZE * point.Y), Stone_Radius)
    pygame.gfxdraw.aacircle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)
    pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)


def _draw_chessman_pos(screen, pos, stone_color):
    pygame.gfxdraw.aacircle(screen, pos[0], pos[1], Stone_Radius2, stone_color)
    pygame.gfxdraw.filled_circle(screen, pos[0], pos[1], Stone_Radius2, stone_color)

#  在后端输出
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
    imgText = font.render(text, True, fcolor)
    screen.blit(imgText, (x, y))

落子动作函数的实现 #

通过pygame库获取鼠标的点击位置,并根据棋盘建立时设置的长、宽、高将其转换为棋盘上的坐标,从而方便进行棋子的绘制。

#######################在五子棋2的_draw_chessman_pos()函数后面添加以下代码作为新的功能函数########
# 获取鼠标点击位置,传入参数为pygame库获取的鼠标点击位置
def _get_clickpoint(click_pos):
    pos_x = click_pos[0] - Start_X # 点击的位置在棋盘中的横坐标
    pos_y = click_pos[1] - Start_Y # 点击的位置在棋盘中的纵坐标
    if pos_x < -Inside_Width or pos_y < -Inside_Width: # 若越界
        return None
    x = pos_x // SIZE # 以棋子的大小为单位计算
    y = pos_y // SIZE
    # 修正点击位置,当用户点击位置与交点有偏差时自动修正
    if pos_x % SIZE > Stone_Radius:
        x += 1
    if pos_y % SIZE > Stone_Radius:
        y += 1
    if x >= Line_Points or y >= Line_Points: # 恰好在中间位置时不修正
        return None

    return Point(x, y) # 返回游戏区的坐标

小结 #

本节介绍了五子棋棋子、动作函数实现和更新方法,需要掌握pygame的调用方法,以及棋子动作交互功能的实现