You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Pygame俄罗斯方块实现DAS延迟自动移位按键处理问题

不需要引入第三方模块,用Pygame自带的时间戳和事件机制即可实现DAS功能,核心逻辑是自主跟踪按键按下时长,不要依赖系统默认的按键重复或逐帧检测的连续移动。

实现思路
  1. 预先定义状态变量,跟踪方向键的按下状态和时长:
import pygame

# 常量定义
DAS_THRESHOLD = 133  # DAS触发阈值,单位毫秒
SCREEN_LEFT_BOUND = 0  # 方块左移的边界值,根据你的游戏实际坐标调整
SCREEN_RIGHT_BOUND = 9  # 方块右移的边界值,根据你的游戏格子数调整

# 方向键状态跟踪变量
left_press_start = None
left_das_triggered = False
right_press_start = None
right_das_triggered = False
  1. 在事件循环中处理KEYDOWN、KEYUP事件,记录按键按下时间,触发单次移动:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        exit()
    # 处理按键按下
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            left_press_start = pygame.time.get_ticks()
            left_das_triggered = False
            # 短按触发单次移动
            if piece.x > SCREEN_LEFT_BOUND:
                piece.x -= 1
        if event.key == pygame.K_RIGHT:
            right_press_start = pygame.time.get_ticks()
            right_das_triggered = False
            # 短按触发单次移动
            if piece.x < SCREEN_RIGHT_BOUND:
                piece.x += 1
    # 处理按键松开
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT:
            left_press_start = None
            left_das_triggered = False
        if event.key == pygame.K_RIGHT:
            right_press_start = None
            right_das_triggered = False
  1. 在主循环的每帧逻辑中检测按键按住时长,触发DAS自动移到边缘:
# 每帧检测左方向键DAS
if left_press_start is not None and not left_das_triggered:
    hold_time = pygame.time.get_ticks() - left_press_start
    if hold_time >= DAS_THRESHOLD:
        # 直接移到左边缘
        piece.x = SCREEN_LEFT_BOUND
        left_das_triggered = True

# 每帧检测右方向键DAS
if right_press_start is not None and not right_das_triggered:
    hold_time = pygame.time.get_ticks() - right_press_start
    if hold_time >= DAS_THRESHOLD:
        # 直接移到右边缘
        piece.x = SCREEN_RIGHT_BOUND
        right_das_triggered = True
原方案问题说明
  • 第一种监听KEYDOWN的方案,默认Pygame未开启按键重复,即使通过pygame.key.set_repeat()开启,也只能实现逐格重复移动,无法做到触发阈值后直接跳到边缘的效果
  • 第二种逐帧调用key.get_pressed()的方案,会每帧触发移动,和游戏帧率强绑定,无法区分短按和长按,调整帧率会影响全局游戏流畅度

内容的提问来源于stack exchange,提问作者Rabinzel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:06:05