Python 2D Sprite Animation












0















I'm trying to animate a sprite using a loop such that each time the loop runs through the position number for an image in an array increases by one. I keep getting "UnboundLocalError: local variable 'Antic' referenced before assignment". There is



    Antic = 0
Antic = int(Antic)
# Global constants
StAnmtn = ["Images/PlayerVampireStanding1.png", "
Images/PlayerVampireStanding2.png",
"Images/PlayerVampireStanding3.png","Images/PlayerVampireStanding4.png",
"Images/PlayerVampireStanding5.png", "Images/PlayerVampireStanding6.png",
"Images/PlayerVampireStanding7.png", "Images/PlayerVampireStanding8.png"]


`
at the start and



    def main():
""" Main Program """
pygame.init()

clock = pygame.time.Clock() # creates clock to limit frames per
second

FPS = 60 # sets max speed of min loop

SCREENSIZE = SCREENWIDTH, SCREENHEIGHT = 1300, 700 # sets size of
screen/window
screen = pygame.display.set_mode(SCREENSIZE) # creates window and game
screen

pygame.display.set_caption("Count Acheron")

# Create the player
player = Player()

# Create all the levels
level_list =
level_list.append( Level_01(player) )

# Set the current level
current_level_no = 0
current_level = level_list[current_level_no]

active_sprite_list = pygame.sprite.Group()
player.level = current_level

player.rect.x = 340
player.rect.y = SCREEN_HEIGHT - player.rect.height
active_sprite_list.add(player)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while not done:

for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.jump()

if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.change_x < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.change_x > 0:
player.stop()

if Antic > 6:
Antic = 0
else:
Antic += 1
# Update the player.
active_sprite_list.update()

# Update items in the level
current_level.update()

# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
current_level.draw(screen)
active_sprite_list.draw(screen)

# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

if __name__ == "__main__":
main()


as the loop. What it doesn't seem to like is the snippet of code



    if Antic > 6:
Antic = 0
else:
Antic += 1


How do I fix this?










share|improve this question























  • Which version of python are you using?

    – cookertron
    Nov 22 '18 at 13:50











  • Ah ok, just seen the tag

    – cookertron
    Nov 22 '18 at 13:54











  • Now I'm having a problem with the variable Antic where it doesn't seem to be finding the file from the array based on the value of Antic. I think it's because you can't use variables in the of an array but I don't know of any functional alternatives ...

    – Benedict Steele
    Jan 10 at 10:20
















0















I'm trying to animate a sprite using a loop such that each time the loop runs through the position number for an image in an array increases by one. I keep getting "UnboundLocalError: local variable 'Antic' referenced before assignment". There is



    Antic = 0
Antic = int(Antic)
# Global constants
StAnmtn = ["Images/PlayerVampireStanding1.png", "
Images/PlayerVampireStanding2.png",
"Images/PlayerVampireStanding3.png","Images/PlayerVampireStanding4.png",
"Images/PlayerVampireStanding5.png", "Images/PlayerVampireStanding6.png",
"Images/PlayerVampireStanding7.png", "Images/PlayerVampireStanding8.png"]


`
at the start and



    def main():
""" Main Program """
pygame.init()

clock = pygame.time.Clock() # creates clock to limit frames per
second

FPS = 60 # sets max speed of min loop

SCREENSIZE = SCREENWIDTH, SCREENHEIGHT = 1300, 700 # sets size of
screen/window
screen = pygame.display.set_mode(SCREENSIZE) # creates window and game
screen

pygame.display.set_caption("Count Acheron")

# Create the player
player = Player()

# Create all the levels
level_list =
level_list.append( Level_01(player) )

# Set the current level
current_level_no = 0
current_level = level_list[current_level_no]

active_sprite_list = pygame.sprite.Group()
player.level = current_level

player.rect.x = 340
player.rect.y = SCREEN_HEIGHT - player.rect.height
active_sprite_list.add(player)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while not done:

for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.jump()

if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.change_x < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.change_x > 0:
player.stop()

if Antic > 6:
Antic = 0
else:
Antic += 1
# Update the player.
active_sprite_list.update()

# Update items in the level
current_level.update()

# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
current_level.draw(screen)
active_sprite_list.draw(screen)

# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

if __name__ == "__main__":
main()


as the loop. What it doesn't seem to like is the snippet of code



    if Antic > 6:
Antic = 0
else:
Antic += 1


How do I fix this?










share|improve this question























  • Which version of python are you using?

    – cookertron
    Nov 22 '18 at 13:50











  • Ah ok, just seen the tag

    – cookertron
    Nov 22 '18 at 13:54











  • Now I'm having a problem with the variable Antic where it doesn't seem to be finding the file from the array based on the value of Antic. I think it's because you can't use variables in the of an array but I don't know of any functional alternatives ...

    – Benedict Steele
    Jan 10 at 10:20














0












0








0








I'm trying to animate a sprite using a loop such that each time the loop runs through the position number for an image in an array increases by one. I keep getting "UnboundLocalError: local variable 'Antic' referenced before assignment". There is



    Antic = 0
Antic = int(Antic)
# Global constants
StAnmtn = ["Images/PlayerVampireStanding1.png", "
Images/PlayerVampireStanding2.png",
"Images/PlayerVampireStanding3.png","Images/PlayerVampireStanding4.png",
"Images/PlayerVampireStanding5.png", "Images/PlayerVampireStanding6.png",
"Images/PlayerVampireStanding7.png", "Images/PlayerVampireStanding8.png"]


`
at the start and



    def main():
""" Main Program """
pygame.init()

clock = pygame.time.Clock() # creates clock to limit frames per
second

FPS = 60 # sets max speed of min loop

SCREENSIZE = SCREENWIDTH, SCREENHEIGHT = 1300, 700 # sets size of
screen/window
screen = pygame.display.set_mode(SCREENSIZE) # creates window and game
screen

pygame.display.set_caption("Count Acheron")

# Create the player
player = Player()

# Create all the levels
level_list =
level_list.append( Level_01(player) )

# Set the current level
current_level_no = 0
current_level = level_list[current_level_no]

active_sprite_list = pygame.sprite.Group()
player.level = current_level

player.rect.x = 340
player.rect.y = SCREEN_HEIGHT - player.rect.height
active_sprite_list.add(player)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while not done:

for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.jump()

if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.change_x < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.change_x > 0:
player.stop()

if Antic > 6:
Antic = 0
else:
Antic += 1
# Update the player.
active_sprite_list.update()

# Update items in the level
current_level.update()

# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
current_level.draw(screen)
active_sprite_list.draw(screen)

# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

if __name__ == "__main__":
main()


as the loop. What it doesn't seem to like is the snippet of code



    if Antic > 6:
Antic = 0
else:
Antic += 1


How do I fix this?










share|improve this question














I'm trying to animate a sprite using a loop such that each time the loop runs through the position number for an image in an array increases by one. I keep getting "UnboundLocalError: local variable 'Antic' referenced before assignment". There is



    Antic = 0
Antic = int(Antic)
# Global constants
StAnmtn = ["Images/PlayerVampireStanding1.png", "
Images/PlayerVampireStanding2.png",
"Images/PlayerVampireStanding3.png","Images/PlayerVampireStanding4.png",
"Images/PlayerVampireStanding5.png", "Images/PlayerVampireStanding6.png",
"Images/PlayerVampireStanding7.png", "Images/PlayerVampireStanding8.png"]


`
at the start and



    def main():
""" Main Program """
pygame.init()

clock = pygame.time.Clock() # creates clock to limit frames per
second

FPS = 60 # sets max speed of min loop

SCREENSIZE = SCREENWIDTH, SCREENHEIGHT = 1300, 700 # sets size of
screen/window
screen = pygame.display.set_mode(SCREENSIZE) # creates window and game
screen

pygame.display.set_caption("Count Acheron")

# Create the player
player = Player()

# Create all the levels
level_list =
level_list.append( Level_01(player) )

# Set the current level
current_level_no = 0
current_level = level_list[current_level_no]

active_sprite_list = pygame.sprite.Group()
player.level = current_level

player.rect.x = 340
player.rect.y = SCREEN_HEIGHT - player.rect.height
active_sprite_list.add(player)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while not done:

for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.jump()

if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.change_x < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.change_x > 0:
player.stop()

if Antic > 6:
Antic = 0
else:
Antic += 1
# Update the player.
active_sprite_list.update()

# Update items in the level
current_level.update()

# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
current_level.draw(screen)
active_sprite_list.draw(screen)

# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

# Limit to 60 frames per second
clock.tick(60)

# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

if __name__ == "__main__":
main()


as the loop. What it doesn't seem to like is the snippet of code



    if Antic > 6:
Antic = 0
else:
Antic += 1


How do I fix this?







python python-3.x animation pygame






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 '18 at 10:10









Benedict SteeleBenedict Steele

11




11













  • Which version of python are you using?

    – cookertron
    Nov 22 '18 at 13:50











  • Ah ok, just seen the tag

    – cookertron
    Nov 22 '18 at 13:54











  • Now I'm having a problem with the variable Antic where it doesn't seem to be finding the file from the array based on the value of Antic. I think it's because you can't use variables in the of an array but I don't know of any functional alternatives ...

    – Benedict Steele
    Jan 10 at 10:20



















  • Which version of python are you using?

    – cookertron
    Nov 22 '18 at 13:50











  • Ah ok, just seen the tag

    – cookertron
    Nov 22 '18 at 13:54











  • Now I'm having a problem with the variable Antic where it doesn't seem to be finding the file from the array based on the value of Antic. I think it's because you can't use variables in the of an array but I don't know of any functional alternatives ...

    – Benedict Steele
    Jan 10 at 10:20

















Which version of python are you using?

– cookertron
Nov 22 '18 at 13:50





Which version of python are you using?

– cookertron
Nov 22 '18 at 13:50













Ah ok, just seen the tag

– cookertron
Nov 22 '18 at 13:54





Ah ok, just seen the tag

– cookertron
Nov 22 '18 at 13:54













Now I'm having a problem with the variable Antic where it doesn't seem to be finding the file from the array based on the value of Antic. I think it's because you can't use variables in the of an array but I don't know of any functional alternatives ...

– Benedict Steele
Jan 10 at 10:20





Now I'm having a problem with the variable Antic where it doesn't seem to be finding the file from the array based on the value of Antic. I think it's because you can't use variables in the of an array but I don't know of any functional alternatives ...

– Benedict Steele
Jan 10 at 10:20












2 Answers
2






active

oldest

votes


















0














Personally I've never used pygame's sprite module.



import pygame

class character:
def __init__(self, x, y):
self.x = x
self.y = y
self.sprites = [pygame.image.load("img1.png"), pygame.image.load("img2.png")]
self.frame = 0

def draw(self, surface):
surface.blit(self.sprites[self.frame], (self.x, self.y))
self.frame += 1
if self.frame > len(self.sprites) - 1: self.frame = 0

pygame.init()
DS = pygame.display.set_mode((1280, 720))
clock = pygame.time.Clock()

c = character(640, 360)

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
pygame.quit()

c.draw(DS)
pygame.display.update()
clock.tick(30)
DS.fill((0, 0, 0))





share|improve this answer































    0














    Needed to globalise the function ("global Antic" in the main loop)






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428525%2fpython-2d-sprite-animation%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Personally I've never used pygame's sprite module.



      import pygame

      class character:
      def __init__(self, x, y):
      self.x = x
      self.y = y
      self.sprites = [pygame.image.load("img1.png"), pygame.image.load("img2.png")]
      self.frame = 0

      def draw(self, surface):
      surface.blit(self.sprites[self.frame], (self.x, self.y))
      self.frame += 1
      if self.frame > len(self.sprites) - 1: self.frame = 0

      pygame.init()
      DS = pygame.display.set_mode((1280, 720))
      clock = pygame.time.Clock()

      c = character(640, 360)

      while True:
      for event in pygame.event.get():
      if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
      pygame.quit()

      c.draw(DS)
      pygame.display.update()
      clock.tick(30)
      DS.fill((0, 0, 0))





      share|improve this answer




























        0














        Personally I've never used pygame's sprite module.



        import pygame

        class character:
        def __init__(self, x, y):
        self.x = x
        self.y = y
        self.sprites = [pygame.image.load("img1.png"), pygame.image.load("img2.png")]
        self.frame = 0

        def draw(self, surface):
        surface.blit(self.sprites[self.frame], (self.x, self.y))
        self.frame += 1
        if self.frame > len(self.sprites) - 1: self.frame = 0

        pygame.init()
        DS = pygame.display.set_mode((1280, 720))
        clock = pygame.time.Clock()

        c = character(640, 360)

        while True:
        for event in pygame.event.get():
        if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
        pygame.quit()

        c.draw(DS)
        pygame.display.update()
        clock.tick(30)
        DS.fill((0, 0, 0))





        share|improve this answer


























          0












          0








          0







          Personally I've never used pygame's sprite module.



          import pygame

          class character:
          def __init__(self, x, y):
          self.x = x
          self.y = y
          self.sprites = [pygame.image.load("img1.png"), pygame.image.load("img2.png")]
          self.frame = 0

          def draw(self, surface):
          surface.blit(self.sprites[self.frame], (self.x, self.y))
          self.frame += 1
          if self.frame > len(self.sprites) - 1: self.frame = 0

          pygame.init()
          DS = pygame.display.set_mode((1280, 720))
          clock = pygame.time.Clock()

          c = character(640, 360)

          while True:
          for event in pygame.event.get():
          if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
          pygame.quit()

          c.draw(DS)
          pygame.display.update()
          clock.tick(30)
          DS.fill((0, 0, 0))





          share|improve this answer













          Personally I've never used pygame's sprite module.



          import pygame

          class character:
          def __init__(self, x, y):
          self.x = x
          self.y = y
          self.sprites = [pygame.image.load("img1.png"), pygame.image.load("img2.png")]
          self.frame = 0

          def draw(self, surface):
          surface.blit(self.sprites[self.frame], (self.x, self.y))
          self.frame += 1
          if self.frame > len(self.sprites) - 1: self.frame = 0

          pygame.init()
          DS = pygame.display.set_mode((1280, 720))
          clock = pygame.time.Clock()

          c = character(640, 360)

          while True:
          for event in pygame.event.get():
          if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
          pygame.quit()

          c.draw(DS)
          pygame.display.update()
          clock.tick(30)
          DS.fill((0, 0, 0))






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 14:25









          cookertroncookertron

          677




          677

























              0














              Needed to globalise the function ("global Antic" in the main loop)






              share|improve this answer




























                0














                Needed to globalise the function ("global Antic" in the main loop)






                share|improve this answer


























                  0












                  0








                  0







                  Needed to globalise the function ("global Antic" in the main loop)






                  share|improve this answer













                  Needed to globalise the function ("global Antic" in the main loop)







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 10 at 10:16









                  Benedict SteeleBenedict Steele

                  11




                  11






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428525%2fpython-2d-sprite-animation%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Create new schema in PostgreSQL using DBeaver

                      Deepest pit of an array with Javascript: test on Codility

                      Costa Masnaga