棋盘游戏(围棋、五子棋、棋盘)

棋盘游戏(围棋、五子棋、棋盘)围棋小游戏,五子棋也可以_pygame围棋

大家好,欢迎来到IT知识分享网。


import pygame
import random

font = "./font/方正像素12.TTF"
gamename = '全仿真棋盘'

WIN_WIDTH = 1000  # 窗口宽度
WIN_HEIGHT = 694  # 窗口高度

# 初始化游戏
pygame.init()
pygame.mixer.init()

window = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))  # 创建窗口
pygame.display.set_caption(gamename)  # 设置title
pygame.display.flip()  # 初始化后第一次更新窗口

# board_image = pygame.image.load("./imgs/board.png").convert_alpha()
# board_image = pygame.transform.scale(board_image, (700, 694))

clock = pygame.time.Clock()
game_exit = False


def draw_board(screen, distance1, num=19):

    # window.blit(board_image, (0, 0))

    # 设置线条颜色
    line_color = bgc[1]

    # 绘制线条
    for i in range(0, num):
        pygame.draw.line(screen, line_color, (distance1,
                         distance1 * (i+1)), (distance1 * num, distance1 * (i+1)))
        pygame.draw.line(screen, line_color, (distance1 * (i+1),
                         distance1), (distance1 * (i+1), distance1 * num))

    # 设置星位颜色
    star_color = (0, 0, 0)

    # 绘制星位
    star_points = []
    if num == 9:
        star_points = [(3, 3), (3, 7), (3, 5),
                       (7, 3), (7, 7), (7, 5), (5, 3), (5, 7), (5, 5)]
    elif num == 13:
        star_points = [(4, 4), (4, 10), (4, 7), (10, 4),
                       (10, 10), (10, 7), (7, 4), (7, 10), (7, 7)]
    else:
        star_points = [(4, 4), (4, 10), (4, 16), (10, 4), (10, 10),
                       (10, 16), (16, 4), (16, 10), (16, 16)]

    for point in star_points:
        pygame.draw.circle(screen, star_color, (distance1 *
                           point[0], distance1 * point[1]), distance1/4-distance1/23*1.1)


def draw_button(text, x, y, font_size=20, btn_size="auto", color="black", bg_color="white"):
    font1 = pygame.font.Font(font, font_size)
    text_surface = font1.render(text, True, color)
    text_rect = text_surface.get_rect()

    if btn_size == "auto":
        # 自动调整按钮大小
        width = text_rect.width + font_size
        height = text_rect.height + font_size // 2
    else:
        width, height = btn_size
    # 创建一个矩形对象
    button_rect = pygame.Rect(x, y, width, height)
    # 绘制矩形
    pygame.draw.rect(window, bg_color, (x, y, width, height))

    # 填充文本
    text_x = x + (width - text_rect.width) // 2
    text_y = y + (height - text_rect.height) // 2
    window.blit(text_surface, (text_x, text_y))
    return button_rect


font2 = pygame.font.Font(font, 20)


def fillText(text, x, y, font_size=20, font_color=(0, 0, 0)):
    global font2
    if font_size != 20:
        font2 = pygame.font.Font(font, font_size)
    # f = pygame.font.Font(font_, font_size)
    te = font2.render(text, True, font_color)
    window.blit(te, (x, y))


black1 = 0
white1 = 0


def log(text):
    global log_list
    log_list.append(text)
    print(f"系统: {text}")


class Chess:
    def __init__(self, screen, x, y, color):
        self.x = x+random.randint(-2, 2)
        self.y = y+random.randint(-2, 2)
        if color == "black":
            self.color = (0, 0, 0)
        else:
            self.color = color
        self.screen = screen
        self.qi = 4
        self.size = 8*distance/17

    def show(self):

        pygame.draw.circle(self.screen, self.color,
                           (self.x, self.y), self.size)
        pygame.draw.circle(self.screen, (self.color[0]+10, self.color[1]+10, self.color[2]+10),
                           (self.x-self.size/3, self.y-self.size/3), self.size/2)
        pygame.draw.circle(self.screen, (255, 255, 255),
                           (self.x-self.size/3-self.size/9, self.y-self.size/3-self.size/9), self.size/4)


def draw_cross(screen, x, y, color, size=15):
    pygame.draw.line(screen, color, (x-size, y), (x+size, y), 5)
    pygame.draw.line(screen, color, (x, y+size), (x, y-size), 5)


def draw_cha(x, y):
    # pygame.draw.circle(window, "red", (x, y), 15, 2)
    aa = ((8*distance/17)+(8*distance/17)/3)/2
    pygame.draw.line(window, "red", (x-aa, y-aa), (x+aa, y+aa), 3)
    pygame.draw.line(window, "red", (x+aa, y-aa), (x-aa, y+aa), 3)


def draw_info():
    global log_list, white1, black1

    if pan_inf == 19:
        for i in range(1, 20):
            fillText(str(i), 34.5*i, 15)
            fillText(str(i), 15, 34*i*1.01)

    pygame.draw.rect(window, "white", (730, 200, 200, 300))
    for i in range(len(log_list)):
        fillText(log_list[i], 740, 205+i*32, 20)
        # print(log_list[i])
    if len(log_list) >= 10:
        log_list.pop(0)

    fillText(f"黑子:{black1}\n白子:{white1}", 740, 600, font_color=bgc[1])
    black1, white1 = 0, 0
    for i in chess_dic:
        if type(chess_dic[i]) == Chess and chess_dic[i].color == (0, 0, 0):
            black1 += 1
        elif type(chess_dic[i]) == Chess and chess_dic[i].color == (232, 232, 232):
            white1 += 1

        if not is_tizi:
            # 落点预判
            if i[0]+(distance//2) > e_x > i[0]-(distance//2) and i[1]+(distance//2) > e_y > i[1]-(distance//2) and chess_dic[i] == -1:
                if is_black_turn:
                    chess_dic[i] = ("black_show", i[0], i[1])
                else:
                    chess_dic[i] = ("white_show", i[0], i[1])
            elif type(chess_dic[i]) != Chess:
                if i[0]+(distance//2) > e_x > i[0]-(distance//2) and i[1]+(distance//2) > e_y > i[1]-(distance//2):
                    pass
                else:
                    chess_dic[i] = -1

        # 画出盘面信息
        if chess_dic[i] == -1:
            continue
        elif type(chess_dic[i]) == Chess:
            Chess.show(chess_dic[i])
        elif chess_dic[i][0] == "black_show" and is_tizi == False:
            draw_cross(window, chess_dic[i][1],
                       chess_dic[i][2], "black", 8*distance/17)
        elif chess_dic[i][0] == "white_show" and is_tizi == False:
            draw_cross(window, chess_dic[i][1],
                       chess_dic[i][2], (232, 232, 232), 8*distance/17)

        if is_tizi:
            if i[0]+(distance//2) > e_x > i[0]-(distance//2) and i[1]+(distance//2) > e_y > i[1]-(distance//2) and type(chess_dic[i]) == Chess:
                draw_cha(chess_dic[(i[0], i[1])].x, chess_dic[(i[0], i[1])].y)
    # fillText("648ms")


def del_chess():
    for i in chess_dic:
        if i[0]+(distance//2) > e_x > i[0]-(distance//2) and i[1]+(distance//2) > e_y > i[1]-(distance//2) and type(chess_dic[i]) == Chess:
            log(f"提子:{(int((i[0]-distance)/distance),int((i[1]-distance)/distance))} ")
            chess_dic[i] = -1


def fall_fruit(black: bool, last_pos):
    for i in chess_dic:
        x, y = i[0], i[1]
        if (x - distance//2) < e_x < (x + distance//2) and (y - distance//2) < e_y < (y + distance//2):
            if not isinstance(chess_dic[i], Chess):
                if black:
                    chess_dic[i] = Chess(window, x, y, "black")
                    log(f"黑方落子:{(int(x//distance), int(y//distance))}")
                else:
                    chess_dic[i] = Chess(window, x, y, (232, 232, 232))
                    log(f"白方落子:{(int(x//distance), int(y//distance))}")
                last_pos.append((x, y))
                return True
    return False


def randomcolor():
    r, g, b = (random.randint(0, 255), random.randint(
        0, 255), random.randint(0, 255))
    r1, g1, b1 = (255-r, 255-g, 255-b)
    return [(r, g, b), (r1, g1, b1)]


# 76, 255, 253
# 255, 145, 76


def close_pic():
    a, b = randomcolor()
    window.fill(a)
    fillText("正在关闭...", (WIN_WIDTH - 100*5)/2,
             (WIN_HEIGHT-100)/2-50, 100, b)


def init_chess_dic(num=19, distance1=35):
    global last_pos, log_list, pan_inf, chess_dic, is_black_turn
    is_black_turn = True
    pan_inf = num
    last_pos = []
    log_list = []
    po_x11 = distance1
    po_y11 = distance1
    chess_dic = {(round(po_x11 + distance1 * i), round(po_y11 + distance1 * j)): -1
                 for i in range(num) for j in range(num)}


chess_dic = {}

init_chess_dic(19, 35)

is_black_turn = True

auto_change_turn = True
is_tizi = False
last_pos = []


# 双击间隔时间阈值
DOUBLE_CLICK_THRESHOLD = 400

# 双击计数器
double_click_counter = 0
last_click_time = 0

morenbgc = [(214, 197, 127), (41, 58, 128)]
bgc = morenbgc

log_list = []
pan_inf = 19
index = 0


while not game_exit:


    window.fill(bgc[0])
    if index >= 99999:
        index = 0
    else:
        index += 1
    if index % 20 == 0:
        # print()
        pass
    distance = 665/pan_inf
    e_x, e_y = pygame.mouse.get_pos()
    draw_board(window, distance, pan_inf)
    # 画出盘面信息

    # 画出按钮
    morenbgc_btn = draw_button("默认", 870, 560)
    bgc_btn = draw_button("更换背景颜色", 732, 560)
    back_btn = draw_button("悔棋", 740, 30, btn_size=(70, 31))
    if is_tizi:
        player_white_btn = draw_button("白子", 830, 80, btn_size=(90, 31))
        player_black_btn = draw_button("黑子", 740, 80, btn_size=(70, 31))
    elif is_black_turn:
        player_black_btn = draw_button(
            "黑子", 740, 80, btn_size=(70, 31), bg_color=(121, 188, 195))
        player_white_btn = draw_button("白子", 830, 80, btn_size=(90, 31))
    else:
        player_black_btn = draw_button("黑子", 740, 80, btn_size=(70, 31))
        player_white_btn = draw_button(
            "白子", 830, 80, btn_size=(90, 31), bg_color=(121, 188, 195))

    if is_tizi:
        tizi_btn = draw_button("提子(t)", 830, 30, bg_color="green")
    else:
        tizi_btn = draw_button("提子(t)", 830, 30, bg_color=(112, 112, 112))

    if len(last_pos) == 0:
        qingpan_btn = draw_button(
            "清空棋盘(双击)", 740, 650, bg_color=(112, 112, 112))
    else:
        qingpan_btn = draw_button("清空棋盘(双击)", 740, 650)
    if auto_change_turn:
        auto_chang_turn_btn = draw_button(
            "自动更换落子颜色", 740, 130, bg_color="green")
    else:
        auto_chang_turn_btn = draw_button("自动更换落子颜色", 740, 130, bg_color="red")

    if pan_inf == 19:
        pan_19 = draw_button("19路", 730, 520, bg_color="green")
        pan_13 = draw_button("13路", 805, 520)
        pan_9 = draw_button("9路", 880, 520)
    elif pan_inf == 13:
        pan_19 = draw_button("19路", 730, 520)
        pan_13 = draw_button("13路", 805, 520, bg_color="green")
        pan_9 = draw_button("9路", 880, 520)
    if pan_inf == 9:
        pan_19 = draw_button("19路", 730, 520)
        pan_13 = draw_button("13路", 805, 520)
        pan_9 = draw_button("9路", 880, 520, bg_color="green")
    draw_info()

    # 游戏事件检测
    for event in pygame.event.get():
        # 鼠标点击事件
        if event.type == pygame.MOUSEBUTTONDOWN:

            if back_btn.collidepoint(e_x, e_y) and len(last_pos) != 0:
                # 悔棋
                is_black_turn = not is_black_turn
                chess_dic[last_pos[-1]] = -1
                log(f"悔棋:{int((last_pos[-1][0]-distance)/distance),int((last_pos[-1][1]-distance)/distance)}")
                last_pos.pop()
            if morenbgc_btn.collidepoint(e_x, e_y):
                bgc = morenbgc
            if bgc_btn.collidepoint(e_x, e_y):
                bgc = randomcolor()
            if player_black_btn.collidepoint(e_x, e_y):
                is_black_turn = True
                is_tizi = False
            if player_white_btn.collidepoint(e_x, e_y):
                is_black_turn = False
                is_tizi = False
            if pan_19.collidepoint(e_x, e_y):
                pan_inf = 19
                distance = 665/pan_inf
                chess_dic.clear()
                init_chess_dic(pan_inf, distance)
            elif pan_13.collidepoint(e_x, e_y):
                pan_inf = 13
                distance = 665/pan_inf
                chess_dic.clear()
                init_chess_dic(pan_inf, distance)
            elif pan_9.collidepoint(e_x, e_y):
                pan_inf = 9
                distance = 665/pan_inf
                chess_dic.clear()
                init_chess_dic(pan_inf, distance)

            if auto_chang_turn_btn.collidepoint(e_x, e_y):
                auto_change_turn = not auto_change_turn
            if tizi_btn.collidepoint(e_x, e_y):
                is_tizi = not is_tizi

                # 检测鼠标左键双击事件
            current_time = pygame.time.get_ticks()
            if current_time - last_click_time < DOUBLE_CLICK_THRESHOLD:
                double_click_counter += 1
                # 清空盘面
                if qingpan_btn.collidepoint(e_x, e_y):
                    init_chess_dic(pan_inf, distance)
                # log(str((e_x, e_y)))
            else:
                double_click_counter = 1
            last_click_time = current_time

            # 落子
            if is_tizi:
                del_chess()
            else:
                is_fall = fall_fruit(is_black_turn, last_pos)
                if is_fall:
                    if auto_change_turn:
                        is_black_turn = not is_black_turn
                        # is_tizi = False
                    else:
                        # is_tizi = True
                        pass
        if event.type == pygame.KEYDOWN:
            keys = pygame.key.get_pressed()
            if event.key == pygame.K_t:
                is_tizi = True
            if keys[pygame.K_r] and keys[pygame.K_d] and keys[pygame.K_o] and keys[pygame.K_m] and keys[pygame.K_a] and keys[pygame.K_n]:
                for i in chess_dic:
                    if random.randint(0, 1) == 1:
                        chess_dic[i] = Chess(window, i[0], i[1], "black")
                    else:
                        chess_dic[i] = Chess(
                            window, i[0], i[1], (232, 232, 232))
            if keys[pygame.K_LMETA] and keys[pygame.K_z]:
                # 悔棋
                try:
                    chess_dic[last_pos[-1]] = -1
                    log(
                        f"悔棋:{int((last_pos[-1][0]-distance)/distance),int((last_pos[-1][1]-distance)/distance)}")
                    is_black_turn = not is_black_turn
                    last_pos.pop()
                except:
                    pass
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_t:
                is_tizi = False

        # 点X关闭窗口
        if event.type == pygame.QUIT:
            # 退出
            close_pic()
            game_exit = True
    distance = 665/pan_inf


    # 画面更新
    pygame.display.update()
    clock.tick(120)

pygame.quit()

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/27308.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信