索引器错误:列表索引超出范围,snake gam

2024-05-29 02:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

'''
Created on 13.3.2016
worm game
@author: Hai
'''
import pygame
import random
from pygame import * ##

class Worm:
    def __init__(self, surface):
        self.surface = surface
        self.x = surface.get_width() / 2
        self.y = surface.get_height() / 2
        self.length = 1
        self.grow_to = 50
        self.vx = 0
        self.vy = -1
        self.body = []
        self.crashed = False
        self.color = 255, 255, 0

    def key_event(self, event):
        """ Handle keyboard events that affect the worm. """
        if event.key == pygame.K_UP and self.vy != 1:
            self.vx = 0
            self.vy = -1
        elif event.key == pygame.K_RIGHT and self.vx != -1:
            self.vx = 1
            self.vy = 0
        elif event.key == pygame.K_DOWN and self.vy != -1:
            self.vx = 0
            self.vy = 1
        elif event.key == pygame.K_LEFT and self.vx != 1:
            self.vx = -1
            self.vy = 0

    def move(self):
        """ Moving worm """
        self.x += self.vx # add vx to x
        self.y += self.vy

        if (self.x, self.y) in self.body:
            self.crashed = True

        self.body.insert(0, (self.x, self.y))

        # Changes worm to right size so it is grow_to
        if self.grow_to > self.length: 
            self.length += 1

        # If body is longer than length then pop
        if len(self.body) > self.length:
            self.body.pop()
    """            
    def draw(self):

        self.surface.set_at((int(self.x), int(self.y)), (255, 255, 255))
        self.surface.set_at((int(self.last[0]),int(self.last[1])), (0,0,0))
    """
    def position(self):
        return self.x, self.y

    def eat(self):
        self.grow_to += 25

    def draw(self):

        x, y = self.body[0]
        self.surface.set_at((int(x), int(y)), self.color)
        x, y = self.body[-1]
        self.surface.set_at((int(x), int(y)), (0, 0, 0))

    #    for x, y in self.body:
    #        self.surface.set_at((int(x), int(y)), self.color)
    #        pygame.draw.rect(self.surface, self.color, (self.x, self.y, 6, 6), 0)
    # worm's head


class Food:
    def __init__(self, surface):
            self.surface = surface
            self.x = random.randint(0, surface.get_width())
            self.y = random.randint(0, surface.get_height())
            self.color = 255,255,255

    def draw(self):
        self.surface.set_at((int(self.x),int(self.y)), self.color)
        pygame.draw.rect(self.surface, self.color, (self.x, self.y, 6, 6), 0)

    def position(self):
        return self.x, self.y

    """ Check if worm have eaten this food """
    def check(self, x, y):
        if x < self.x or x > self.x + 6:
            return False
        elif y < self.y or y > self.y + 6:
            return False
        else:
            return True

    def erase(self):
        pygame.draw.rect(self.surface, (0,0,0), (int(self.x), int(self.y), 6, 6), 0)        



w = h = 500

screen = pygame.display.set_mode((w, h))
clock = pygame.time.Clock()

pygame.mixer.init()
chomp = pygame.mixer.Sound("bow.wav")

score = 0
worm = Worm(screen) ###
food = Food(screen)
running = True

while running:
    # screen.fill((0, 0, 0)) optimized in worm draw()
    worm.draw()
    food.draw()
    worm.move()


    if worm.crashed or worm.x <= 0 or worm.x >= w-1 or worm.y <= 0 or worm.y >= h-1:
        print("U lose")
        running = False
    elif food.check(worm.x, worm.y):
        worm.eat()
        food.erase()
        chomp.play()
        score += 1
        print("Score is: %d" % score)
        food = Food(screen)


    for event in pygame.event.get():
        if event.type == pygame.QUIT: # Pressed X
            running = False
        elif event.type == pygame.KEYDOWN: # When pressing keyboard
            worm.key_event(event)

    pygame.display.flip()
    clock.tick(100)

你好,我收到错误 x、 y=自我身体[0] 索引器错误:列表索引超出范围 我正在做这个教程: https://lorenzod8n.wordpress.com/2008/03/01/pygame-tutorial-9-first-improvements-to-the-game/

我对python很陌生,请帮帮我


Tags: toselfeventifdefbodysurfacepygame
3条回答

根据您正在执行的操作顺序,body列表实际上仍然是空的。按照你的代码逻辑,你会看到。在

首先在此处实例化蠕虫:

worm = Worm(screen) ###

因此,如果您查看Worm__init__,那么您将{}设置为一个空列表[]。在

如果您遵循从那时到实际调用的所有代码:

^{pr2}$

实际上,您从未在body列表中插入任何内容。因此,当您试图在draw方法中访问您的尸体列表时:

error x, y = self.body[0]

你肯定会得到一个索引超出范围的错误,因为没有什么可访问的。在

要纠正这种情况,您需要提供如下默认值:

^{4}$

或者,在draw方法中确定如何使用以下条件处理空列表:

if self.body:
    # do things

问题是在类的__init__函数中,定义了self.body = []。这意味着列表包含0项。在

在稍后的代码中,您将引用self.body[0]和{},这是列表中的第一和第二项。由于这些不存在,因此会引发错误。要解决此问题,需要用两个项初始化self.body。在

在蠕虫的__init__函数中,可以将self.body[]设置为self.body[(0, 0)],这样就可以了。出现此错误是因为您在开始时定义了一个空列表,后来您试图通过传递索引(self.body[0])从列表中获取项。但是由于列表是空的,Python无法获取所请求的值。在

希望这有帮助!在

相关问题 更多 >

    热门问题