{"id":900,"date":"2018-08-03T18:38:33","date_gmt":"2018-08-03T16:38:33","guid":{"rendered":"http:\/\/pythonprogramming.altervista.org\/?p=900"},"modified":"2018-08-27T07:54:40","modified_gmt":"2018-08-27T05:54:40","slug":"pygame-animate-a-sprite","status":"publish","type":"post","link":"https:\/\/pythonprogramming.altervista.org\/pygame-animate-a-sprite\/","title":{"rendered":"Pygame: Animate a sprite"},"content":{"rendered":"<h2>Dive into Pygame<\/h2>\n<div style=\"background: black;\"><center><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-930\" src=\"http:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/mariowalk.gif\" alt=\"\" width=\"36\" height=\"77\" \/><br \/>\n<center><\/center><\/center><\/div>\n<p>We can use pygame to make games, but games can be used not only for entertaining. In fact we could use this module for educational purporses. Anyway, we will explore the basic stuff. As usual, we will dive into the practical examples for useful stuff, instead of long introductions. So, not to deny what I just wrote, let&#8217;s dive into pygame right now.<\/p>\n<h2>Did you import pygame?<\/h2>\n<p>First thing to do is import pygame. At the moment we&#8217;ve arrived at 1.9.4, release on july 2018.<\/p>\n<pre class=\"lang:default decode:true \">\"\"\"Dive into pygame.\r\n\r\nA close look at programming trough games\r\n\"\"\"\r\n\r\nimport pygame as pg<\/pre>\n<h2>Pygame zero anyone?<\/h2>\n<p>If you installed pgzero (go to see the article about this modules), you have pygame module yet, because pygame zero is based on pygame as the name suggests obviously.<\/p>\n<figure id=\"attachment_901\" aria-describedby=\"caption-attachment-901\" style=\"width: 1053px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-901 size-full\" src=\"http:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/mario_screen.png\" alt=\"The animation and the welcome text of pygame 1.9.4\" width=\"1053\" height=\"683\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/mario_screen.png 1053w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/mario_screen-320x208.png 320w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/mario_screen-768x498.png 768w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/mario_screen-960x623.png 960w\" sizes=\"auto, (max-width: 1053px) 100vw, 1053px\" \/><figcaption id=\"caption-attachment-901\" class=\"wp-caption-text\">The animation and the welcome text of pygame 1.9.4<\/figcaption><\/figure>\n<h2>The basic window<\/h2>\n<p>We need some code to see a simple window:<\/p>\n<ul>\n<li>we define width and height of the screen<\/li>\n<li>use the set_mode method to give the measures of the screen<\/li>\n<li>we create an infinite loop to get the user imput<\/li>\n<li>if we close the window then we quit pygame<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \">import pygame as pg\r\n\r\nW = 800\r\nH = 600\r\n\r\ndisplay = pg.display.set_mode((W, H))\r\npg.display.set_caption(\"Mario Game\")\r\n\r\n\r\nclock = pg.time.Clock()\r\n\r\ncrashed = False\r\n\r\n# infinite loop, until you close the window\r\nwhile not crashed:\r\n        # pc waits for an event (user input)\r\n\tfor event in pg.event.get():\r\n                # the only event is the quit of the window\r\n\t\tif event.type == pg.QUIT:\r\n                        # if you press the quit button the loop ends and pygame quits\r\n\t\t\tcrashed = True\r\n        # if you do not do anything the window continues to update\r\n\tpg.display.update()\r\n        # this is the framerate\r\n\tclock.tick(60)\r\n\r\npg.quit()<\/pre>\n<p>&nbsp;<\/p>\n<h2>Load an image<\/h2>\n<pre class=\"lang:default decode:true \">img = pygame.image.load(\"mario_1.png\")<\/pre>\n<h2>Load all the image in a folder starting with &#8220;mario&#8221;<\/h2>\n<pre class=\"lang:default decode:true\">import glob\r\n\r\nmario = glob.glob(\"mario*.png\")\r\n\r\n# mario is a list with all the name of the files\r\n# that starts with mario, followed by anithing\r\n# (i.e. numerbers 1, 2, 3...) and ending with .png\r\n\r\nmario_img = []\r\nfor png in mario:\r\n    mario_img.append(pg.image.load(png))<\/pre>\n<h2>Display the image on the screen<\/h2>\n<p>After we charged all the images in the folder in mario_image list of images we display the second one (mario_img[1]*).<\/p>\n<p>* the lists starts from 0, so 1 is the second item.<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true \">import pygame as pg\r\nimport glob\r\n\r\npg.init()\r\nw = 800\r\nh = 600\r\nscreen = pg.display.set_mode((w, h))\r\nclock = pg.time.Clock()\r\nmario = glob.glob(\"*.png\")\r\n\r\n# mario is a list with all the name of the files\r\n# that starts with mario, followed by anithing\r\n# (i.e. numerbers 1, 2, 3...) and ending with .png\r\n\r\nmario_img = []\r\nfor png in mario:\r\n    mario_img.append(pg.image.load(png))\r\n\r\nend = False\r\n\r\nwhile not end:\r\n    screen.fill((0, 0, 0))\r\n    screen.blit(mario_img[1], (10, 10))\r\n\r\n    for event in pg.event.get():\r\n        if event.type == pg.QUIT:\r\n            end = True\r\n    clock.tick(60)\r\n    pg.display.update()\r\npg.quit()<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<h2>Move left and right<\/h2>\n<p>In this code we take all the pictures in a folder (png) and we use the to animate the chacter walking.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-935 aligncenter\" src=\"http:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/manysprites.png\" alt=\"\" width=\"690\" height=\"108\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/manysprites.png 690w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/manysprites-320x50.png 320w\" sizes=\"auto, (max-width: 690px) 100vw, 690px\" \/><\/p>\n<div style=\"background: black;\"><center><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-930\" src=\"http:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/alienwalk.gif\" alt=\"\" width=\"36\" height=\"77\" \/><br \/>\n<center><\/center><\/center><\/div>\n<pre class=\"lang:default decode:true\">\"\"\"Install pygame with pgzero.\r\n\r\npip install pgzero\r\n\"\"\"\r\n\r\n\r\nimport pygame\r\nimport sys\r\nimport glob\r\n\r\npygame.init()\r\n\r\nh = 400\r\nw = 800\r\n\r\nscreen = pygame.display.set_mode((w, h))\r\nclock = pygame.time.Clock()\r\n\r\n\r\nclass Player:\r\n    def __init__(self):\r\n        self.x = 200\r\n        self.y = 300\r\n        self.speed_init = 10\r\n        self.speed = self.speed_init\r\n        self.ani = glob.glob(\"*.png\")\r\n        self.ani.sort()\r\n        self.ani_pos = 0\r\n        self.ani_max = len(self.ani) - 1\r\n        self.img = pygame.image.load(self.ani[0])\r\n        self.update(0)\r\n\r\n    def update(self, pos):\r\n        if pos != 0:\r\n            self.speed -= 1\r\n            self.x += pos\r\n            if self.speed == 0:\r\n                self.img = pygame.image.load(self.ani[self.ani_pos])\r\n                self.speed = self.speed_init\r\n                if self.ani_pos == self.ani_max:\r\n                    self.ani_pos = 0\r\n                else:\r\n                    self.ani_pos += 1\r\n        screen.blit(self.img, (self.x, self.y))\r\n\r\n\r\nplayer = Player()\r\npos = 0\r\n\r\ncrashed = False\r\nright = 0\r\nwhile not crashed:\r\n    screen.fill((0, 0, 0))\r\n    clock.tick(60)\r\n\r\n    for event in pygame.event.get():\r\n        if event.type == pygame.QUIT:\r\n            crashed = True\r\n        elif right == 1:\r\n            pos +=1\r\n            if pos == len(player.ani):\r\n                right = 0\r\n        elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:\r\n            pos += 1\r\n            #right = 1\r\n        elif event.type == pygame.KEYUP and event.key == pygame.K_LEFT:\r\n            pos = 0\r\n        elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:\r\n            pos = -1\r\n        elif event.type == pygame.KEYUP and event.key == pygame.K_RIGHT:\r\n            pos = 0\r\n\r\n    player.update(pos)\r\n    pygame.display.update()\r\n\r\npygame.quit()<\/pre>\n<h2>Moving costantly<\/h2>\n<p>Now the character moves continuosly left and right<\/p>\n<pre class=\"lang:default decode:true\">\"\"\"Install pygame with pgzero.\r\n\r\npip install pgzero\r\n\"\"\"\r\n\r\n\r\nimport pygame\r\nimport sys\r\nimport glob\r\n\r\npygame.init()\r\n\r\nh = 400\r\nw = 800\r\n\r\nscreen = pygame.display.set_mode((w, h))\r\nclock = pygame.time.Clock()\r\n\r\n\r\nclass Player:\r\n    def __init__(self):\r\n        self.x = 200\r\n        self.y = 300\r\n        self.speed_init = 10\r\n        self.speed = self.speed_init\r\n        self.ani = glob.glob(\"*.png\")\r\n        self.ani.sort()\r\n        self.ani_pos = 0\r\n        self.ani_max = len(self.ani) - 1\r\n        self.img = pygame.image.load(self.ani[0])\r\n        self.update(0)\r\n\r\n    def update(self, pos):\r\n        if pos != 0:\r\n            self.speed -= 1\r\n            self.x += pos\r\n            if self.speed == 0:\r\n                self.img = pygame.image.load(self.ani[self.ani_pos])\r\n                self.speed = self.speed_init\r\n                if self.ani_pos == self.ani_max:\r\n                    self.ani_pos = 0\r\n                else:\r\n                    self.ani_pos += 1\r\n        screen.blit(self.img, (self.x, self.y))\r\n\r\n\r\nplayer = Player()\r\npos = 0\r\n\r\ncrashed = False\r\n\r\nwhile not crashed:\r\n    screen.fill((0, 0, 0))\r\n    clock.tick(60)\r\n\r\n    for event in pygame.event.get():\r\n        if event.type == pygame.QUIT:\r\n            crashed = True\r\n        elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:\r\n            pos += 1\r\n        # when KEYUP the alien continues to move forward\r\n        elif event.type == pygame.KEYUP and event.key == pygame.K_RIGHT:\r\n            if pos &lt; len(player.ani):\r\n                pos += 1\r\n        elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:\r\n            pos = -1\r\n        # when KEYUP the alien continues to move backward\r\n        elif event.type == pygame.KEYUP and event.key == pygame.K_LEFT:\r\n            if pos &gt; 0:\r\n                pos -= 1\r\n\r\n    player.update(pos)\r\n    pygame.display.update()\r\n\r\npygame.quit()<\/pre>\n<h2>Moving at different speed<\/h2>\n<p>This time we made the alien move incrementally when pressing the left and right arrow.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-921\" src=\"http:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/text.png\" alt=\"\" width=\"805\" height=\"427\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/text.png 805w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/text-320x170.png 320w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2018\/08\/text-768x407.png 768w\" sizes=\"auto, (max-width: 805px) 100vw, 805px\" \/><\/p>\n<pre class=\"lang:default decode:true\">\"\"\"Install pygame with pgzero.\r\n\r\npip install pgzero\r\n\"\"\"\r\n\r\n\r\nimport pygame\r\nimport glob\r\n\r\npygame.init()\r\n\r\nh = 400\r\nw = 800\r\n\r\nscreen = pygame.display.set_mode((w, h))\r\nclock = pygame.time.Clock()\r\npygame.font.init()  # you have to call this at the start,\r\n# if you want to use this module.\r\nmyfont = pygame.font.SysFont('Comic Sans MS', 30)\r\ntextsurface = myfont.render('Right or left arrow to move', False, (255, 255, 255))\r\nvelocity = myfont.render('...', False, (255, 255, 255))\r\n\r\n\r\nclass Player:\r\n    def __init__(self):\r\n        self.x = 300\r\n        self.y = 200\r\n        self.speed_init = 10\r\n        self.speed = self.speed_init\r\n        self.ani = glob.glob(\"*.png\")\r\n        self.ani.sort()\r\n        self.ani_pos = 1\r\n        self.ani_max = len(self.ani) - 1\r\n        self.img = pygame.image.load(self.ani[0])\r\n        self.update(0)\r\n\r\n    def update(self, pos):\r\n        if pos != 0:\r\n            self.speed -= 2\r\n            self.x += pos\r\n            if self.speed == 0:\r\n                self.img = pygame.image.load(self.ani[self.ani_pos])\r\n                self.speed = self.speed_init\r\n                if self.ani_pos == self.ani_max:\r\n                    self.ani_pos = 0\r\n                else:\r\n                    self.ani_pos += 1\r\n        elif self.speed == 0:\r\n            self.img = pygame.image.load(self.ani[self.ani_pos])\r\n            self.speed = self.speed_init\r\n            if self.ani_pos == self.ani_max:\r\n                self.ani_pos = 0\r\n            else:\r\n                self.ani_pos += 1\r\n        screen.blit(self.img, (self.x, self.y))\r\n\r\n\r\nplayer = Player()\r\npos = 0\r\n\r\ncrashed = False\r\n\r\nwhile not crashed:\r\n    screen.fill((0, 0, 0))\r\n    clock.tick(60)\r\n    screen.blit(textsurface, (0, 0))\r\n    screen.blit(velocity, (0, 40))\r\n\r\n    for event in pygame.event.get():\r\n        if event.type == pygame.QUIT:\r\n            crashed = True\r\n\r\n        # MOVE RIGHT\r\n        elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:\r\n            if pos &lt; 5:  # max velocity = 5\r\n                pos += 1  # pos -= 1 # velocit\u00e0 incrementale\r\n                velocity = myfont.render('Velocit\u00e0 ' + str(pos), False, (255, 255, 255))\r\n            \"\"\"\r\n        elif event.type == pygame.KEYUP and event.key == pygame.K_RIGHT:\r\n            if pos &lt; len(player.ani):\r\n                pos = +1\r\n\"\"\"\r\n        # MOVE LEFT\r\n        elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:\r\n            if pos &gt; -5:  # max velocity -5\r\n                pos -= 1  # pos -= 1 # velocit\u00e0 incrementale\r\n                velocity = myfont.render('Velocit\u00e0 ' + str(pos), False, (255, 255, 255))\r\n        \"\"\"\r\n        elif event.type == pygame.KEYUP and event.key == pygame.K_LEFT:\r\n            if pos &gt; 0:\r\n                pos = -1\r\n\"\"\"\r\n    player.update(pos)\r\n    pygame.display.update()\r\n\r\npygame.quit()\r\n<\/pre>\n<p><iframe loading=\"lazy\" title=\"Pygame: alien moves at different speed\" width=\"747\" height=\"560\" src=\"https:\/\/www.youtube.com\/embed\/3ltPseVxny0?feature=oembed&amp;enablejsapi=1\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<h2>How to add the text in pygame<\/h2>\n<p>Let&#8217;s take a look at how to put text on the screen.<\/p>\n<p><iframe loading=\"lazy\" title=\"Text in pygame\" width=\"747\" height=\"560\" src=\"https:\/\/www.youtube.com\/embed\/bBfG8bmTVhk?feature=oembed&amp;enablejsapi=1\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<h2>Making the sprite reappear from the opposite site<\/h2>\n<p>Adding this code we will make the sprite reappear from the opposite border when he moves too much on the left or on the right.<\/p>\n<p>The code added in the method update of the class player is this<\/p>\n<pre class=\"lang:default decode:true \">        if self.x &gt; 800:\r\n            self.x = -60\r\n        elif self.x &lt; -80:\r\n            self.x = 790<\/pre>\n<p>The whole code now is the following:<\/p>\n<pre class=\"lang:default decode:true\">\"\"\"Install pygame with pgzero.\r\n\r\npip install pgzero\r\n\"\"\"\r\n\r\n\r\nimport pygame\r\nimport glob\r\n\r\npygame.init()\r\n\r\nh = 400\r\nw = 800\r\n\r\nscreen = pygame.display.set_mode((w, h))\r\nclock = pygame.time.Clock()\r\n\r\n# =========== FONT ==============\r\npygame.font.init()\r\nmyfont = pygame.font.SysFont('Comic Sans MS', 30)\r\ntextsurface = myfont.render('Right or left arrow to move', False, (255, 255, 255))\r\nvelocity = myfont.render('...', False, (0, 255, 0))\r\n\r\n\r\nclass Player:\r\n    def __init__(self):\r\n        self.x = 300\r\n        self.y = 300\r\n        self.speed_init = 10\r\n        self.speed = self.speed_init\r\n        self.ani = glob.glob(\"*.png\")\r\n        self.ani.sort()\r\n        self.ani_pos = 1\r\n        self.ani_max = len(self.ani) - 1\r\n        self.img = pygame.image.load(self.ani[0])\r\n        self.update(0)\r\n\r\n    def update(self, pos):\r\n        if pos != 0:\r\n            self.speed -= 2\r\n            self.x += pos\r\n            if self.speed == 0:\r\n                self.img = pygame.image.load(self.ani[self.ani_pos])\r\n                self.speed = self.speed_init\r\n                if self.ani_pos == self.ani_max:\r\n                    self.ani_pos = 0\r\n                else:\r\n                    self.ani_pos += 1\r\n        elif self.speed == 0:\r\n            self.img = pygame.image.load(self.ani[self.ani_pos])\r\n            self.speed = self.speed_init\r\n            if self.ani_pos == self.ani_max:\r\n                self.ani_pos = 0\r\n            else:\r\n                self.ani_pos += 1\r\n        if self.x &gt; 800:\r\n            self.x = -60\r\n        elif self.x &lt; -80:\r\n            self.x = 790\r\n        screen.blit(self.img, (self.x, self.y))\r\n\r\n\r\nplayer = Player()\r\npos = 0\r\n\r\ncrashed = False\r\n\r\nwhile not crashed:\r\n    screen.fill((0, 0, 0))\r\n    clock.tick(60)\r\n    screen.blit(textsurface, (0, 0))\r\n    screen.blit(velocity, (0, 40))\r\n\r\n    for event in pygame.event.get():\r\n        if event.type == pygame.QUIT:\r\n            crashed = True\r\n        elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:\r\n            if pos &lt; 5:  # max velocity = 5\r\n                pos += 1  # pos -= 1 # velocit\u00e0 incrementale\r\n                velocity = myfont.render('Speed ' + str(pos), False, (0, 255, 0))\r\n        elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:\r\n            if pos &gt; -5:  # max velocity -5\r\n                pos -= 1  # pos -= 1 # velocit\u00e0 incrementale\r\n                velocity = myfont.render('Speed ' + str(pos), False, (0, 255, 0))\r\n    player.update(pos)\r\n    pygame.display.update()\r\n\r\npygame.quit()\r\n<\/pre>\n<h2>Some improvements to the animation and a soundtrack<\/h2>\n<p>In this code I used more frames (you can put how many frames you want in the folder and the code will add them, they have to start with p1_walk and then have a progressive number). The track also can be random from all the wav files that are there in the music directory. I used the pgzrun module to load the music (to install pgzrun write pip install pgzero).<\/p>\n<pre class=\"lang:default decode:true \">\"\"\"Install pygame with pgzero.\r\n\r\npip install pgzero\r\n\"\"\"\r\n\r\nimport pygame\r\nimport glob\r\nfrom pgzrun import *\r\nfrom random import choice\r\n\r\n\r\npygame.init()\r\nh = 400\r\nw = 800\r\n\r\nscreen = pygame.display.set_mode((w, h))\r\nclock = pygame.time.Clock()\r\n\r\n# =========== FONT ==============\r\npygame.font.init()\r\nmyfont = pygame.font.SysFont('Comic Sans MS', 30)\r\ntextsurface = myfont.render('Right or left arrow to move', False, (255, 255, 255))\r\nvelocity = myfont.render('...', False, (0, 255, 0))\r\n\r\nmusic.play(choice(glob.glob(\"music\/*.wav\"))[6:])\r\n\r\n\r\nclass Player:\r\n    def __init__(self):\r\n        self.x = 300\r\n        self.y = 300\r\n        self.speed_init = 10\r\n        self.speed = self.speed_init\r\n        # list of images for the animation\r\n        self.ani = glob.glob(\"p1_walk*.png\")\r\n        self.ani.sort()\r\n        self.ani_pos = 1\r\n        self.ani_max = len(self.ani) - 1\r\n        self.img = pygame.image.load(self.ani[0])\r\n        self.update(0)\r\n\r\n    def update(self, pos):\r\n        if pos != 0:\r\n            self.speed -= 2\r\n            self.x += pos\r\n            if self.speed == 0:\r\n                self.img = pygame.image.load(self.ani[self.ani_pos])\r\n                self.speed = self.speed_init\r\n                if self.ani_pos == self.ani_max:\r\n                    self.ani_pos = 0\r\n                else:\r\n                    self.ani_pos += 1\r\n        elif self.speed == 0:\r\n            self.img = pygame.image.load(self.ani[self.ani_pos])\r\n            self.speed = self.speed_init\r\n            if self.ani_pos == self.ani_max:\r\n                self.ani_pos = 0\r\n            else:\r\n                self.ani_pos += 1\r\n        if self.x &gt; 800:\r\n            self.x = -60\r\n        elif self.x &lt; -80:\r\n            self.x = 790\r\n        if pos == 0:\r\n            self.img = pygame.image.load(self.ani[0])\r\n        screen.blit(self.img, (self.x, self.y))\r\n\r\n\r\nplayer = Player()\r\npos, crashed = 0, False\r\n\r\n\r\ndef speed_render(pos):\r\n    global velocity\r\n    velocity = myfont.render('Speed ' + str(pos), False, (0, 255, 0))\r\n\r\n\r\nwhile not crashed:\r\n    screen.fill((0, 0, 0))\r\n    clock.tick(60)\r\n    screen.blit(textsurface, (0, 0))\r\n    screen.blit(velocity, (0, 40))\r\n\r\n    for event in pygame.event.get():\r\n        if event.type == pygame.QUIT:\r\n            crashed = True\r\n\r\n        if event.type == pygame.KEYDOWN:\r\n            if event.key == pygame.K_RIGHT:\r\n                if pos &lt; 5:  # max velocity = 5\r\n                    pos += 1  # pos -= 1 # velocit\u00e0 incrementale\r\n                    speed_render(pos)\r\n            elif event.key == pygame.K_LEFT:\r\n                if pos &gt; -5:  # max velocity -5\r\n                    pos -= 1  # pos -= 1 # velocit\u00e0 incrementale\r\n                    speed_render(pos)\r\n\r\n    player.update(pos)\r\n    pygame.display.update()\r\n\r\npygame.quit()\r\n<\/pre>\n<p>This video shows the animation&#8230; it is smoother in the reality, if you see that it is not so smooth it is for the frame rate of the video.<\/p>\n<p><iframe loading=\"lazy\" title=\"Animation with pygame\" width=\"747\" height=\"420\" src=\"https:\/\/www.youtube.com\/embed\/45txweHcyLs?feature=oembed&amp;enablejsapi=1\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<h2>Convert and preload<\/h2>\n<p>To convert the images in a faster type of image we used &#8220;convert()&#8221; method to the loaded images.<\/p>\n<p>We also created a list of loaded image objects, so that the code is shorter and clearer and I hope it&#8217;s execution is faster too.<\/p>\n<pre class=\"lang:default decode:true \">self.ani_obj = []\r\n        # create a list of object converted, not to load everytime the images\r\n        for img in self.ani:\r\n            self.ani_obj.append(pygame.image.load(img).convert())\r\n        self.img = self.ani_obj[0]<\/pre>\n<p>Now the whole code looks like this:<\/p>\n<pre class=\"lang:default decode:true \">\"\"\"Install pygame with pgzero.\r\n\r\npip install pgzero\r\n\"\"\"\r\n\r\nimport pygame\r\nimport glob\r\nfrom pgzrun import *\r\nfrom random import choice\r\n\r\n\r\npygame.init()\r\nh = 400\r\nw = 800\r\n\r\nscreen = pygame.display.set_mode((w, h))\r\nclock = pygame.time.Clock()\r\n\r\n# =========== FONT ==============\r\npygame.font.init()\r\nmyfont = pygame.font.SysFont('Comic Sans MS', 30)\r\ntextsurface = myfont.render('Right or left arrow to move', False, (255, 255, 255))\r\nvelocity = myfont.render('...', False, (0, 255, 0))\r\n\r\nmusic.play(choice(glob.glob(\"music\/*.wav\"))[6:])\r\n\r\n\r\nclass Player:\r\n    def __init__(self):\r\n        self.x = 300\r\n        self.y = 300\r\n        self.speed_init = 10\r\n        self.speed = self.speed_init\r\n        # list of images for the animation\r\n        self.ani = glob.glob(\"p1_walk*.png\")\r\n        self.ani.sort()\r\n        self.ani_pos = 1\r\n        self.ani_max = len(self.ani) - 1\r\n        self.ani_obj = []\r\n        # create a list of object converted, not to load everytime the images\r\n        for img in self.ani:\r\n            self.ani_obj.append(pygame.image.load(img).convert())\r\n        self.img = self.ani_obj[0]\r\n        self.update(0)\r\n\r\n    def update(self, pos):\r\n        if pos != 0:\r\n            self.speed -= 2\r\n            self.x += pos\r\n            if self.speed == 0:\r\n                self.img = self.ani_obj[self.ani_pos]\r\n                self.speed = self.speed_init\r\n                if self.ani_pos == self.ani_max:\r\n                    self.ani_pos = 0\r\n                else:\r\n                    self.ani_pos += 1\r\n        elif self.speed == 0:\r\n            self.img = self.ani_obj[self.ani_pos]\r\n            self.speed = self.speed_init\r\n            if self.ani_pos == self.ani_max:\r\n                self.ani_pos = 0\r\n            else:\r\n                self.ani_pos += 1\r\n        if self.x &gt; 800:\r\n            self.x = -60\r\n        elif self.x &lt; -80:\r\n            self.x = 790\r\n        if pos == 0:\r\n            self.img = self.ani_obj[0]\r\n        screen.blit(self.img, (self.x, self.y))\r\n\r\n\r\nplayer = Player()\r\npos, crashed = 0, False\r\n\r\n\r\ndef speed_render(pos):\r\n    global velocity\r\n    velocity = myfont.render('Speed ' + str(pos), False, (0, 255, 0))\r\n\r\n\r\nwhile not crashed:\r\n    screen.fill((0, 0, 0))\r\n    clock.tick(60)\r\n    screen.blit(textsurface, (0, 0))\r\n    screen.blit(velocity, (0, 40))\r\n\r\n    for event in pygame.event.get():\r\n        if event.type == pygame.QUIT:\r\n            crashed = True\r\n\r\n        if event.type == pygame.KEYDOWN:\r\n            if event.key == pygame.K_RIGHT:\r\n                if pos &lt; 5:  # max velocity = 5\r\n                    pos += 1  # pos -= 1 # velocit\u00e0 incrementale\r\n                    speed_render(pos)\r\n            elif event.key == pygame.K_LEFT:\r\n                if pos &gt; -5:  # max velocity -5\r\n                    pos -= 1  # pos -= 1 # velocit\u00e0 incrementale\r\n                    speed_render(pos)\r\n\r\n    player.update(pos)\r\n    pygame.display.update()\r\n\r\npygame.quit()\r\n<\/pre>\n<p><iframe loading=\"lazy\" title=\"Pygame convert and preload http:\/\/pythonprogramming.altervista.org\/pygame-animate-a-sprite\/\" width=\"747\" height=\"420\" src=\"https:\/\/www.youtube.com\/embed\/roHz9AH9IXE?feature=oembed&amp;enablejsapi=1\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<h3>Pygame's Platform Game<\/h3>\r\n\r\n<a href=\"https:\/\/pythonprogramming.altervista.org\/pygame-platform-game-5-sounds-and-mixer\/\"><img decoding=\"async\" src=\"https:\/\/i1.wp.com\/pythonprogramming.altervista.org\/wp-content\/uploads\/2020\/01\/climbercover.png?w=557&ssl=1\"\/ width=\"50%\"><\/a>\r\n<script>\r\nvar title = \"Platform Pygame\";\r\n\t\tvar links = [\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-animation-of-a-sprite-v-1-3\/\",\"Animation 1.3\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-sprite-animation-v-2-better-coding-test-it-checking-fps-on-the-screen\/\",\"Animation 1.2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-how-to-display-the-frame-rate-fps-on-the-screen\/\",\"Display Frame rate\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-sprite-animation-update\/\",\"Animation 1.1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platformer-1\/\",\"Pygame Platform Game 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/python-platform-game-2\/\",\"Pygame Platform 2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platform-game-3-recap-cheatsheet\/\",\"Pygame PLatform 3 - recap and some Cheat Sheet\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platform-game-4-background-and-stuffs\/\",\"Pygame Platform 4 - Background & organizing code\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platform-game-5-sounds-and-mixer\/\",\"Pygame Platform 5 - Sounds\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/platform-game-in-detail-part-1\/\",\"Game in detail part 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/map-maker-1-2\/\", \"Map maker 1.2\"]\r\n\t\t];\r\n\t\t<\/script>\r\n<script>\r\n\t\r\nif (typeof next2 != \"undefined\"){let next2 = 0;}\r\n\t\r\nnext2 = 0;\r\n\thtml = \"\";\/\/<b style='color:coral;font-size:1.2em'>Other posts about \" + title + \"<\/b><br>\";\r\nfor (address of links) \r\n{\r\n\r\n\tif (next2 == 1){\r\n\t\thtml += \"<div style='background:coral'>\";\r\n\t\thtml += \"Next link => <a href='\" + address[0] + \"'>\" + address[1] + \"<\/a>\";\r\n\t\thtml += \"<\/div><br>\";\r\n\t\tnext2 = 0;\r\n\t}\r\n\tif (address[0] == document.URL) {\r\n\t\tnext2 = 1;\r\n\t}\r\n}\r\n\r\nif (typeof next != \"undefined\") {let next = 0;}\r\nif (typeof addressStart != \"undefined\") {let addressStart = \"\";}\r\nnext = 0;\r\naddressStart = \"<a href='\";\r\nfor (address of links) {\r\n\tif (next == 1){\r\n\t\thtml += \">>>\" + addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t\tnext = 0;\r\n\t}\r\n\telse if (addressStart + address[0] != document.URL)\r\n\t{\r\n\t\thtml += addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnext = 1;\r\n\t\tnext_address = address[0]\r\n\t\tnext_title = address[1]\r\n\t\thtml += \"<span style='color:gray'>\" + address[1] + \"<\/span><br>\";\r\n\t}\r\n\r\n}\r\n\r\n\thtml += `<span style=\"font-size:8px\">Powered by <a href=\"https:\/\/pythonprogramming.altervista.org\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2673\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png\" alt=\"\" width=\"70\" height=\"25\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png 156w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2-150x56.png 150w\" sizes=\"auto, (max-width: 70px) 100vw, 70px\" \/>pythonprogramming.altervista.org<\/a><\/span>`\r\n\thtml = \"<div style='background:yellow'>\" + html + \"<\/div>\";\r\n\tdocument.write(html)\r\n<\/script>\r\n\r\n<h3>Other Pygame's posts<\/h3>\r\n\r\n<script>\r\nvar title = \"Pygame's Posts\"\r\nvar links = [\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-platformer-1\/\",\"Platform game 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/make-a-platform-game-with-pygame-dafluffypotato\/\",\"DaFluffyPotato Platform Tutorials\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/python-and-classic-arcade-games-pong\/\",\"Pong Game Full\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/python-draws-in-colors-app-to-draw-with-pygame\/\",\"PyGameGIF 2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-draw-app-with-animation\/\",\"PyGameGIF 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pydraw-2-0-app-to-draw-gif\/\",\"PyDraw 2.0\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-drawing-2\/\",\"Draw with Pygame\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/animation-with-pygame\",\"Sprite animation 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/animation-on-pygame-2-free-characters-and-more-actions\/\",\"Sprite animation 2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/starting-with-pygame\/\",\"Starting movements with Pygame\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-3-move-sprite\/\", \"Move a Sprite\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-4-fonts\/\",\"Text and Fonts\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-animate-a-sprite\/\", \"Animate a sprite\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pygame-and-mouse-events\/\",\"Mouse events\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/pgp-aka-pygamepresentation-project\/\",\"Pygame presentation\"],\r\n\t[\"https:\/\/pythonprogramming.altervista.org\/moving-the-player-in-pygame-with-key-get_pressed\/\",\"How to use key.get_pressed()\"]\r\n]\r\n<\/script>\r\n\r\n\r\n<script>\r\n\t\r\nif (typeof next2 != \"undefined\"){let next2 = 0;}\r\n\t\r\nnext2 = 0;\r\n\thtml = \"\";\/\/<b style='color:coral;font-size:1.2em'>Other posts about \" + title + \"<\/b><br>\";\r\nfor (address of links) \r\n{\r\n\r\n\tif (next2 == 1){\r\n\t\thtml += \"<div style='background:coral'>\";\r\n\t\thtml += \"Next link => <a href='\" + address[0] + \"'>\" + address[1] + \"<\/a>\";\r\n\t\thtml += \"<\/div><br>\";\r\n\t\tnext2 = 0;\r\n\t}\r\n\tif (address[0] == document.URL) {\r\n\t\tnext2 = 1;\r\n\t}\r\n}\r\n\r\nif (typeof next != \"undefined\") {let next = 0;}\r\nif (typeof addressStart != \"undefined\") {let addressStart = \"\";}\r\nnext = 0;\r\naddressStart = \"<a href='\";\r\nfor (address of links) {\r\n\tif (next == 1){\r\n\t\thtml += \">>>\" + addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t\tnext = 0;\r\n\t}\r\n\telse if (addressStart + address[0] != document.URL)\r\n\t{\r\n\t\thtml += addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnext = 1;\r\n\t\tnext_address = address[0]\r\n\t\tnext_title = address[1]\r\n\t\thtml += \"<span style='color:gray'>\" + address[1] + \"<\/span><br>\";\r\n\t}\r\n\r\n}\r\n\r\n\thtml += `<span style=\"font-size:8px\">Powered by <a href=\"https:\/\/pythonprogramming.altervista.org\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2673\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png\" alt=\"\" width=\"70\" height=\"25\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png 156w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2-150x56.png 150w\" sizes=\"auto, (max-width: 70px) 100vw, 70px\" \/>pythonprogramming.altervista.org<\/a><\/span>`\r\n\thtml = \"<div style='background:yellow'>\" + html + \"<\/div>\";\r\n\tdocument.write(html)\r\n<\/script>\n","protected":false},"excerpt":{"rendered":"Pygame: how to animate a sprite\n<a class=\"moretag\" href=\"https:\/\/pythonprogramming.altervista.org\/pygame-animate-a-sprite\/\"> [...]<\/a>","protected":false},"author":1,"featured_media":937,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[1,154,191],"tags":[219,218,217,194],"class_list":["post-900","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples","category-games","category-pygame","tag-animation","tag-font","tag-font-render","tag-pygame"],"avopt_banners_inside_post":true,"avopt_banners_on_page":true,"av_copy_from":"","av_sharing_message":"","av_sharing_allowed":false,"av_sharing_on":{"fb":[],"tw":[]},"av_allow_affiliate_banner":false,"av_allow_affiliate_multi_banner":false,"av_show_affiliation_buy_button":false,"av_post_rating":true,"av_have_post_rating_value":false,"av_is_artificial_intelligence_content":false,"_links":{"self":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/900","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/comments?post=900"}],"version-history":[{"count":22,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/900\/revisions"}],"predecessor-version":[{"id":976,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/900\/revisions\/976"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media\/937"}],"wp:attachment":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media?parent=900"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/categories?post=900"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/tags?post=900"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}