Python Pygame Tutorial - Sprite Sheets

Поделиться
HTML-код
  • Опубликовано: 6 окт 2024
  • Thank you for watching my video and I really hope you found something useful.
    Pygame on Facebook: www. gro...
    Hello to you! In this episode I'll be examining sprite
    sheets and blitting individual cells to the display
    surface.
    If you'd like to know how to install and run your first Python Pygame script then watch my first video here: • Python Pygame Tutorial...
    Download the script and image files for this tutorial here:
    drive.google.c...
    You can find all the scripts here in my Google Drive Folder goo.gl/PeBc0Y
    ... and if you have any comments then feel free but bear in mind I don't pretend to be an expert, I just enjoying using Python and Pygame.
    Anthony
    Downloads:
    Python 2.7.x ....... www.python.org...
    Pygame 1.9.x ....... www.pygame.org/...
    Notepad++ ....... notepad-plus-p...
    Documents:
    Pygame ....... www.pygame.org...

Комментарии • 128

  • @djarrah
    @djarrah 5 лет назад +34

    Nice and useful video, thanks!
    Small note: in Python 3.7 you must write index//cols*h instead of index/cols*h, else you will get a shifted frame from index 1

    • @mattgoodman2687
      @mattgoodman2687 4 года назад

      this should be pinned for newcomers. Thanks for the video!!

    • @jboblk
      @jboblk 2 года назад

      it took me so long to figure out why the top 3 pixels were cut off, thx

  • @hossamel2006
    @hossamel2006 3 года назад +1

    You are very PRO, very thanks, you are the BEST

  • @namline9010
    @namline9010 3 года назад

    very good video with a nice explanation thank you

  • @richayers9023
    @richayers9023 3 года назад

    Thanks!

  • @aarondraws7699
    @aarondraws7699 3 года назад +1

    fyi if your using python 3 i /c will give you a float so you have to cast it to an int

  • @randor73
    @randor73 5 лет назад

    Awesome tutorial.. Not only do you show what to do, you explain why.. that is sooo lacking in most tutorials. Appreciate the efforts, New subscriber here, looking forward to watching all your tutorials,

  • @HordeCommander
    @HordeCommander 3 года назад

    your material has been so helpful. thank you so much :)

  • @Cytzix
    @Cytzix 7 лет назад +2

    For me as a total noob it was a little hard to follow first, but I sticked to the end and then broke down every line of the code to understand it. Then I've removed the handle method, since it was not necessary for my purposes and the code looked much more simple! I wished you had skipped this part in the first place, but dude, your tutorial was so awesome! I dont understand why you have so few subscribers. Thanks!

  • @Tay_T
    @Tay_T 4 года назад

    These videos are really helping me a ton. I am in a python class right now and even though you haven't made anymore videos these ones are making things a lot easier for me. We are doing our final project right now and I am trying to make a side scrolling game that is similar to the offline Google dinosaur game. I would love to see more videos in the future.

  • @codinginframes
    @codinginframes 4 года назад

    You just deliver in a very understandable way. Keep doing .

  • @benjaminpattison1907
    @benjaminpattison1907 6 лет назад

    I have always been wondering how to use sprite sheets, and I could never figure it out. Thank you! You have saved me from a lot of headaches, and have also given me new power and energy to work on my game!!

  • @Mohawk763
    @Mohawk763 3 года назад

    Looking forward to working through the other projects and tutorials you have done. Thanks.

  • @szymanek2k208
    @szymanek2k208 7 лет назад +7

    As usual a good guide and I look forward to the next.

    • @codePylet
      @codePylet  7 лет назад +1

      I'm looking at collisions now, I haven't forgotten :)

    • @szymanek2k208
      @szymanek2k208 7 лет назад +2

      Thanks, I will wait for it ;)

  • @sergiocano6248
    @sergiocano6248 7 лет назад +8

    I finally learned how to work with spritesheets. Thanks a lot. Suscribed!

    • @codePylet
      @codePylet  7 лет назад

      +Sergio Cano muchas gracias! Glad I could help. What project are you working on?

  • @DeerhunterCZ
    @DeerhunterCZ 7 лет назад

    Just discovered your channel last night. Thanks for the tutorials, they're awesome and so helpful!

    • @codePylet
      @codePylet  7 лет назад

      +DeerhunterCZ Thank you, kind of you to say :) What are you working on at the minute?

    • @DeerhunterCZ
      @DeerhunterCZ 7 лет назад

      I was working on my first pygame project, but I am fairly new to coding in general (started november 2016). I think I know a lot about python's fundamentals + some basic libraries, I am good at making pixelart and animating, so I wanted to do some pygame. But my problem is still OOP, classes and such, I don't feel like I have a full grasp on it. Made a simple game using only functions, but I just know I have to understand OOP and classes.
      Your videos helped me a lot and them + your scripts to download are great study materials, you put a great effort into explaining things to your audience. That's so much appreciated. Thanks again! Can't forget to mention your amazingly commented and readable code, that's awesome.

    • @codePylet
      @codePylet  7 лет назад

      Classes can get very complex and it's easy to lose track of which object should be interacting other. I always say, if it seems too complicated then it probably is. Keep everything as simple as possible. If a game can be made using just functions then it's still a game. If you need help tell me, I'll share what I know :)

  • @ygdrasulskarkja6195
    @ygdrasulskarkja6195 5 лет назад +3

    So thats what spritesheets are for... was getting frustrated cutting and pasting the images individually into my game

  • @haydengames3v2
    @haydengames3v2 4 года назад

    Very nicely made. I added in another variable into the draw function to create a starting point for the frame, makes it a little bit more practical I think.

  • @IdunRedstone
    @IdunRedstone 4 года назад

    Super helpful thanks a bunch! Previous tutorial had seperate images for each sprite frame which I knew i'd start finding annoying very fast so nice I can put everything in one file and work around that. I think the only thing is adding all the positioning of sprite around center x,y coords adds a lot of complexity (as in understanding/code wise for layman, not computation) but I can see why you'd want to do that for less headache in positioning things later on. Had to go through my history on browser to find this next day as didn't seem to come high up in search when I searched for this topic and I remembered this vid was good, but that's just luck of youtube magic algorithm I guess. Glad i found it again though!

  • @zenchiassassin283
    @zenchiassassin283 5 лет назад

    Good

  • @galsk2533
    @galsk2533 6 лет назад +1

    Thanks for these videos. Just discovered your channel and it has helped me so much. I am working on a 2D platform type game with a couple of my nerd-friends. Subscribed! :)

  • @theafr0842
    @theafr0842 4 года назад

    You like metal detecting?

  • @almightynoob1631
    @almightynoob1631 4 года назад

    Didn't work for the sprite i had

  • @denilsonsantos9984
    @denilsonsantos9984 7 лет назад +3

    Awsome tutorial. You have a new subscriber, and i hope to see more tutorial like this.

  • @arsnakehert
    @arsnakehert 6 лет назад

    Human being reporting in, thanks for making this, very helpful

  • @nuparuchi
    @nuparuchi 6 лет назад

    Awesome video, very helpful. Thanks a lot!

  • @Underdrummer
    @Underdrummer 5 лет назад

    Great stuff, clear explanation and very informative. Thank you!

  • @lajosvarga6544
    @lajosvarga6544 3 года назад

    This is not good for me (index % cols * w, index / cols * h, w, h) just like this (index % cols * w, int(index / cols) * h, w, h)

  • @toussainttyson2723
    @toussainttyson2723 6 лет назад

    great explanation

  • @Captain_Rhodes
    @Captain_Rhodes 7 лет назад +2

    That i%c, i/c trick is very clever. is that a standard thing or did you come up with that?

  • @georgevasiliadis4228
    @georgevasiliadis4228 6 лет назад

    Just another human being watchin your vids
    Wp

  • @gregbushta3086
    @gregbushta3086 4 года назад

    Thanks for this. I am trying to learn sprite sheets and this is helping. There are errors when using python3. The circle draw gets an error because of floats instead of integers. The sprites show up but end up scrolling up within the box they are trying to display. I think it has to do with indexing and the counting of the number or rows and columns. I am using python3 since python2 has been dropped. I'll see what I need to do to get the sprites to not scroll.

    • @gregbushta3086
      @gregbushta3086 4 года назад

      It took me a bit to find. This code runs on my MacBook just fine when called from the command line with 'python sprite_test.py' However, when calling it with 'python3 sprite_test.py' the sprite ends up scrolling toward the top of the sprite rectangle. It is like the sprite [0] is just fine but sprite [1] starts part way down the rectangle on the sprite sheet. Sprite [2] is even further down. I tracked it down to this line,"self.cells = list([(index%cols*w, index/cols*h, w, h)for index in range(self.totalCellCount)])". Python doesn't have a problem with this. Python3 doesn't like it at all. I had to put and int() into the part index/cols*w. It should be int(index/cols)*w.
      self.cells = list([(index%cols*w, int(index/cols)*h, w, h)for index in range(self.totalCellCount)])
      This will make the code run properly when calling it with 'python3 sprite_test.py'. Perhaps this is due to something in the OS X version of python3 or python3 version 3.7.6.
      I also had to put integer calls in the line that draws a little circle onto the center of the display window. pygame.draw.circle(DS, WHITE, (int(HW), int(HH)),2, 0) There would be an error with just (HW, HH) and python3 would not run but would report the error. TypeError: integer argument expected, got float
      Perhaps this is all taken care of in python3 version 3.8.x, but I had trouble with pygame on my Mac with 3.8.x
      Thank you code.Pylet for an informative video that helped me understand Sprite Sheets a whole lot more.

  • @tyrelwaggoner9608
    @tyrelwaggoner9608 6 лет назад

    Greetings, I'm getting into python codding and found your channel. First off thank you for your great videos. Second is a question. Are you a Ham Radio operator as wall as a code writer? I ask due to you intro. I love sending Morse Code in CW Mode and was instantly intrigued. Thanks and 73

  • @vicbelleton6729
    @vicbelleton6729 6 лет назад +1

    Thank you !

  • @HannazRolynn
    @HannazRolynn 4 года назад

    what if the sprite sheet is in a straight column

    • @HannazRolynn
      @HannazRolynn 4 года назад

      send help

    • @IdunRedstone
      @IdunRedstone 4 года назад +1

      @@HannazRolynn You'd just set the columns as 1 and the rows as how ever many sprites you have going down. Because a column is a 1 wide sheet of that many rows.

  • @dangerman5221
    @dangerman5221 4 года назад

    Very helpful tut. Just wanna ask if there is any way to place on screen rotated frame without creating a new class' object with rotated whole image?

  • @Satwafr
    @Satwafr 6 лет назад +1

    Hello, love this tutorial! However, how do we do collision using this class?

  • @brivet5049
    @brivet5049 5 лет назад

    Wow thanks !

  • @fxstreamer238
    @fxstreamer238 5 лет назад

    surface.blit? where did you define "surface" ?

  • @SuperStarwarsfan7
    @SuperStarwarsfan7 5 лет назад

    Great video and great explanations! I get an error that says HW is not defined when i use this. Anyone know how to fix it?

    • @GrodVidar
      @GrodVidar 5 лет назад +1

      The HW is what he calls the variable for half the width of the window(or screen), on the video he defines this at row 14 as "HW, HH = W/2, H/2" hope that helps! :)

  • @andrewschroeder5485
    @andrewschroeder5485 7 лет назад +3

    If I wanted to run my game at say 120fps but I didn't want to cycle through my walking sprites that fast how would I put in a delay between sprites without delaying the whole program? So that maybe I cycle through my sprites at 8 fps? Thanks!

    • @codePylet
      @codePylet  7 лет назад +3

      +Andrew Schroeder use a counter to increment the frame. Divide 120fps by 8fps which equals 15, that what your counter should reach to increment the animation frame. Like this:
      FPS = 120
      animFPS = 8
      countRange = int(FPS / animFPS)
      count = 0
      frameIndex = 0
      While True:
      counter += 1
      If counter == countRange:
      frameIndex += 1
      counter = 0
      spritesheet.draw(displaySurface, x, y, frameIndex)
      Hope that helps. If not lemme know :)

    • @apfelflo4239
      @apfelflo4239 6 лет назад

      I want to do the same thing, but I'm not sure, where to implement these lines of code. Are some of these inside the class of the spritesheet or outside? I'll try some combinations, but i would be glad, if you could clear up, where these line get implementedxD

    • @codePylet
      @codePylet  6 лет назад

      Try creating a new class...
      pastebin.com/6jtaSc00
      Hope that helps :)

    • @apfelflo4239
      @apfelflo4239 6 лет назад +1

      Thank you so much for the quick answer! Works perfectly~ (I just started with Python 2 weeks ago, so i'm still getting used to things. Your tutorials are extremly helpful tho! Thanks for doing this!)

  • @galsk2533
    @galsk2533 6 лет назад

    How would I be able to make them bigger? I am using a 16 bit spritesheet and am wondering how to scale them bigger without stretching them in my drawing program.

    • @codePylet
      @codePylet  6 лет назад

      +TheAmazingGuy pygame allows you to scale a surface using transforms' methods. Have a look at this video ruclips.net/video/g7KoOUu4v7Q/видео.html to see how it's done and then try implement it into your code, if you're still struggling after that drop me another message :)

  • @extroordinary
    @extroordinary 7 лет назад +1

    for the line: screen.blit(self.sheet, (x + self.handle[handle][0], y + self.handle[handle][1]), self.cells[cellIndex])
    I dont quite undesrstand the 0 and 1 part. Could you please elaborate on that. Your help is much appreciated

    • @codePylet
      @codePylet  7 лет назад +1

      I apologise I should have made the variable names a bit clearer.
      The variable self.handle contains nine x & y offset values.
      self.handle[ *handle* ][ 0 ]
      In the code above *handle* contains a number from 0 - 8 and is used to index self.handle which is a list of 9 pairs of values, x & y. Each of the 9 pairs in _self.handle_ contains the x offset and the y offset and these are indexed by a number for 0 - 1, 0 contains the x offset and 1 contains the y offset. This is why we add self.handle[handle] *[0]* to the x coordinate and self.handle[handle] *[1]* to the y.
      I hope that helps, if not let me know. Happy coding!

    • @extroordinary
      @extroordinary 7 лет назад +1

      So it is basically a list inside a list. I should have realized this haha.
      Anyway, thanks for clarifying that for me and keep up the good work!!

    • @codePylet
      @codePylet  7 лет назад

      Yeah, a list inside a list lol

  • @tcchan14
    @tcchan14 6 лет назад

    What is the meaning of handle function?

    • @codePylet
      @codePylet  6 лет назад

      +tc chan the handle function allows you to place a sprite at a predefined offset to the X and Y coordinate.

  • @hairywalrusminecraftgamepl1189
    @hairywalrusminecraftgamepl1189 7 лет назад

    When I run this, the sprite looks like it is just scrolling down. I copied the script exactly from your google drive and cannot tell what is wrong. Thanks for you response!

    • @codePylet
      @codePylet  7 лет назад

      +HairyWalrus | Minecraft Gameplay hi, are you using the same spritesheet or your own?

    • @hairywalrusminecraftgamepl1189
      @hairywalrusminecraftgamepl1189 7 лет назад

      I am using your sprite sheet. I am using Python 3 though which might be the problem.

    • @codePylet
      @codePylet  7 лет назад

      +HairyWalrus | Minecraft Gameplay have a look at this:
      docs.python.org/2/library/2to3.html
      Convert my code with it and let me know if it solves the problem. If it doesn't I'll have a look at it tomorrow and convert it to python 3 myself :)

    • @hairywalrusminecraftgamepl1189
      @hairywalrusminecraftgamepl1189 7 лет назад

      I tried converting it and I am still having the problem. I tried it on two computer so I think the issue is that I am using the wrong version of Python. Thanks for all the great help btw.

    • @codePylet
      @codePylet  7 лет назад

      No problem.
      Pygame 1.9.2+ should support python3.x.x
      Let's a have look at which versions you're using.
      Press the windows key + r together and type python and enter.
      Then type the following:
      import pygame
      import sys
      print pygame.version.ver, sys.version_info
      Copy the result into the comments so I can see what versions you have.
      We'll sort this out :)

  • @Nathan_fc
    @Nathan_fc 6 лет назад

    your code doesnt work on python 3.2 but good video for the explainations

    • @codePylet
      @codePylet  6 лет назад +2

      +Nathan hi, In the drive folder for this video there's a version for Python 3. Hope that helps :)

    • @Nathan_fc
      @Nathan_fc 6 лет назад +1

      thanks you i didnt see

  • @iskariotas
    @iskariotas 7 лет назад

    Why did you create and use local variables h, w instead of the others self.h, self.w that you had also created?

    • @codePylet
      @codePylet  7 лет назад

      Hi Nikolajus, just for readability really. I find writing w or h a lot tidier than self.cellWidth or self.cellHeight. If they're the only width and height values in the function then there's no confusion about what they represent either :)

    • @iskariotas
      @iskariotas 7 лет назад

      Oh okay! That bugged me a little bit ;)
      Awesome tutorials, subscribed and most likely going to watch everything as I am getting ready for my first Ludum Dare jam. I love your explanations, @code.Pylet !

    • @codePylet
      @codePylet  7 лет назад

      Wow, Ludum Dare, I love the stuff that comes out of there. What's the theme this year?

    • @iskariotas
      @iskariotas 7 лет назад

      The theme isn't decided yet, the poll isn't available as well. The polls to decide the theme will be open two weeks before the jam begins and the theme will be announced when it actually starts (July 28th). You can check more info on www.ldjam.com (maybe you will participate? ;) )

    • @codePylet
      @codePylet  7 лет назад

      Sadly not, my life is a bit chaotic at the minute. Let me know what your LD username is and I'll look out for your entry :)

  • @gfaus6118
    @gfaus6118 7 лет назад

    One thing. In the tutorial, on the draw function, Pygame gives me a TypeError of "Invalid rectstyle argument". I am using Pygame 1.9 and IDLE 3.6.2. Why does it give me that?

    • @codePylet
      @codePylet  7 лет назад

      +S.G. Harmonia if you're trying to draw a rectangle then the arguments should be surface, color, rect, thickness
      Rect is a tuple object structured like this:
      rect_param = (x, y, width, height)
      so here's an example:
      pygame.draw.rect(dispaySurface, (255, 255, 255), (10, 10, 50, 50), 0)
      That'll draw a 50px white square at location 10, 10 on the display
      Hope that helps

    • @gfaus6118
      @gfaus6118 7 лет назад

      Also, when I load a frame from my sheet, it prints two halves of two different frames. It also leaves some frames behind. The sheet is a 1 * 4 sheet. Why does it do this?

    • @codePylet
      @codePylet  7 лет назад

      +S.G. Harmonia are your 'sprites evenly spaced into identically sized cells?

    • @gfaus6118
      @gfaus6118 7 лет назад

      Yes, each cell is a 16x16 cell.

    • @codePylet
      @codePylet  7 лет назад

      If you upload your image (and code if you want) to this Google Drive folder I'll have a look for you :)

  • @tioseika
    @tioseika 6 лет назад

    Hello!
    Should you help me to understand handle and offset? I saw the video n times and don't understand.
    I can read better than listen. So if you can help me, I will so glad.
    About my text, I hope you can understand.
    Thanks!

    • @codePylet
      @codePylet  6 лет назад +1

      When you blit an image to the pygame display it is drawn so that the top left corner of the image where the x, y coordinate is

    • @codePylet
      @codePylet  6 лет назад +1

      The handle/offset allows you to drawn the image so that the x, y is in a different place, for instance the top right corner of the image or the center.

    • @tioseika
      @tioseika 6 лет назад

      OK! Now I understand. Thanks a lot!

  • @s.r.howell1297
    @s.r.howell1297 7 лет назад

    I wonder if you can solve a problem for me relating to spritesheets. I've been able to colour the unwanted background of a sprite in alpha when loading it from its own file, but having loaded an image from a spritesheet, suddenly the unwanted colour reappears. Any ideas?

    • @codePylet
      @codePylet  7 лет назад

      +S.R. Howell can you dump your pics and code into this Google Drive folder so I can have a look please? goo.gl/1qrD1L

    • @s.r.howell1297
      @s.r.howell1297 7 лет назад

      I've dumped the code in there that I think is relevant. There was an awful lot so I hope what I gave you is enough. I'm going to try an Ordered sprite group, but even if that works I would still be unable to explain why alpha colours are blocking out the background.

    • @codePylet
      @codePylet  7 лет назад

      +S.R. Howell
      Inside the spritesheet.get_image(...) function you have the line:
      image = pygame.Surface((width, height))
      Change it to this and let me know what happens:
      image = pygame.Surface((width, height), SRCALPHA)
      Hope it solves your issue :)

    • @s.r.howell1297
      @s.r.howell1297 7 лет назад

      Yes, problem solved! Thank you very much.
      What happened, though? I looked up source alpha and all I found (in a brief 2 mins search) was the hint that blit can be prone to breaking and so, extra parameters like source alpha provide it with expected approximations of return values.

    • @codePylet
      @codePylet  7 лет назад

      +S.R. Howell I think by default (don't quote me) all new pygame surfaces don't have an alpha channel unless you specify on creation with the SCRALPHA flag.
      Hope your game goes well, upload the finished product (Google Drive link I gave you) when you're done I'd love to see it :)

  • @SnowyGlory
    @SnowyGlory 6 лет назад

    Hi, first, AMAZING VIDEO! Second XD, I am experiencing an error when attempting to run the script (I am using Python 3.x and I think almost everything is adjusted for 3):
    local variable 'index' referenced before assignment
    and it is having the issue with:
    Rosa.draw(gameDisplay,index % Rosa.totalCellCount,HW,HH,CENTER_HANDLE)
    I can send the rest of the script if needed, I have this:
    Rosa = spritesheet("ROSA PARKS-SPRITE SHEET.png",1,3)
    CENTER_HANDLE = 3
    index = 0
    written below the class spritesheet but, outside of the class/functions. Any and all help will be very much appreciated!

    • @codePylet
      @codePylet  6 лет назад

      Hi mate, you need to set the value of index before you call Rosa.draw(...) Otherwise python doesn't know the value of index. Hope that helps

    • @SnowyGlory
      @SnowyGlory 6 лет назад

      Thank you very much for the speedy response! Do I set the value of index inside of the main loop? When I set the index value within the loop my program runs but stops responding and anytime I write it outside of the main loop (Like where colors and the display are established or below the spriteclass (in the same indentation as colors and display)) I still receive the error, "local variable 'index' referenced before assignment".

    • @codePylet
      @codePylet  6 лет назад

      The initial value of index should be set outside of the main loop otherwise the value keeps getting set over and over.
      That being said I'll need to see your code in full to understand why you're getting the error message when index is declared outside of the main loop. Can you copy to pastebin and send me the link please?

    • @SnowyGlory
      @SnowyGlory 6 лет назад

      This is my first time using Pastebin, hopefully I did this correctly XD
      pastebin.com/iqECfLsq
      There are also some other things in the 'file' since I had started working on this project beforehand. Thankyou for taking the time to look at my code and help me.

    • @codePylet
      @codePylet  6 лет назад +1

      Ah ok, it's because your main loop is contained within a function. Try defining index after def game_loop() or add index to the global list like this global pause, index

  • @blodstormZ
    @blodstormZ 6 лет назад

    Hey man, can you also do a vid about pygame's built in sprite functions? www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite

    • @codePylet
      @codePylet  6 лет назад

      +Robbe Benjamin I've never used them to be honest Robbe. I prefer to handle sprites myself