pygame对象不可下标

时间:2019-01-13 21:44:47

标签: pygame typeerror

Traceback (most recent call last):
  File "C:\Users\Austin\PycharmProjects\Project\pygame\pygame1.py", line 
84, in <module>
    redrawGameWindow()
  File "C:\Users\Austin\PycharmProjects\Project\pygame\pygame1.py", line 
34, in redrawGameWindow
    win.blit(walkLeft[walkCount//3], (x, y))
TypeError: 'pygame.Surface' object is not subscriptable

当我左右移动用作头像的图片时发生错误。无法完全确定要更改的内容。我将按照以下YouTube视频观看pygame:https://www.youtube.com/watch?v=UdsNBIzsmlI

据我所知,他的代码与我的代码相同,除了我的图像不同。

import pygame

pygame.init()

win = pygame.display.set_mode((500, 500))

pygame.display.set_caption("First Game")

walkLeft = pygame.image.load('adnan_leftWalk.png')
walkRight = pygame.image.load('adnan_rightWalk.png')
bg = pygame.image.load('Game1.jpg')
char = pygame.image.load('adnanJump.png')

clock = pygame.time.Clock()


x = 50
y = 425
width = 64
height = 64
vel = 5
left = False
right = False
walkCount = 0
isJump = False
jumpCount = 10

def redrawGameWindow():
    global walkCount
    win.blit(bg, (0,0))
    if walkCount + 1 >= 27:
        walkCount = 0
    if left:
        win.blit(walkLeft[walkCount//3], (x, y))
        walkCount += 1
    elif right:
        win.blit(walkRight[walkCount//3], (x, y))
        walkCount += 1
    else:
        win.blit(char, (x,y))

    pygame.display.update()


run = True
while run:
    clock.tick(27)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and x > vel:
        x -= vel
        left = True
        right = False
    elif keys[pygame.K_RIGHT] and x < 460:
        x += vel
        right = True
        left = False
    else:
        right = False
        left = False
        walkCount = 0
    if not (isJump):
        if keys[pygame.K_SPACE]:
            isJump = True
            right = False
            left = False
            walkCount = 0
    else:
        if jumpCount >= -10:
            neg = 1
            if jumpCount < 0:
                neg = -1
            y -= (jumpCount ** 2) * 0.5 * neg
            jumpCount -= 1

        else:
            isJump = False
            jumpCount = 10

    redrawGameWindow()


pygame.quit()

我希望我的头像能够左右移动,但似乎不太清楚。这是我第一次使用pygame。

1 个答案:

答案 0 :(得分:0)

此代码的读取方式类似于walkLeft应该是用于动画行走的图像列表。但是,在问题的代码中,walkLeft是单个图像:

walkLeft = pygame.image.load('adnan_leftWalk.png')

所以似乎有点混乱。

代码产生的错误消息-object is not subscriptable,表示代码尝试使用数组符号(从技术上讲,它尝试使用__getitem__()属性),但所涉及的对象不是数组/列表。

出现错误的行:

 win.blit(walkLeft[walkCount//3], (x, y))  # ERROR HERE

让我认为walkLeft应该是图像列表,因为它在变量上使用了数组/列表符号,并且walkCount的最大值限制为27。将整数除以3,也没有意义(也许有3张动画图像?)。只需删除数组标记可能可以使您对此问题有所了解:

 win.blit(walkLeft, (x, y))  # Fixes the bug, somewhat

...,并允许代码运行,绘制相同的位图,但位置不同。但是很明显有些东西丢失了。代码可以结合两个(或更多)示例吗?