首页 > 解决方案 > Pygame 教程中的“IndentationError: expected an indented block”

问题描述

我遵循 Pygame 的教程只是为了感受一下。我是编码新手,我没有复制和粘贴代码,而是自己输入了代码。它在视频中运行良好,我不知道为什么在视频中没有某行时应该缩进。我收到了第 51 行和第 54 行的错误。

def show_go_screen(self):
  ^
IndentationError: expected an indented block

试图正确输入错误代码,这是我第一次在这里发帖。

import pygame as pg
import random
import os
from settings import *

class Game:
    def __init__(self):
        # initialize window
        pg.init()
        pg.mixer.init()
        screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        clock = pg.time.Clock()
        self.running = True

    def new(self):
        # Start New Game
        self.all_sprites = pg.sprite.Group()

    def run(self):
        # Game Loop
        self.playing = True
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    def update(self):
        # Game Loop Update
        self.all_sprites.update()

    def events(self):
        # Game Loop Events
        for event in pg.event.quit():
            if event.type == pg.QUIT:
                if self.playing:
                    self.playing = False
                self.running = False

    def draw(self):
        # Game Loop Draw
        self.screen.fill(BLACK)
        self.all_sprites.draw(self.screen)

        pg.display.flip()

    def show_start_screen(self):
        # game start screen

    def show_go_screen(self):
        # game over/continue
    
g = Game()
g.show_start_screen()
while g.running:
    g.new()
    g.run()
    g.show_go_screen()

pg.quit
    

标签: python

解决方案


问题在这里:

def show_start_screen(self):
    # game start screen

def show_go_screen(self):
    # game over/continue

您不能像在 C 或 Java 中那样将函数留空,您需要使用pass.

def show_start_screen(self):
    # game start screen
    pass

def show_go_screen(self):
    # game over/continue
    pass

这应该可以解决缩进问题,但我认为代码不会按预期工作,因为函数无缘无故不存在......为什么会无缘无故调用空白函数?你肯定错过了什么。


推荐阅读