【问题标题】:IndexError: list index out of range, snake gameIndexError:列表索引超出范围,蛇游戏
【发布时间】:2016-03-15 03:34:51
【问题描述】:
'''
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很陌生,请帮助我

【问题讨论】:

    标签: python arrays indexing pygame


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      您首先在此处实例化您的蠕虫:

      worm = Worm(screen) ###
      

      因此,如果您查看Worm__init__,您将self.body 设置为一个空列表[]

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

      worm.draw()
      

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

      error x, y = self.body[0]
      

      您肯定会遇到索引超出范围错误,因为没有可访问的内容。

      要纠正这个问题,您需要提供一个默认值,例如:

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

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

      if self.body:
          # do things
      

      【讨论】:

        【解决方案3】:

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

        希望这会有所帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-18
          • 1970-01-01
          • 2020-12-18
          • 1970-01-01
          • 2011-10-31
          • 2015-06-26
          相关资源
          最近更新 更多