Python Snake游戏索引器:列表索引超出范围

Python Snake游戏索引器:列表索引超出范围,python,pygame,Python,Pygame,我的snake代码有问题,并且不断收到indexer:list索引超出范围的错误消息 我想问题出在114行 for choice in selection: pygame.draw.rect(screen,WHITE,choice,0) # redraw selected button in another colour pygame.draw.rect(screen,GREEN,sele

我的snake代码有问题,并且不断收到indexer:list索引超出范围的错误消息

我想问题出在114行

 for choice in selection:
                    pygame.draw.rect(screen,WHITE,choice,0)

                # redraw selected button in another colour
                pygame.draw.rect(screen,GREEN,selection[num], 0)

如果代码中有任何其他问题,如bug或不一致,请告诉我

但是如果您找到了索引问题的解决方案,请解释一下,因为我是python新手 此外,一个解决方案也会有所帮助

import pygame
import sys
import random
import time

pygame.init()

WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
DARKRED = (125, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

screenWidth = 800
screenHeight = 800


screen = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption('Snake Game by Loneth')

clock = pygame.time.Clock()

snakeBlock = 10
snakeSpeed = 15

fontTitle = pygame.font.SysFont("arial",100)
fontStyle = pygame.font.SysFont("ariel", 50)
scoreFont = pygame.font.SysFont("ariel", 35)
instructionsTitle = pygame.font.SysFont("arial", 48)


def score(score):
    value = scoreFont.render(" Score: " + str(score), True, BLACK)
    screen.blit(value, [50, 50])



def snake(snakeBlock, snakeList):
    for x in snakeList:
        pygame.draw.rect(screen, GREEN, [x[0], x[1], snakeBlock, snakeBlock])


def message(msg, colour):
    msg = fontStyle.render(msg, True, BLACK)
    screen.blit(msg, [screenWidth / 20, screenHeight / 2])


def gameLoop():

    gameOver = False
    gameEnd = False
    instructions = False
    game = True
    intro = True
    main = True


    x1 = screenWidth / 2
    y1 = screenHeight / 2

    dx = 0
    dy = 0

    snakeList = []
    snakeLength = 2

    foodx = round(random.randrange(0, screenWidth - snakeBlock) / 10.0) * 10.0
    foody = round(random.randrange(0, screenHeight - snakeBlock) / 10.0) * 10.0

    def menu(titles):
        mx, my = 0, 0

        buttonTitleFont = pygame.font.SysFont("arial", 52)
        selection = []
        rectWidth = 400
        rectHeight = 60
        x = int(screen.get_width()/2 - rectWidth/2)
        y = 450
        length = len(titles)
        num = 0
        hover = False
        # creates the Rects (containers) for the buttons

        for i in range (0,length,1):
            choiceRect = pygame.Rect(x,y,rectWidth,rectHeight)
            selection.append(choiceRect)
            y += 100

            #main loop in menu    
            menu = True
            while menu:    
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        menu = False
                        pygame.quit()
                        sys.exit()
                    if event.type ==pygame.MOUSEMOTION:     # if mouse moved
                        hover = False
                        mx, my = pygame.mouse.get_pos()     # get the mouse position

                    if selection[0].collidepoint((mx,my)):  # check if x,y of mouse is in a button
                        num = i
                        hover = True
                    if event.type == pygame.MOUSEBUTTONDOWN and hover == True:  #if mouse is in button
                        menu = False                                              # and has been clicked

                # draw all buttons                                                                
                for choice in selection:
                    pygame.draw.rect(screen,WHITE,choice,0)

                # redraw selected button in another colour
                pygame.draw.rect(screen,GREEN,selection[num], 0)

                # draw all the titles on the buttons
                x = int(screen.get_width()/2 - 150)
                y = 450
                for i in range(0,length,1):
                    buttonTitle = buttonTitleFont.render(titles[i],True,BLACK)
                    screen.blit(buttonTitle,(x,y))
                    y += 100

                pygame.display.update()
            return num

    while main:
        for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
            if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
                main = False         # set the "main" variable to False to exit while loop

        while intro:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    main = False
                    intro = False

            screen.fill(BLACK)

            menuMain = ["Launch", "Instructions","QUIT"]

            mainMenu = True
            mainInt = True
            while mainInt:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        main = False
                        intro = False
                        mainInt = False

                screen.fill(BLACK)

                #Centers the rendered tiles
                textTitle = fontTitle.render("Snake", True, GREEN )
                textW = textTitle.get_width()
                textH = textTitle.get_height()
                xTitle = int(screenWidth/2 - textW/2)
                yTitle = int(screenHeight/4 - textH/2)
                screen.blit(textTitle, (xTitle,yTitle))
                pygame.display.update()

                # in the intro, this asks the user where they would like to go
                if mainMenu ==True:
                    choose = menu(menuMain)
                    if choose == 0:
                        menu = False
                        intro = False
                        mainInt = False
                        mainMenu = False
                        game = True
                        screen.fill(BLACK)
                    elif choose ==1:
                        menu = False
                        instructions = True
                        mainMenu = False
                        screen.fill(BLACK)
                        pygame.display.update()
                    elif choose == 2:
                        menu = False
                        main = False
                        intro = False
                        mainInt = False
                        mainMenu = False


        while instructions:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    main = False
                    instructions = False

            screen.fill(BLACK)

            # main instructions title
            insTitle = fontTitle.render("Instructions!", True, RED)
            insW = insTitle.get_width()
            insx = int(screenWidth/2 - insW/2)
            insy = 10
            screen.blit(insTitle, (insx,insy))

            # first line of instructions
            playerInsTitle = instructionsTitle.render("Hey youre a snake and that sucks.", True, RED)
            playW = playerInsTitle.get_width()
            playx = int(screenWidth/2 - playW/2)
            playy = 200
            screen.blit(playerInsTitle, (playx,playy))

            # second line of instructions
            playerInsTitle2 = instructionsTitle.render("as a snake you have to eat food and stay alive long enough to be crowned king of snakes", True, RED)
            play2W = playerInsTitle2.get_width()
            play2x = int(screenWidth/2 - play2W/2)
            play2y = 300
            screen.blit(playerInsTitle2, (play2x,play2y))

            #third line of instructions
            playerInsTitle3 = instructionsTitle.render("Avoid hitting your self or the walls or else you'll die", True, RED)
            play3W = playerInsTitle3.get_width()
            play3x = int(screenWidth/2 - play3W/2)
            play3y = 400
            screen.blit(playerInsTitle3, (play3x,play3y))

            # fourth line of instructions
            playerInsTitle4 = instructionsTitle.render("Now you know how to play the game!", True, RED)
            play4W = playerInsTitle4.get_width()
            play4x = int(screenWidth/2 - play4W/2)
            play4y = 500
            screen.blit(playerInsTitle4, (play4x,play4y))


            # Detects if Q is pressed and starts the game
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    game = True
                    instructions = False


            pygame.display.update()


        while game: 

            if gameOver == True:
                game = False

            while gameEnd == True:
                screen.fill(DARKRED)
                message("You Lost! Press C to Play Again or Q to Quit", RED)
                score(snakeLength - 1)
                pygame.display.update()

                for event in pygame.event.get():
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_q:
                            gameOver = True
                            gameEnd = False
                        if event.key == pygame.K_c:
                            gameLoop()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    gameOver = True
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        dx = -snakeBlock
                        dy = 0
                    elif event.key == pygame.K_RIGHT:
                        dx = snakeBlock
                        dy = 0
                    elif event.key == pygame.K_UP:
                        dx = 0
                        dy = -snakeBlock
                    elif event.key == pygame.K_DOWN:
                        dx = 0
                        dy = snakeBlock

            if x1 >= screenWidth or x1 < 0 or y1 >= screenHeight or y1 < 0:
                gameEnd = True

            x1 += dx
            y1 += dy

            screen.fill(WHITE)

            pygame.draw.rect(screen, RED, [foodx, foody, snakeBlock, snakeBlock])
            snakeHead = []
            snakeHead.append(x1)
            snakeHead.append(y1)
            snakeList.append(snakeHead)

            if len(snakeList) > snakeLength:
                del snakeList[0]

            for x in snakeList[:-1]:
                if x == snakeHead:
                    gameEnd = True

            snake(snakeBlock, snakeList)
            score(snakeLength - 1)

            pygame.display.update()

            if x1 == foodx and y1 == foody:
                foodx = round(random.randrange(0, screenWidth - snakeBlock) / 10.0) * 10.0
                foody = round(random.randrange(0, screenHeight - snakeBlock) / 10.0) * 10.0
                snakeLength += 1

            clock.tick(snakeSpeed)

        pygame.quit()
        quit()


gameLoop()
导入pygame
导入系统
随机输入
导入时间
pygame.init()
白色=(255,255,255)
黄色=(255、255、102)
黑色=(0,0,0)
红色=(255,0,0)
DARKRED=(125,0,0)
绿色=(0,255,0)
蓝色=(0,0255)
屏幕宽度=800
屏幕高度=800
screen=pygame.display.set_模式((屏幕宽度、屏幕高度))
pygame.display.set_标题('Loneth的蛇游戏')
clock=pygame.time.clock()
蛇形块=10
蛇速=15
fontTitle=pygame.font.SysFont(“arial”,100)
fontStyle=pygame.font.SysFont(“ariel”,50)
scoreFont=pygame.font.SysFont(“ariel”,35)
指令标题=pygame.font.SysFont(“arial”,48)
def分数(分数):
value=scoreFont.render(“分数:+str(分数),真,黑色)
blit(值,[50,50])
def snake(蛇块、蛇师):
对于蛇列表中的x:
pygame.draw.rect(屏幕,绿色,[x[0],x[1],蛇挡,蛇挡])
def消息(消息,颜色):
msg=fontStyle.render(msg,True,黑色)
screen.blit(消息,[screenWidth/20,screenHeight/2])
def gameLoop():
gameOver=False
gameEnd=False
指令=错误
游戏=真实
简介=正确
main=True
x1=屏幕宽度/2
y1=屏幕高度/2
dx=0
dy=0
蛇学家=[]
蛇形长度=2
foodx=圆形(随机随机随机范围(0,屏幕宽度-蛇形块)/10.0)*10.0
foody=圆形(random.randrange(0,屏幕高度-蛇形块)/10.0)*10.0
def菜单(标题):
mx,my=0,0
buttonTitleFont=pygame.font.SysFont(“arial”,52)
选择=[]
矩形宽度=400
高度=60
x=int(screen.get_width()/2-rectWidth/2)
y=450
长度=长度(标题)
num=0
悬停=错误
#为按钮创建矩形(容器)
对于范围内的i(0,长度,1):
choiceRect=pygame.Rect(x,y,rectWidth,rectHeight)
selection.append(choiceRect)
y+=100
#菜单中的主循环
菜单=真
while菜单:
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
菜单=错误
pygame.quit()
sys.exit()
if event.type==pygame.MOUSEMOTION:#如果鼠标移动
悬停=错误
mx,my=pygame.mouse.get_pos()#获取鼠标位置
如果选择[0]。碰撞点((mx,my)):#检查鼠标的x,y是否在按钮中
num=i
悬停=真
如果event.type==pygame.MOUSEBUTTONDOWN和hover==True:#如果鼠标在按钮中
menu=False#并且已被单击
#绘制所有按钮
在选择中选择:
pygame.draw.rect(屏幕,白色,选项,0)
#用另一种颜色重新绘制所选按钮
pygame.draw.rect(屏幕,绿色,选择[num],0)
#在按钮上绘制所有标题
x=int(screen.get_width()/2-150)
y=450
对于范围内的i(0,长度,1):
buttonTitle=buttonTitleFont.render(标题[i],真,黑色)
屏幕光点(按钮,(x,y))
y+=100
pygame.display.update()
返回数
虽然主要:
对于pygame.event.get()中的事件:#检查是否有任何事件(如按键、鼠标单击等)
if event.type==pygame.QUIT:#检查屏幕右上角是否为“x”
main=False#将“main”变量设置为False以退出循环
而简介:
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
main=False
简介=错误
屏幕填充(黑色)
menuMain=[“启动”、“说明”、“退出”]
主菜单=真
mainit=True
维护时:
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
main=False
简介=错误
mainit=False
屏幕填充(黑色)
#使渲染的平铺居中
textTitle=fontTitle.render(“蛇”,真,绿色)
textW=textTitle.get_width()
textH=textTitle.get_height()
xTitle=int(屏幕宽度/2-textW/2)
yTitle=int(屏幕高度/4-textH/2)
screen.blit(文本标题(xTitle,yTitle))
pygame.display.update()
#在介绍中,询问用户想去哪里
如果mainMenu==True:
选择=菜单(菜单名)
如果choose==0:
菜单=错误
简介=错误
mainit=False
主菜单=错误
游戏=真实
屏幕填充(黑色)
elif choose==1:
菜单=错误
说明=正确
主菜单=错误
屏幕填充(黑色)
pygame.display.update()
elif choose==2:
def menu(titles):
    mx, my = 0, 0

    buttonTitleFont = pygame.font.SysFont("arial", 52)
    selection = []
    rectWidth = 400
    rectHeight = 60
    x = int(screen.get_width()/2 - rectWidth/2)
    y = 450
    length = len(titles)
    num = 0
    hover = False
    # creates the Rects (containers) for the buttons

    for i in range (0,length,1):
        choiceRect = pygame.Rect(x,y,rectWidth,rectHeight)
        selection.append(choiceRect)
        y += 100

    #!!! Here was indentation wrong, move the whole `while` block to the left

    #main loop in menu
    menu = True
    while menu:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                menu = False
                pygame.quit()
                sys.exit()
            if event.type ==pygame.MOUSEMOTION:     # if mouse moved
                hover = False
                mx, my = pygame.mouse.get_pos()     # get the mouse position

            #!!! Here I put for-loop to check mouse position against every button:

            for i in range(length):
                if selection[i].collidepoint((mx,my)):  # check if x,y of mouse is in a button
                    num = i
                    hover = True
                if event.type == pygame.MOUSEBUTTONDOWN and hover == True:  #if mouse is in button
                    menu = False                                              # and has been clicked

        # draw all buttons
        for choice in selection:
            pygame.draw.rect(screen,WHITE,choice,0)

        # redraw selected button in another colour
        pygame.draw.rect(screen,GREEN,selection[num], 0)

        # draw all the titles on the buttons
        x = int(screen.get_width()/2 - 150)
        y = 450
        for i in range(0,length,1):
            buttonTitle = buttonTitleFont.render(titles[i],True,BLACK)
            screen.blit(buttonTitle,(x,y))
            y += 100

        pygame.display.update()
    return num