Implementación de Gomoku a través de pygame (Gomoku)

Un estudiante universitario desconocido, conocido como Caigou en el mundo de las artes marciales.
Autor original: Jacky Li.
Correo electrónico: [email protected]
. Última edición: 2022.11.30.

Tabla de contenido

Implementación de Gomoku a través de pygame (Gomoku)

Introducción al backgammon

1: visualización de efectos

Dos: configuración requerida 

Tres: visualización de código

1.Parámetros del marco del tablero de ajedrez

2. Dibuja un tablero de ajedrez

3. Dibuja piezas de ajedrez

4. Cómo jugar ajedrez en el lado de la IA

5.Juez de victoria

Cuatro: perspectiva de valor

1. Jugar al backgammon es una forma de entretenimiento para cultivar tu cuerpo y mejorar tu salud física y mental.

2. Jugar al backgammon tiene el efecto de fortalecer el cerebro y aumentar la inteligencia.

3. El backgammon tiene una buena función de regulación de la psicología.

El autor tiene algo que decir.


Implementación de Gomoku a través de pygame (Gomoku)

Introducción al backgammon

        El backgammon se originó en China y es uno de los eventos competitivos de los Juegos Intelectuales Nacionales. Es un juego de ajedrez puramente estratégico que se juega entre dos personas. Ambos bandos utilizan piezas de ajedrez blancas y negras respectivamente y las colocan en la intersección de las líneas recta y horizontal del tablero. El primero en formar una secuencia de cinco piezas gana. El backgammon es fácil de aprender, apto para todas las edades, divertido y atractivo. No sólo mejora la capacidad de pensamiento y la inteligencia, sino que también es rico en filosofía y ayuda a cultivar el carácter moral.

1: visualización de efectos

 

 

Dos: configuración requerida 

pygame

aleatorio

sistema

Tres: visualización de código

1.Parámetros del marco del tablero de ajedrez

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)

2. Dibuja un tablero de ajedrez

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)

3. Dibuja piezas de ajedrez

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)

4. Cómo jugar ajedrez en el lado de la IA

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

5.Juez de victoria

    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

Cuatro: perspectiva de valor

1. Jugar al backgammon es una forma de entretenimiento para cultivar tu cuerpo y mejorar tu salud física y mental.


Jugar al backgammon presta atención a la ética y el estilo del ajedrez y a tratar a los demás con cortesía. Los europeos llaman al backgammon "ajedrez de caballeros", lo que significa que los jugadores que juegan al backgammon deben tener el comportamiento y el temperamento de un caballero. Jugar al ajedrez un movimiento a la vez es como vivir una vida real paso a paso. El backgammon no requiere mucho tiempo y es muy interesante. Si estás interesado, estarás de buen humor. Por tanto, tiene buenos efectos de prevención y control de la neurastenia, la ansiedad, la depresión y el TDAH.


2. Jugar al backgammon tiene el efecto de fortalecer el cerebro y aumentar la inteligencia.


Jugar al ajedrez puede fortalecer tu cerebro y mejorar tu capacidad de pensamiento. La persistencia en jugar backgammon no sólo puede mejorar la velocidad de las actividades intelectuales, sino también mejorar la capacidad de resolver problemas desde diferentes ángulos y la originalidad en el razonamiento lógico. Esto también es muy útil para desarrollar la inteligencia de niños en edad preescolar y estudiantes de primaria y secundaria.


3. El backgammon tiene una buena función de regulación de la psicología.


Algunas personas suelen quejarse de mala memoria, y el motivo suele ser la falta de concentración. Jugar al backgammon ayuda a mejorar la concentración. Cuando se juega al ajedrez, "una mente no puede hacer dos cosas". La concentración puede mejorar el orden de las actividades de las células cerebrales y, al mismo tiempo, promover una regulación benigna del pensamiento, las actividades psicológicas, el sistema circulatorio y el sistema respiratorio de las personas.
 

El autor tiene algo que decir.

Si necesita el código, envíe un mensaje privado al blogger y él le responderá después de verlo.

Si cree que lo que dijo el blogger es útil para usted, haga clic en "Seguir" para apoyarlo. Continuaremos actualizando dichos problemas...

Supongo que te gusta

Origin blog.csdn.net/weixin_62075168/article/details/128116286
Recomendado
Clasificación