IndexError:列表索引超出范围,蛇游戏

时间:2016-03-14 19:18:33

标签: python arrays indexing pygame

'''
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 = self.body [0] IndexError:列表索引超出范围 我正在做这个教程: https://lorenzod8n.wordpress.com/2008/03/01/pygame-tutorial-9-first-improvements-to-the-game/

我是python的新手,PLZ帮帮我

3 个答案:

答案 0 :(得分:0)

问题在于,在您班级的__init__功能中,您可以定义self.body = []。这意味着该列表包含0个项目。

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

答案 1 :(得分:0)

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

首先在这里实例化你的蠕虫:

worm = Worm(screen) ###

因此,如果您查看__init__的{​​{1}},则表示您将Worm设置为空列表self.body

如果您遵循从那时起发生的所有代码,直到您实际致电:

[]

您实际上从未在worm.draw() 列表中插入任何内容。因此,当您尝试在body方法中访问正文列表时:

draw

你肯定会得到索引超出范围的错误,因为无法访问。

要纠正此问题,您需要提供以下默认值:

error x, y = self.body[0]

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

# arbitrary data
self.body = [0, 0]

答案 2 :(得分:0)

在您的蠕虫的__init__功能中,您可以将self.body[]设置为self.body[(0, 0)],这是有效的。引发错误的原因是您在开头定义了一个空列表,之后您尝试通过传递索引(self.body[0])从列表中获取项目。但由于列表为空,因此Python无法获取所请求的值。

希望这有帮助!