Skip to content
Advertisement

When I start this code, i found a problem with error Traceback (most recent call last) in my code with pygame module

I have problem with function. I starting learn pygame with video course, and this is my first pygame code. My .py code:

import pygame

pygame.init()

win = pygame.display.set_mode((1280, 720))

pygame.display.set_caption("text.")

walkaniml = pygame.image.load('left1.png')
walkanimr = pygame.image.load('right1.png')
stickmanStand = pygame.image.load('stickman.png')

clock = pygame.time.Clock()

x = 250
y = 400
widht = 271
height = 293
speed = 5

jump = False
jumplov = 10

left = False
right = False
animcount = 0

def drawcube():

    global animcount

    win.fill((255, 218, 185))

    if animcount + 1 >= 24:
        animcount = 0

    if left:
        win.blit(walkaniml(animcount // 1, (x, y)))

    elif right:
        win.blit(walkanimr(animcount // 1, (x, y)))

    else:
        win.blit(stickmanStand, (x, y))

    pygame.display.update()

run = True

while run:
    clock.tick(24)

    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 > 1:
        x -= speed
        left = True
        right = False

    elif keys[pygame.K_RIGHT] and x < 1280 - widht - 1:
        x += speed
        left = False
        right = True

    else:
        left = False
        right = False
        animcount = 0

    if not(jump):

        if keys[pygame.K_DOWN] and y < 720 - height - 1:
            y += speed

        if keys[pygame.K_SPACE]:
            jump = True
    else:

        if jumplov >= -10:
            if jumplov < 0:
                y += (jumplov ** 2) / 3

            else:
                y -= (jumplov ** 2) / 3
            jumplov -= 1

        else:

            jump = False
            jumplov = 10

enter image description here drawcube()

I wanna do a mini-game with stickman, and i found a very big problem, when I start game in cmd and I’m going to web to found decision, but.. I don’t find him. Please guys, I realy need help((

Advertisement

Answer

walkaniml and walkanimr are pygame.Surface objects. You can’t call an object:

win.blit(walkaniml(animcount // 1, (x, y)))

win.blit(walkaniml, (x, y))

If walkaniml and walkanimr are a list of Surfaces, you can get an element from the lists by it’s index with subscription (even if the list contains only 1 element):

walkaniml = [ pygame.image.load('left1.png') ]
walkanimr = [ pygame.image.load('right1.png') ]
if left:
    if animcount >= len(walkaniml):
        animcount = 0
    win.blit(walkaniml[animcount], (x, y))

elif right:
    if animcount >= len(walkanimr):
        animcount = 0
    win.blit(walkanimr[animcount], (x, y))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement