import pygame
import sys
import random

pygame.init()
WIDTH, HEIGHT = 480, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("向上抽纸巾｜空格大力抽纸｜修复空格生效")
clock = pygame.time.Clock()

# 颜色
WHITE = (255, 255, 255)
BROWN = (139, 90, 43)
BLACK = (20, 20, 20)
GRAY = (160, 160, 160)
RED = (200, 30, 30)
BLUE = (40, 120, 220)

# 字体兼容海龟编辑器
try:
    font = pygame.font.SysFont("simhei", 24)
    font_small = pygame.font.SysFont("simhei", 18)
except:
    font = pygame.font.Font(None, 24)
    font_small = pygame.font.Font(None, 18)

# ========== 音效加载（没有文件不会崩溃） ==========
sound_pull = None
sound_tear = None
try:
    sound_pull = pygame.mixer.Sound("pull.wav")
    sound_tear = pygame.mixer.Sound("tear.wav")
    sound_pull.set_volume(0.4)
    sound_tear.set_volume(0.6)
except Exception:
    print("未找到音效文件，静音运行")

# 卷筒参数
roll_x = WIDTH // 2
roll_y = 580
roll_radius = 60

# 游戏参数
paper_max_length = 420
current_length = 0
is_drag = False
start_mouse_y = 0
score = 0

# 阻力参数
drag_force = 0.0
max_resistance = 8.5

# 撕裂动画参数
is_tearing = False
tear_timer = 0
tear_duration = 35
screen_shake = (0, 0)

# 空格状态变量（重点修复！）
space_pressed = False

def reset_game():
    global current_length, drag_force, is_tearing, tear_timer, screen_shake
    current_length = 0
    drag_force = 0
    is_tearing = False
    tear_timer = 0
    screen_shake = (0, 0)

running = True
while running:
    clock.tick(60)
    screen.fill(WHITE)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # 按下空格标记
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                space_pressed = True
        # 松开空格取消标记
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                space_pressed = False

        # 鼠标按下
        if event.type == pygame.MOUSEBUTTONDOWN and not is_tearing:
            if event.button == 1:
                is_drag = True
                start_mouse_y = event.pos[1]

        # 鼠标松开
        if event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                is_drag = False
                # 完全抽出，触发撕裂
                if current_length >= paper_max_length and not is_tearing:
                    is_tearing = True
                    tear_timer = tear_duration
                    if sound_tear:
                        sound_tear.play()

    mx, my = pygame.mouse.get_pos()

    # ========== 拖拽物理逻辑【修复空格生效】 ==========
    if is_drag and not is_tearing:
        mouse_delta = start_mouse_y - my
        if mouse_delta > 0:
            resist_ratio = current_length / paper_max_length
            resistance = 1 + resist_ratio * max_resistance
            base_speed = 0.22

            # 按住空格，抽取速度大幅提升
            if space_pressed:
                base_speed = 0.48

            add_len = mouse_delta * base_speed / resistance
            current_length += add_len
            current_length = min(current_length, paper_max_length)
            drag_force += abs(mouse_delta) * 0.01
            # 播放抽纸音效（间断播放）
            if sound_pull and drag_force > 3:
                sound_pull.play()
                drag_force = 0
        start_mouse_y = my

    # ========== 撕裂动画倒计时 ==========
    if is_tearing:
        tear_timer -= 1
        shrink_speed = 6
        current_length -= shrink_speed
        # 撕裂时屏幕震动
        shake_x = random.randint(-4, 4)
        shake_y = random.randint(-4, 4)
        screen_shake = (shake_x, shake_y)
        if current_length < 0 or tear_timer <= 0:
            score += 1
            reset_game()
    else:
        screen_shake = (0, 0)

    # 创建临时画布实现震动
    display_surface = pygame.Surface((WIDTH, HEIGHT))

    # ========== 绘制卷筒 ==========
    pygame.draw.circle(display_surface, BROWN, (roll_x, roll_y), roll_radius)
    pygame.draw.circle(display_surface, BLACK, (roll_x, roll_y), 12)

    # ========== 绘制纸巾 + 强化撕裂效果 ==========
    top_y = roll_y - current_length
    paper_w = 84
    paper_left = roll_x - paper_w//2

    if current_length > 0:
        # 纸巾主体
        rect = [paper_left, top_y, paper_w, current_length]
        pygame.draw.rect(display_surface, (245,245,245), rect)
        pygame.draw.rect(display_surface, GRAY, rect, 2)

        # 纸巾横线纹理
        for l in range(0, int(current_length), 28):
            line_y = roll_y - l
            pygame.draw.line(display_surface, GRAY, (paper_left+4, line_y), (paper_left+paper_w-4, line_y),1)

        # 撕裂动画：更多锯齿裂痕！强化特效
        if is_tearing:
            crack_y = top_y
            for i in range(10):
                offset_x = random.randint(-18,18)
                pygame.draw.line(display_surface, RED,
                    (roll_x-38 + offset_x, crack_y+i*5),
                    (roll_x+38 - offset_x, crack_y+i*5+5), 3)

    # ========== UI文字 ==========
    text1 = font.render("鼠标向上拖动抽纸 | 按住空格大力抽！", True, BLACK)
    text2 = font.render(f"得分：{score}", True, BLACK)
    display_surface.blit(text1, (40, 20))
    display_surface.blit(text2, (40, 55))

    if space_pressed and is_drag and not is_tearing:
        space_tip = font.render("【全力拉动中】", True, BLUE)
        display_surface.blit(space_tip, (60, 120))

    if current_length >= paper_max_length - 80 and not is_tearing:
        warn = font.render("阻力暴涨！用力拖动！", True, RED)
        display_surface.blit(warn, (60, 90))

    if is_tearing:
        tip_tear = font.render("撕裂！！", True, RED)
        display_surface.blit(tip_tear, (180, 120))

    # 震动偏移输出到屏幕
    screen.blit(display_surface, screen_shake)
    pygame.display.flip()

pygame.quit()
sys.exit()