欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python PyGame五子棋小游戏

程序员文章站 2022-03-07 14:05:43
目录前言五子棋小游戏1、简介2、环境准备3、初始化环境4、棋盘5、黑白棋子6、对局信息7、ai8、完善总结前言pygame 是一个专门设计来进行游戏开发设计的 python 模块,允许实时电子游戏研发...

前言

pygame 是一个专门设计来进行游戏开发设计的 python 模块,允许实时电子游戏研发而无需被低级语言(如机器语言和汇编语言)束缚,使用起来非常的简单,非常适合新手拿来玩耍,本教程源码均基于 python 3.x 版本。

五子棋小游戏

1、简介

五子棋是我们小时候经常玩的两人对弈策略小游戏,规则简单:

1、对局双方各执一色棋子,常为黑白两色;2、空棋盘开局;3、黑先、白后,交替下子,每次只能下一子;4、棋子下在棋盘的空白点上,棋子下定后,不得向其它点移动,不得从棋盘上拿掉或拿起另落别处;5、黑方的第一枚棋子可下在棋盘任意交叉点上;6、轮流下子是双方的权利,但允许任何一方放弃下子权,先形成5子连线者获胜;

五子棋容易上手,规则简单,老少皆宜,而且趣味横生,引人入胜。它不仅能增强思维能力,提高智力,而且富含哲理,有助于修身养性。

2、环境准备

本次教程需要提前安装好 python 3.x 环境以及 pygame 模块,python 环境建议安装 anaconda 以及 jupyter,对于新手比较友好!

pip install jupyter
pip install pygame

安装好 pygame 模块之后,咱们就可以正式开写了!

3、初始化环境

首先需要引入以下模块:

import sys
import random
import pygame
from pygame.locals import *
import pygame.gfxdraw
from collections import namedtuple

接着我们初始化棋盘的一些变量,便于下面写代码:

chessman = namedtuple('chessman', 'name value color')
point = namedtuple('point', 'x y')

black_chessman = chessman('黑子', 1, (45, 45, 45))
white_chessman = chessman('白子', 2, (219, 219, 219))

offset = [(1, 0), (0, 1), (1, 1), (1, -1)]

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  # 游戏屏幕的宽

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)

right_info_pos_x = screen_height + stone_radius2 * 2 + 10

4、棋盘

通过上述变量画出棋盘,主要源码如下:

# 画棋盘
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)

5、黑白棋子

有了棋盘当然少不了黑白棋子,比较简单:

# 画棋子
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)

6、对局信息

每一局游戏不可缺少的就是双方玩家的对局信息,主要展示双方的黑白执子以及战况,关键源码如下:

# 画左侧信息显示
def _draw_left_info(screen, font, cur_runner, black_win_count, white_win_count):
    _draw_chessman_pos(screen, (screen_height + stone_radius2, start_x + stone_radius2), black_chessman.color)
    _draw_chessman_pos(screen, (screen_height + stone_radius2, start_x + stone_radius2 * 4), white_chessman.color)

    print_text(screen, font, right_info_pos_x, start_x + 3, '玩家', blue_color)
    print_text(screen, font, right_info_pos_x, start_x + stone_radius2 * 3 + 3, '电脑', blue_color)

    print_text(screen, font, screen_height, screen_height - stone_radius2 * 8, '战况:', blue_color)
    _draw_chessman_pos(screen, (screen_height + stone_radius2, screen_height - int(stone_radius2 * 4.5)), black_chessman.color)
    _draw_chessman_pos(screen, (screen_height + stone_radius2, screen_height - stone_radius2 * 2), white_chessman.color)
    print_text(screen, font, right_info_pos_x, screen_height - int(stone_radius2 * 5.5) + 3, f'{black_win_count} 胜', blue_color)
    print_text(screen, font, right_info_pos_x, screen_height - stone_radius2 * 3 + 3, f'{white_win_count} 胜', blue_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)

画出来的整体效果如下:

python PyGame五子棋小游戏

至此,整个棋盘的布局就完成了!

7、ai

由于咱们的小游戏不可以联机,因此大部分时间应该都是人机对下,这样就需要引入 ai 人机,让电脑作为对手陪我们下棋,主要源码如下:

class ai:
    def __init__(self, line_points, chessman):
        self._line_points = line_points
        self._my = chessman
        self._opponent = black_chessman if chessman == white_chessman else white_chessman
        self._checkerboard = [[0] * line_points for _ in range(line_points)]

    def get_opponent_drop(self, point):
        self._checkerboard[point.y][point.x] = self._opponent.value

    def ai_drop(self):
        point = none
        score = 0
        for i in range(self._line_points):
            for j in range(self._line_points):
                if self._checkerboard[j][i] == 0:
                    _score = self._get_point_score(point(i, j))
                    if _score > score:
                        score = _score
                        point = point(i, j)
                    elif _score == score and _score > 0:
                        r = random.randint(0, 100)
                        if r % 2 == 0:
                            point = point(i, j)
        self._checkerboard[point.y][point.x] = self._my.value
        return point

    def _get_point_score(self, point):
        score = 0
        for os in offset:
            score += self._get_direction_score(point, os[0], os[1])
        return score

    def _get_direction_score(self, point, x_offset, y_offset):
        count = 0   # 落子处我方连续子数
        _count = 0  # 落子处对方连续子数
        space = none   # 我方连续子中有无空格
        _space = none  # 对方连续子中有无空格
        both = 0    # 我方连续子两端有无阻挡
        _both = 0   # 对方连续子两端有无阻挡

        # 如果是 1 表示是边上是我方子,2 表示敌方子
        flag = self._get_stone_color(point, x_offset, y_offset, true)
        if flag != 0:
            for step in range(1, 6):
                x = point.x + step * x_offset
                y = point.y + step * y_offset
                if 0 <= x < self._line_points and 0 <= y < self._line_points:
                    if flag == 1:
                        if self._checkerboard[y][x] == self._my.value:
                            count += 1
                            if space is false:
                                space = true
                        elif self._checkerboard[y][x] == self._opponent.value:
                            _both += 1
                            break
                        else:
                            if space is none:
                                space = false
                            else:
                                break   # 遇到第二个空格退出
                    elif flag == 2:
                        if self._checkerboard[y][x] == self._my.value:
                            _both += 1
                            break
                        elif self._checkerboard[y][x] == self._opponent.value:
                            _count += 1
                            if _space is false:
                                _space = true
                        else:
                            if _space is none:
                                _space = false
                            else:
                                break
                else:
                    # 遇到边也就是阻挡
                    if flag == 1:
                        both += 1
                    elif flag == 2:
                        _both += 1

        if space is false:
            space = none
        if _space is false:
            _space = none

        _flag = self._get_stone_color(point, -x_offset, -y_offset, true)
        if _flag != 0:
            for step in range(1, 6):
                x = point.x - step * x_offset
                y = point.y - step * y_offset
                if 0 <= x < self._line_points and 0 <= y < self._line_points:
                    if _flag == 1:
                        if self._checkerboard[y][x] == self._my.value:
                            count += 1
                            if space is false:
                                space = true
                        elif self._checkerboard[y][x] == self._opponent.value:
                            _both += 1
                            break
                        else:
                            if space is none:
                                space = false
                            else:
                                break   # 遇到第二个空格退出
                    elif _flag == 2:
                        if self._checkerboard[y][x] == self._my.value:
                            _both += 1
                            break
                        elif self._checkerboard[y][x] == self._opponent.value:
                            _count += 1
                            if _space is false:
                                _space = true
                        else:
                            if _space is none:
                                _space = false
                            else:
                                break
                else:
                    # 遇到边也就是阻挡
                    if _flag == 1:
                        both += 1
                    elif _flag == 2:
                        _both += 1

        score = 0
        if count == 4:
            score = 10000
        elif _count == 4:
            score = 9000
        elif count == 3:
            if both == 0:
                score = 1000
            elif both == 1:
                score = 100
            else:
                score = 0
        elif _count == 3:
            if _both == 0:
                score = 900
            elif _both == 1:
                score = 90
            else:
                score = 0
        elif count == 2:
            if both == 0:
                score = 100
            elif both == 1:
                score = 10
            else:
                score = 0
        elif _count == 2:
            if _both == 0:
                score = 90
            elif _both == 1:
                score = 9
            else:
                score = 0
        elif count == 1:
            score = 10
        elif _count == 1:
            score = 9
        else:
            score = 0

        if space or _space:
            score /= 2

        return score

    # 判断指定位置处在指定方向上是我方子、对方子、空
    def _get_stone_color(self, point, x_offset, y_offset, next):
        x = point.x + x_offset
        y = point.y + y_offset
        if 0 <= x < self._line_points and 0 <= y < self._line_points:
            if self._checkerboard[y][x] == self._my.value:
                return 1
            elif self._checkerboard[y][x] == self._opponent.value:
                return 2
            else:
                if next:
                    return self._get_stone_color(point(x, y), x_offset, y_offset, false)
                else:
                    return 0
        else:
            return 0

8、完善

最后就是对规则的一些完善,比如落子,判断输赢以及胜利界面之类的编写,关键源码如下:

class checkerboard:
    def __init__(self, line_points):
        self._line_points = line_points
        self._checkerboard = [[0] * line_points for _ in range(line_points)]

    def _get_checkerboard(self):
        return self._checkerboard

    checkerboard = property(_get_checkerboard)

    # 判断是否可落子
    def can_drop(self, point):
        return self._checkerboard[point.y][point.x] == 0

    def drop(self, chessman, point):
        """
        落子
        :param chessman:
        :param point:落子位置
        :return:若该子落下之后即可获胜,则返回获胜方,否则返回 none
        """
        print(f'{chessman.name} ({point.x}, {point.y})')
        self._checkerboard[point.y][point.x] = chessman.value

        if self._win(point):
            print(f'{chessman.name}获胜')
            return chessman

    # 判断是否赢了
    def _win(self, point):
        cur_value = self._checkerboard[point.y][point.x]
        for os in offset:
            if self._get_count_on_direction(point, cur_value, os[0], os[1]):
                return true

    def _get_count_on_direction(self, point, value, x_offset, y_offset):
        count = 1
        for step in range(1, 5):
            x = point.x + step * x_offset
            y = point.y + step * y_offset
            if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
                count += 1
            else:
                break
        for step in range(1, 5):
            x = point.x - step * x_offset
            y = point.y - step * y_offset
            if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
                count += 1
            else:
                break

        return count >= 5

至此,整个游戏就已经制作完成,下面我们可以试玩一下:

python PyGame五子棋小游戏

说来惭愧,竟不敌人机,再来一局,胜天半子,终于赢了!

python PyGame五子棋小游戏

总结

到此这篇关于python pygame五子棋小游戏的文章就介绍到这了,更多相关python pygame五子棋内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!