0

I am trying to get the cloud to animate from left to right and back on a basic screen, it works when I don't use the define and just put it into the game loop, so why does it stop working inside the define?

import pygame, sys
from pygame.locals import *

pygame.init()

FPS = 30
fpsClock = pygame.time.Clock()

width = 500
length = 300
DISPLAYSURF = pygame.display.set_mode((width, length), 0, 32)
pygame.display.set_caption('Test')

def Clouds():
    BROWN = ( 139, 69, 19)
    GREEN = (  0, 255,   0)
    LIGHT_BLUE = ( 135, 206, 250)
    global cloudimg, cloudx, cloudy
    cloudimg = pygame.image.load('Cartoon_cloud.png')
    direction = 'left'
    cloudx = 100
    cloudy = 70

    DISPLAYSURF.fill(LIGHT_BLUE)
    pygame.draw.rect(DISPLAYSURF, BROWN, (0, 285, width, 15))
    pygame.draw.rect(DISPLAYSURF, GREEN, (0, 280, width, 5))

    if direction == 'left':
        cloudx += 1
        if cloudx == 450:
            direction = 'right'
    elif direction == 'right':
        cloudx -= 1
        if cloudx == 0:
            direction = 'left'

while True:
    Clouds()
    DISPLAYSURF.blit(cloudimg, (cloudx, cloudy))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
    fpsClock.tick(FPS)
E.Schwerdt
  • 47
  • 6
  • 1
    `direction` is always going to be `'left'` since it is reset on every loop. – Klaus D. Jun 29 '17 at 11:34
  • 1
    It's a bit hard to tell because we only have one version of your code. A problem, however, is that you reset `cloudx` and `cloudy` to their initial values everytime you call `Clouds()`. – Thierry Lathuille Jun 29 '17 at 11:34
  • Any Idea how to fix that while still using variables? – E.Schwerdt Jun 30 '17 at 12:10
  • @E.Schwerdt use Sprites, everything else is crap. – sloth Jun 30 '17 at 13:52
  • @E.Schwerdt just create those 3 variables outside the function, since you're already using `global` (add `direction` to this line). And to be sure to reverse the direction, use `if cloudx >= 450:` , and `if cloudx <= 0:` – PRMoureu Jun 30 '17 at 21:56
  • The code should be structured in a different way. The `Clouds` function is doing too much (functions should preferably do only one thing) and should be split apart. Actually the function is not needed at all, since you call it only one time. Also, global variables should be avoided, since they can make code harder to understand and maintain. You can just pass the variables as arguments and return something from the function. – skrx Jul 01 '17 at 06:36

0 Answers0