KeyError:0 Python -无法在代码中找到问题

k5hmc34c  于 2023-03-04  发布在  Python
关注(0)|答案(2)|浏览(100)

我正在为一个大学项目制作一个flappy Bird克隆,不断遇到这个问题:

Traceback (most recent call last):
  File "E:\computer science\ROCKETGAME\RocketGame.py", line 215, in <module>
    menuscreen()
  File "E:\computer science\ROCKETGAME\RocketGame.py", line 46, in menuscreen
    maingame()
  File "E:\computer science\ROCKETGAME\RocketGame.py", line 131, in maingame
    if 0<upperObs[0]['x']<5:
KeyError: 0

以下是错误消息引用的行:

if 0<upperObs[0]['x']<5:

我将张贴整个代码的点的错误,因为这将可能有助于解决这个问题。
(抱歉,这是很多,我只是通过学校学习Python,并作出了非常初级的项目,没有这样的规模,我是非常新的StackOverflow,所以不知道这是如何工作的)
我正在学习一个在线教程,但遇到了一些问题,我不得不自己解决,教程没有涵盖任何错误消息。我在开发过程中遇到了一些错误,我不得不在不知道StackOverflow的情况下揭穿自己。

import random
import sys
import pygame
from pygame.locals import *

#global var
fps = 32
scrwid = 289 #screen width
scrhi = 511 #screen height
screen = pygame.display.set_mode((scrwid, scrhi)) #make game window to mimick mobile size
GROUNDY = scrhi * 0.8 #declare ground variable
game_sprites = {}
game_sounds = {}
PLAYER = 'resources\SPRITES\\Rocket1.png' #player sprite
BACKGROUND = 'resources\SPRITES\\PygameStage.png' #background sprite
OBSTACLE = 'resources\SPRITES\\object1.png' #obstaclesprite

def menuscreen(): #menu screen function
    
    playerx = int(scrwid/5)
    playery = int(scrhi - game_sprites['player'].get_height())/2
    menux = int(scrwid - game_sprites['menuscreen'].get_width())/2
    menuy = int(scrhi * 0.13)
    basex = 0

    #draw rectangle for play button
    playbutton = pygame.Rect(108,222,68,65)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit() #quit game if player has a certain input

            elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
                return

            pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
            if pygame.mouse.get_pos()[0] > playbutton[0] and pygame.mouse.get_pos()[0] < playbutton[0] + playbutton[2]:
                if pygame.mouse.get_pos()[1] > playbutton[1] and pygame.mouse.get_pos()[1] < playbutton[1] + playbutton[3]:
                    pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)

            if playbutton.collidepoint(pygame.mouse.get_pos()):

                if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                    maingame()

            else:
                screen.blit(game_sprites['background'],(0,0))
                screen.blit(game_sprites['player'],(playerx,playery))
                screen.blit(game_sprites['menuscreen'],(menux,menuy))
                screen.blit(game_sprites['base'],(basex,GROUNDY))
                pygame.display.update()
                FPSCLOCK.tick(fps)

                
def maingame():
    score = 0
    playerx = int(scrwid/5)
    playery = int(scrhi/2)
    basex = 0

#creating upper and lower obstacles
    newObs1 = getRandomObstacle()
    newObs2 = getRandomObstacle()

    #upper obs list
    upperObs = [
        {'x':scrwid + 200,'y':newObs1[0]['y']},
        {'x':scrwid + 200 + (scrwid/2),'y':newObs2[0]['y']}
    ]

    #lower obs list
    lowerObs = [
        {'x':scrwid + 200,'y':newObs1[1]['y']},
        {'x':scrwid + 200 + (scrwid/2),'y':newObs2[1]['y']}
    ]

    obsVelX = -4 #object velocity x
    PlayerVelY = -9 
    PlayerMaxVelY = 10 #Player's maximum Y velocity
    PlayerMinVely = -8 #Player's minimum Y velocity
    PlayerAccY = 1 

    PlayerJumpAccv = -8 #velocity while flying up (Jumping)
    PlayerJumped = False

    while True:
        
        for event in pygame.event.get():

            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()

            if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP or event.key == 'w'):
                if playery > 0:
                    PlayerVelY = PlayerJumpAccv
                    PlayerJumped = True

        #check player score
        playerMidPosition = playerx + game_sprites['player'].get_width()/2
        for obstacle in upperObs:
            obsMidPosition = obstacle['x'] + game_sprites['obstacle'][0].get_width()/2
            if obsMidPosition <= playerMidPosition < obsMidPosition + 4:
                score += 1
                print("Your score is {score}")

                

        if PlayerVelY < PlayerMaxVelY and not PlayerJumped:
            PlayerVelY += PlayerAccY

        if PlayerJumped: #Makes it so the player cannot go below the ground when it hits it.
            PlayerJumped = False
        playerheight = game_sprites['player'].get_height()
        playery = playery + min(PlayerVelY, GROUNDY - playery - playerheight)


        #move obstacles to the left of the screen
        for upperObs, lowerObs in zip(upperObs, lowerObs):
            upperObs['x'] += obsVelX
            lowerObs['x'] += obsVelX

        #create new obstacle when needed
            if 0<upperObs[0]['x']<5:
                newObs = getRandomObstacle()
                upperObs.append(newObs[0])
                lowerObs.append(newObs[1])

        #when an obstacle is off screen destroy it
            if upperObs[0]['x']< -game_sprites['obstacle'][0].get_width():
                upperObs.pop(0)
                lowerObs.pop(0)

我试着在谷歌上搜索答案,这就是我在这里发现了一个类似的线程讨论类似的问题。然而,当我尝试实现这些解决方案时,它们也不起作用,所以我将代码改回原来的样子,这是为了这篇文章。
谢谢你的帮助。

wydwbb8l

wydwbb8l1#

下面的代码片段用一个本地状态覆盖了全局状态upperObs,该本地状态只应在这三行中使用。

#move obstacles to the left of the screen
        for upperObs, lowerObs in zip(upperObs, lowerObs):
            upperObs['x'] += obsVelX
            lowerObs['x'] += obsVelX

只需重命名for中使用的变量,这样全局变量就不会被覆盖:

#move obstacles to the left of the screen
        for upper_state, lower_state in zip(upperObs, lowerObs):
            upper_state['x'] += obsVelX
            lower_state['x'] += obsVelX
vngu2lb8

vngu2lb82#

if 0<upperObs[0]['x']<5:
KeyError: 0

方法:我尝试访问upperObs的第0个元素,但一无所获。问题很可能来自:

if upperObs[0]['x']< -game_sprites['obstacle'][0].get_width():
            upperObs.pop(0)
            lowerObs.pop(0)

从对象中删除项目的位置。修复方法可以是确保对象中始终至少有一个项目,以便您可以访问它,或者处理使用tryexcept块找不到对象的情况

相关问题