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

Pygame报错:'Return'不在函数内及clock未定义问题求助

Fixing Your Pygame Indentation and Audio Issues

Let's walk through fixing your errors and getting your game (with music) running properly:

First, Diagnose the Errors

  1. 'Return' outside function: This happened because you had an uncommented line key = pygame with incorrect indentation. Python relies entirely on indentation to define code blocks, and this stray line confused the interpreter into thinking your main() method ended early. As a result, the while loop and its return statements ended up outside any function scope.
  2. clock is not defined on line 30: Since the while loop was incorrectly interpreted as being outside main(), it couldn't access the clock variable you defined inside the method.

Here's the Fixed Code

I've cleaned up the indentation, fixed the audio logic, and tidied up your commented-out Player class:

# This just imports all the Pygame modules
import pygame

class Game(object):
    def main(self, screen):
        # Initialize audio mixer before playing sound
        pygame.mixer.init()
        # Load and play background music (-1 means loop indefinitely)
        pygame.mixer.music.load('The Tonight Show Star Wars The Bee Gees Stayin Alive Shortened.mp3')
        pygame.mixer.music.play(-1)

        clock = pygame.time.Clock()
        # Commented-out Player class (fixed indentation and syntax)
        # class Player(pygame.sprite.Sprite):
        #     def __init__(self, *groups):
        #         super(Player, self).__init__(*groups)
        #         self.image = pygame.image.load('Sprite-01.png')
        #         self.rect = pygame.rect.Rect((320, 240), self.image.get_size())
        #     def update(self):
        #         key = pygame.key.get_pressed()
        #         # Add player movement logic here if you revisit this class

        image = pygame.image.load('Sprite-01.png')
        # Initialize position variables
        image_x = 0
        image_y = 0

        while True:
            clock.tick(60)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    return

            # Handle continuous key presses
            key = pygame.key.get_pressed()
            if key[pygame.K_LEFT]:
                image_x -= 10
            if key[pygame.K_RIGHT]:
                image_x += 10
            if key[pygame.K_UP]:
                image_y -= 10
            if key[pygame.K_DOWN]:
                image_y += 10

            # Redraw screen every frame
            screen.fill((200, 200, 200))
            screen.blit(image, (image_x, image_y))
            pygame.display.flip()

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption('St.Patrick game')
    Game().main(screen)

Key Fixes I Made:

  • Removed the stray key = pygame line: This was the root cause of your indentation and scope errors.
  • Fixed audio code:
    • Added pygame.mixer.init() (required to initialize Pygame's audio system).
    • Used pygame.mixer.music instead of pygame.mixer.Sound for background music (better suited for long tracks like MP3s).
    • Removed time.sleep()—it blocks your game loop, making the game unresponsive while music plays. pygame.mixer.music.play() runs in the background without interrupting gameplay.
  • Cleaned up commented code: Fixed indentation in your Player class comments and corrected the super() call syntax (added missing parentheses).
  • Swapped while 1 for while True: More readable and aligned with Python best practices.

Quick Audio Notes:

  • Ensure your MP3 file is in the same folder as your Python script, or provide the full file path to load().
  • To stop the music later (if needed), use pygame.mixer.music.stop().

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:29:52