翻牌

import pygame
import random

# 初始化 Pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("翻牌游戏")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0)]

# 卡片参数
CARD_SIZE = 100
SPACING = 20
ROWS = 4
COLS = 4

# 生成卡片
cards = []
for color in COLORS * 2:  # 每种颜色生成两张
    cards.append({
        "color": color,
        "rect": pygame.Rect(0, 0, CARD_SIZE, CARD_SIZE),
        "flipped": False,
        "matched": False
    })

random.shuffle(cards)  # 打乱顺序

# 布局卡片
for i in range(ROWS * COLS):
    row = i // COLS
    col = i % COLS
    x = SPACING + col * (CARD_SIZE + SPACING)
    y = SPACING + row * (CARD_SIZE + SPACING)
    cards[i]["rect"].topleft = (x, y)

# 游戏循环
selected = []
clock = pygame.time.Clock()
running = True

while running:
    screen.fill(WHITE)

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            for card in cards:
                if card["rect"].collidepoint(pos) and not card["flipped"] and not card["matched"]:
                    card["flipped"] = True
                    selected.append(card)
                    if len(selected) == 2:
                        if selected[0]["color"] == selected[1]["color"]:
                            selected[0]["matched"] = True
                            selected[1]["matched"] = True
                        else:
                            pygame.time.wait(1000)  # 显示1秒后翻转回去
                            selected[0]["flipped"] = False
                            selected[1]["flipped"] = False
                        selected.clear()

    # 绘制卡片
    for card in cards:
        if card["matched"]:
            pygame.draw.rect(screen, card["color"], card["rect"])
        elif card["flipped"]:
            pygame.draw.rect(screen, card["color"], card["rect"])
        else:
            pygame.draw.rect(screen, BLACK, card["rect"])

    pygame.display.flip()
    clock.tick(30)

pygame.quit()

【三重旗艦館】 新北市三重區福德北路12號B1 02-2848-0587

【青埔夢想館】 桃園市大園區大成路二段100號2F 03-287-8015

 

Copyright © 2026 by 乒夢 Persist. All rights reserved.