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...
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
this should be pinned for newcomers. Thanks for the video!!
it took me so long to figure out why the top 3 pixels were cut off, thx
You are very PRO, very thanks, you are the BEST
very good video with a nice explanation thank you
Thanks!
fyi if your using python 3 i /c will give you a float so you have to cast it to an int
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,
your material has been so helpful. thank you so much :)
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!
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.
You just deliver in a very understandable way. Keep doing .
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!!
Looking forward to working through the other projects and tutorials you have done. Thanks.
As usual a good guide and I look forward to the next.
I'm looking at collisions now, I haven't forgotten :)
Thanks, I will wait for it ;)
I finally learned how to work with spritesheets. Thanks a lot. Suscribed!
+Sergio Cano muchas gracias! Glad I could help. What project are you working on?
Just discovered your channel last night. Thanks for the tutorials, they're awesome and so helpful!
+DeerhunterCZ Thank you, kind of you to say :) What are you working on at the minute?
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.
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 :)
So thats what spritesheets are for... was getting frustrated cutting and pasting the images individually into my game
Me too!
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.
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!
Good
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! :)
You like metal detecting?
Didn't work for the sprite i had
Awsome tutorial. You have a new subscriber, and i hope to see more tutorial like this.
Human being reporting in, thanks for making this, very helpful
Awesome video, very helpful. Thanks a lot!
Great stuff, clear explanation and very informative. Thank you!
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)
great explanation
That i%c, i/c trick is very clever. is that a standard thing or did you come up with that?
Just another human being watchin your vids
Wp
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.
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.
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
Thank you !
what if the sprite sheet is in a straight column
send help
@@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.
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?
Hello, love this tutorial! However, how do we do collision using this class?
Wow thanks !
surface.blit? where did you define "surface" ?
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?
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! :)
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!
+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 :)
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
Try creating a new class...
pastebin.com/6jtaSc00
Hope that helps :)
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!)
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.
+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 :)
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
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!
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!!
Yeah, a list inside a list lol
What is the meaning of handle function?
+tc chan the handle function allows you to place a sprite at a predefined offset to the X and Y coordinate.
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!
+HairyWalrus | Minecraft Gameplay hi, are you using the same spritesheet or your own?
I am using your sprite sheet. I am using Python 3 though which might be the problem.
+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 :)
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.
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 :)
your code doesnt work on python 3.2 but good video for the explainations
+Nathan hi, In the drive folder for this video there's a version for Python 3. Hope that helps :)
thanks you i didnt see
Why did you create and use local variables h, w instead of the others self.h, self.w that you had also created?
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 :)
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 !
Wow, Ludum Dare, I love the stuff that comes out of there. What's the theme this year?
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? ;) )
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 :)
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?
+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
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?
+S.G. Harmonia are your 'sprites evenly spaced into identically sized cells?
Yes, each cell is a 16x16 cell.
If you upload your image (and code if you want) to this Google Drive folder I'll have a look for you :)
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!
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
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.
OK! Now I understand. Thanks a lot!
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?
+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
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.
+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 :)
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.
+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 :)
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!
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
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".
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?
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.
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
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
+Robbe Benjamin I've never used them to be honest Robbe. I prefer to handle sprites myself