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

pygame实现简单五子棋游戏

程序员文章站 2022-06-16 14:41:26
本文实例为大家分享了pygame实现简单五子棋游戏的具体代码,供大家参考,具体内容如下看代码:①gomuku2.py:import sysimport randomimport pygamefrom...

本文实例为大家分享了pygame实现简单五子棋游戏的具体代码,供大家参考,具体内容如下

看代码:

①gomuku2.py:

import sys
import random
import pygame
from pygame.locals import *
import pygame.gfxdraw
from checkerboard import checkerboard, black_chessman, white_chessman, offset, point

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


def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
    imgtext = font.render(text, true, fcolor)
    screen.blit(imgtext, (x, y))


def main():
    pygame.init()
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('五子棋')

    font1 = pygame.font.sysfont('simhei', 32)
    font2 = pygame.font.sysfont('simhei', 72)
    fwidth, fheight = font2.size('黑方获胜')

    checkerboard = checkerboard(line_points)
    cur_runner = black_chessman
    winner = none
    computer = ai(line_points, white_chessman)

    black_win_count = 0
    white_win_count = 0

    while true:
        for event in pygame.event.get():
            if event.type == quit:
                sys.exit()
            elif event.type == keydown:
                if event.key == k_return:
                    if winner is not none:
                        winner = none
                        cur_runner = black_chessman
                        checkerboard = checkerboard(line_points)
                        computer = ai(line_points, white_chessman)
            elif event.type == mousebuttondown:
                if winner is none:
                    pressed_array = pygame.mouse.get_pressed()
                    if pressed_array[0]:
                        mouse_pos = pygame.mouse.get_pos()
                        click_point = _get_clickpoint(mouse_pos)
                        if click_point is not none:
                            if checkerboard.can_drop(click_point):
                                winner = checkerboard.drop(cur_runner, click_point)
                                if winner is none:
                                    cur_runner = _get_next(cur_runner)
                                    computer.get_opponent_drop(click_point)
                                    ai_point = computer.ai_drop()
                                    winner = checkerboard.drop(cur_runner, ai_point)
                                    if winner is not none:
                                        white_win_count += 1
                                    cur_runner = _get_next(cur_runner)
                                else:
                                    black_win_count += 1
                        else:
                            print('超出棋盘区域')

        # 画棋盘
        _draw_checkerboard(screen)

        # 画棋盘上已有的棋子
        for i, row in enumerate(checkerboard.checkerboard):
            for j, cell in enumerate(row):
                if cell == black_chessman.value:
                    _draw_chessman(screen, point(j, i), black_chessman.color)
                elif cell == white_chessman.value:
                    _draw_chessman(screen, point(j, i), white_chessman.color)

        _draw_left_info(screen, font1, cur_runner, black_win_count, white_win_count)

        if winner:
            print_text(screen, font2, (screen_width - fwidth)//2, (screen_height - fheight)//2, winner.name + '获胜', red_color)

        pygame.display.flip()


def _get_next(cur_runner):
    if cur_runner == black_chessman:
        return white_chessman
    else:
        return black_chessman


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


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


# 根据鼠标点击位置,返回游戏区坐标
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)


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


if __name__ == '__main__':
    main()

②checkerboard.py:

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)]


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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关标签: pygame 五子棋