惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
C
Check Point Blog
B
Blog RSS Feed
Y
Y Combinator Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
About on SuperTechFans
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 聂微东
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
小众软件
小众软件
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
GbyAI
GbyAI
The Cloudflare Blog
博客园 - 叶小钗
S
SegmentFault 最新的问题
博客园 - Franky
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
B
Blog
Jina AI
Jina AI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Pygame Snake, Pt. 6
David Newber · 2026-05-03 · via DEV Community

David Newberry

Currently, there is a subtle but real flaw in the controls for the game. If the player presses two keys in quick succession, only the last one is registered -- one, or more, are simply dropped.

You can see the effect easily if you lower the framerate to something extreme, e.g. 1 (i.e. 1 frame per second) by changing the clock.tick(20) line to clock.tick(1). If you quickly press down and then right, only right will be registered.

Thankfully, pygame makes it revlatively easy to fix this.

Inside the while loop -- i.e., for each frame -- we want to see if there are arrow keydown events to consume. If so, we want to move a step in each direction pressed. If no keydown events have occured, the snake should continue in last direction it was sent.

Above the for event... loop, add add a line to create an empty list:

    vels = []

Enter fullscreen mode Exit fullscreen mode

Then, inside the following conditional, instead of setting val = ..., add each arrow direction vector to the list:

            vels += [key_vel[event.key]]

Enter fullscreen mode Exit fullscreen mode

Everything from screen.fill("white") until (not including) pygame.quit() will be indented; because just above that, you should add:

    for vel in vels or [vel]:

Enter fullscreen mode Exit fullscreen mode

And that's it. When I first wrote the code I thought it was perfectly reasonable, and then after a while I got a bit confused. I lost track of vel being initialized at the top. It is both a global variable and a loop index in the above for loop. And it appears as part of the for loop's in expresion: or [vel], which provies the current value of vel if vels is empty. Its use as the for loop variable also has the effect of leaving vel with the value of the last element of vels when [one or more] arrow keys are pressed.

Full code as of now:

import pygame
import random

W = 30
H = 30
S = 20

# pygame setup
pygame.init()
screen = pygame.display.set_mode((W * S, H * S))
clock = pygame.time.Clock()
running = True

# game setup
snake = [pygame.Vector2(W / 2, H / 2)]
vel = pygame.Vector2(1, 0)

key_vel = {
    pygame.K_RIGHT: pygame.Vector2(1, 0),
    pygame.K_DOWN: pygame.Vector2(0, 1),
    pygame.K_LEFT: pygame.Vector2(-1, 0),
    pygame.K_UP: pygame.Vector2(0, -1)
}

grow = 3

def place_food():
    global food_pos
    food_pos = pygame.Vector2(
        random.randrange(W),
        random.randrange(H)
    )
    while food_pos in snake:
        food_pos = pygame.Vector2(
            random.randrange(W),
            random.randrange(H)
        )

place_food()

while running:
    # poll for events
    vels = []
    for event in pygame.event.get():
        # pygame.QUIT = user closed window
        if event.type == pygame.QUIT:
            running = False
            break
        elif event.type == pygame.KEYDOWN and event.key in key_vel:
            vels += [key_vel[event.key]]

    for vel in vels or [vel]:
        # fill buffer with white
        screen.fill("white")

        new_head = snake[-1] + vel

        if new_head in snake:
            print("hit self")
            running = False
            break

        if new_head == food_pos:
            grow += 1
            place_food()

        if new_head.x < 0:
            new_head.x = W - 1
        if new_head.x >= W:
            new_head.x = 0

        if new_head.y < 0:
            new_head.y = H - 1
        if new_head.y >= H:
            new_head.y = 0

        snake.append(new_head)

        if grow > 0:
            grow -= 1
        else:
            snake.pop(0)

        for dot in snake:
            square = pygame.Rect(dot * S, (S, S))
            screen.fill("black", square)

        square = pygame.Rect(food_pos * S, (S, S))
        screen.fill("green", square)

        # copy buffer to screen
        pygame.display.flip()

        # limits FPS
        clock.tick(20)

pygame.quit()

Enter fullscreen mode Exit fullscreen mode