Snake游戏OOP:因为上面有这个IndexError列表而感到困惑



目前如此。我正在制作一款蛇游戏类型的游戏,我遇到了一些问题。IndexError和其他一些错误。出于某种奇怪的原因,我一直在努力理解这一点,它对我的udemy教练有效。我对这个错误很困惑。这是代码:

from turtle import Screen, Turtle
from D20_snake import Snake
import time
#setup screen, widths, and heights)
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Armand's Snake game!")
#tracer function to turn animation on/off)
screen.tracer(0)
screen.textinput(title="Start!",prompt="Type Anything to Start Playing the Snake Game: ")

snake = Snake()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)

snake.move()

screen.exitonclick()

这就是我所说的

from turtle import Turtle
#Create the Snake Body and Class, starting with 3 white squares.
STARTING_POSITIONS = [(0,0),(-20,0),(-40,0)]
MOVE_DISTANCE = 20
#make segments list and snake object for snake body, that will get appended with each new body part
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0

class Snake:
def __init__(self):
self.segments = []
self.head = self.segments[0]
#snake body
def create_snake(self):
for position in STARTING_POSITIONS:
new_segment = Turtle("square")
new_segment.color("white")
new_segment.penup()
new_segment.goto(position)
self.segments.append(new_segment)
def move(self):
for seg_num in range(len(self.segments) -1,0,-1):
new_x = self.segments[seg_num - 1].xcor()
new_y = self.segments[seg_num - 1].ycor()
self.segments[seg_num].goto(new_x,new_y)
self.head.forward(MOVE_DISTANCE)  
#arrow key movements        
def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)
def down(self):
if self.head.heading() !=UP:
self.head.setheading(DOWN)
def left(self):
if self.head.heading() !=RIGHT:
self.head.setheading(LEFT)
def right(self):
if self.head.heading() !=LEFT:
self.head.setheading(RIGHT)

这个索引错误弹出在段列表中:

File "c:UsersArmand SDesktopPython FilesD20 The Snake Game.py", line 16, in <module>
snake = Snake()
File "c:UsersArmand SDesktopPython FilesD20_snake.py", line 16, in __init__
self.head = self.segments[0]
IndexError: list index out of range

我自己也不太明白,我很困惑。列表上显然有[0],但它只是说索引错误。

当您创建Snake类的实例时,在您的主文件中:

snake = Snake()

它在Snake类中运行__init__方法您定义的位置:

self.segments = []

在下一行中,您没有在分段列表中添加任何项目,而是写道:

self.head = self.segments[0]

尽管此时段列表不能为空

为了解决这个问题,将__init__方法更改为类似的方法:

def __init__(self):
x = 1   #or maybe something else
self.segments = [x]
self.head = self.segments[0]

最新更新