Pygame Tutorial #1 - Basic Movement and Key Presses
Вставка
- Опубліковано 6 лис 2017
- This is a new series on my channel where I am going to be going through the pygame module in python. Pygame is used to make games and is also useful for making software and other types of programs. In this first tutorial I show how to set up the screen and implement basic character movement.
⭐ Kite is a free AI-powered coding assistant for Python that will help you code smarter and faster. Integrates with Atom, PyCharm, VS Code, Sublime, Vim, and Spyder. I've been using Kite for 6 months and I love it! kite.com/download/?...
Want to learn the fundamentals of programming? Check out my course:
tech-with-tim.teachable.com/p...
Please LIKE and SUBSCRIBE for more content!
Check out My Website: techwithtim.net
SOURCE CODE: techwithtim.net/tutorials/gam...
How To Install Pygame: • Video
Python Programming Tutorials: • Python Programming Tut...
◾◾◾◾◾
💻 Enroll in The Fundamentals of Programming w/ Python
tech-with-tim.teachable.com/p...
📸 Instagram: / tech_with_tim
🌎 Website techwithtim.net
📱 Twitter: / techwithtimm
⭐ Discord: / discord
📝 LinkedIn: / tim-rusci. .
📂 GitHub: github.com/techwithtim
🔊 Podcast: anchor.fm/tech-with-tim
💵 One-Time Donations: www.paypal.com/donate/?token=...
💰 Patreon: / techwithtim
◾◾◾◾◾◾
⚡ Please leave a LIKE and SUBSCRIBE for more content! ⚡
Interested in what its like to be a computer science student? Check out my Podcast: anchor.fm/tech-with-tim
Follow me on Twitter: twitter.com/TechWithTimm
Join my Discord to Ask Questions and get help with pygame! discord.gg/pr2k55t
SOURCE CODE: techwithtim.net/tutorials/game-development-with-python/pygame-tutorial/
why do i get "invalid syntax"
If I had to guess you probably have...
Invalid syntax
You typed something wrong, spelt something wrong, forgot a bracket, messed up indent...
i am
my keys aren't moving
I'm getting an error "source code string cannot contain null bytes"...I had this working the first time, but then when I tried it on my own the 2nd time,I got this error message...please help mee...
while True:
print('thanks')
Error Expected an intendent block
@@technicaleinstein3372 lmao
@@technicaleinstein3372 Earth Sky Missile L
@@technicaleinstein3372 lmaooooooo
error : line 1
indentation error
Very nice of you to include a challenge with a solution hint at the end, very educational, feels like I'm in school again.
Anyone wants to learn Python through basic came can see this link:
ua-cam.com/video/ijOGhZFeVGA/v-deo.html
And let me know, whether you liked it or not
This is the first time where with my beginner level python knowledge helped me understand something like this. Great Video!
*creepy smile*
Same
Same
Seriously the best tutorial I've ever seen. Good job!
Thanks a lot, just what I was looking for: short, clear and practical. Let's go to the next one! 😀
Never seen a better tutorial. This is great, thank you so much!
I swear Tim, you are the king of python, no channel taught me until you did. RESPECT.
Dude, this is awesome, I am so proud of myself making a drawing rectangle
This is the epitome of teaching.
I've searched high and low for exactly this, thank you so much.
Thanks a lot for these tutorials! I'm learning Pygame for a term project and they help a lot:)
finally after serching so much found the tutuorial i needed
finally, thank you so much, my pygame wouldn't work and you fixed it!!!!!
Anyone wants to learn Python through basic came can see this link:
ua-cam.com/video/ijOGhZFeVGA/v-deo.html
And let me know, whether you liked it or not
I'm 28 and I started my codeing career with this video. thanks tim
This tutorial was totally the best for beginners in my perspective and also I changed the colour of the rectangle to yellow (255, 230, 50).Thanks man
OMG Tim I made it! Thanks alot I had so much fun with your tutorial, pls make more for me !!! Your tutorial is easy to understand and clear .
Very well spoken and clearly explained concepts. Great work!!
Thanks!
@@TechWithTim
you are the best
Best pygame/python tutorial I've ever learned. Thank you!
Instantly subbed!
You are a life saver man, keep making these awesome videos, you deserve like a million subs.
Yay! Now I have a moving purple rectangle! (I changed the RGB to (200, 23, 255) to make a light purple color)
Me too! I also add some horizontal acceleration and friction to make it more fun. Now let's program GTA V 😂
wolf hahahahahahah
@@frenzy9741 im tryna make a flight simulator
@Jayant Jagtap r/woooosh
love that color :)
As someone who's been trying to learn pygame in python for a while now , this was very simplified and easy to follow . Thanks so much . :) Looking forward to learning with the others .
Extremely awesome and easy too understand video !
This is SUPER helpful for a resume project I am working on. Thank you very much!
I’m making a small game for my school project, this was really helpful!
Thats cool!
Awesome tutorial and very good teacher. Thank you!
You deserve more than one like my friend unfortinatly its not possible....great job Thank you
That's how tutorials should be, didn't know nothing at first but u made it eaaasyyyyy.❤️
man, thank you for making this, its easy to understand, and it helps me a lot, you earned a like and a sub bro
Anyone wants to learn Python through basic came can see this link:
ua-cam.com/video/ijOGhZFeVGA/v-deo.html
And let me know, whether you liked it or not
dude u are awesome, pls continue doin this
THANK YOU SO MUCH THIS IS THE FIRST CODING VIDEO I'VE WATCHED WITH 0 ERRORS IN MY CODE THANK YOU MAY GOD BLESS YOU
Thank God for Tech with Tim....boy have I came a long way!
bro you are awesome
Congratulations bro.
When I was watching your series it had only 100 views you grew so fast in 2 months
Thanks man
Anyone wants to learn Python through basic came can see this link:
ua-cam.com/video/ijOGhZFeVGA/v-deo.html
And let me know, whether you liked it or not
@@asishraz6173 stop advertising!
Thank you! Your work is very beneficial as a starting point, or a refresher!
You helped me so much with my CS project work, thanks! Keep going!!!
Man... Crazy how this video helps. It's simple yet everything I was looking for the past few hours.
Really helpful!! Thanks :)
The one tutorial I can finally make sense of! Thanks so much :D
This is a really good introduction to pygame. Thank you so much.
For a beginner it's super 👌
Your such a gooooooooood teacher
Amazing, well explained. Thank you so much!
Thanks so much for this. With just this one video I was able to make a complete game of pong by using this basic info.
I really thank you bro. Loves from Turkey
Türk varmış burada:D
greatly explained video!!
Thanks!
u have come such a long way from this video! well done!
Thanks!
helped a lot, keep it up :)
How do you have 10k subscribers, that is so little for such a good teacher. Thank you, I learned something in pygame for once
I read the comment, look how much subscribers he has now (11 months later):181 000 ...
@@valteu look now
WHY DID I NEVER KNOW TILL NOW THE MAGIC OF LIBRARIES!!! I AM SO PISSED AT MYSELF FOR NEVER USING PYGAME BEFORE NOW. THANK YOOOOOOOOOOOOUUUUUUUUUUUUUU!!!!!!!!!!!!!!!!!!!!!
Anyone wants to learn Python through basic came can see this link:
ua-cam.com/video/ijOGhZFeVGA/v-deo.html
And let me know, whether you liked it or not
Thanx Tim, Good tutorial for beginner
The way you teach is so good. You R like a professional Coding Teacher. Its so fun to watch event though i know these stuff. Thanks❤
i did this to make sure that the square wasn't able to move out of the screen. if makes sure that fx the specific function K_LEFT doesn't work if you're too far to the left. (in this case, x = 0)
if x > 0:
if keys[pygame.K_LEFT]:
x -= velocity
if x < 460:
if keys[pygame.K_RIGHT]:
x += velocity
if y > 0:
if keys[pygame.K_UP]:
y -= velocity
if y < 440:
if keys[pygame.K_DOWN]:
y += velocity
Great tutorials, SUBSCRIBED! Helped me a lot with coding.
Just wish you can explain a little bit more about the methods you used from pygame ( things like their required parameters or default parameters, and what do they return? what type is it?)
I know I can basically use help() to see the details but if I can get more brief explanations from your tutorial, I could save a lot of time and work.
Anyway thanks a lot for sharing.
Thank you and I do appreciate the feedback!
Your explaination is very simple and easy to understand, thank you
I can't find a great enough way that fits you to thank you💯🙌
Hey, good video. Will you continue it?
For anyone who has the rectangle showing for a brief moment when quitting the window It's because the below code:
"pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
"
"pygame.display.update()"
is not in line with the "for event in pygame.event.get():"
So for example: (this is how it should be)
|for event in pygame.event.get():
| if event.type == pygame.QUIT:
| run = False
|
|pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
|pygame.display.update()
and (this is how it shouldn't be):
|for event in pygame.event.get():
| if event.type == pygame.QUIT:
| run = False
|
| pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
| pygame.display.update()
the positioning of your codes matters.
how do you make the code in line? mine literally wont let me
DANG!!!!..thanks mate.
Best tutorial ever. Thx for making this tutorial
Marvelous Explanation!!!!
Good Work.........
Bounds checking:
if keys[pygame.K_LEFT] and x > 0:
x -= vel
if keys[pygame.K_RIGHT] and x < 460:
x += vel
if keys[pygame.K_UP] and y > 0:
y -= vel
if keys[pygame.K_DOWN] and y < 440:
y += vel
If you add
from pygame.locals import *
You no longer need the pygame in front of K_UP, K_DOWN, etc. It's a pygame standard, so it's highly recommended.
I am so used to c++ and i am triggered whit and not being && and the condition in if not in (), and the : not being {}. I want to die. But it looks fins. Also rip the semi-colin.
@@yesveryprofesionalnameyes6055 LOL!!! I came from Python 3.7 and when I saw C++ it was confusing. It wasn't as flexible as Python is.
Extra tip because I was Facing this problem:-
If "import pygame, sys" isn"t responding or appearing colourless if you are using PyCharm, write "# noinspection PyUnresolvedReferences" a line before it without using any bnrackets or tuples.....
Thank you ! I liked the tutorial very much.
OMG YOU'RE SO GOOD MY PYGAMES KEPT HAVING ERRORS BUT THANKS TO YOU IT WORKS THX :DD
2:05 Tim: pretty boring window
Me: oh my gosh he opened a window🤯🤯
exactly with me in pygame...
Huge window
o h m y g o d h e o p e n e d a w i n d o w
Something I noticed while tinkering with the game's code is that your speed is tied to the framerate.
edit: If you want to make the game 60fps, change the delay at line 16 to "16" instead of "100".
edit 2: You will notice that you are noticeably faster than before. To remedy this, change the value of "vel" at line 12 to 0.8.
YOOoo that feels so nice
@@andzhurt4827 lol i forgot i made this comment, at least it hekped
Great Tutorial Series... Love the way you explain 👏👏👏
I like this tutorial. It is helping me to really understand 2D game development in python.
When I hold down the keys, my rectangle stops moving. I have to press one key at a time in order for the rectangle to move a certain distance. How do I fix it so I can move it while holding down the keys?
@Jacob MANSFIELD Thank you this helped a lot because I had the same problem, thanks for the solution.
@Jacob MANSFIELD thanks dude
When I run the program, the window quickly closes. I'm running the code via the command prompt on windows and editing it via Sublime text 3
Try using IDLE that comes with python
I have the same issue did u find the solution? please reply!
are you dutch?
me too
I'm having the same problem, but I'm in pycharm
Nice vid,
helped me a lot!
This series is amazing, I have learned lots of basic python stuff from it with almost "hello world" starting knowledge. I'm going on Tutorial #8 and helping guys in our class to learn basic python using this as material.
For example I never could understand the Object-Oriented Programming in courses I went to in university, but using that in a this game project taught me how to use it and what it's good for.
Hey everyone trying to learn code in quarantine
Hiyo!
u got me
when i am running the code in sublime text editor , it opens pygame window and then closes immediately.
Do you know why this is happening?
@Finnbyte yeah I am opening in CMD and there is no error
But that's ok with that main loop it works fine
This tutorial is using 1.6.2 there are others up to date not that this one is bad it's just its 2 years old... but keep watching it's cool to see how far coding has come since 2 years ago
I like how you didn't even activate windows, other than that great video!
Its useless tbh
Damn ! I love this guy ..really men he is the best teacher you will found there..
awesome explanation, very helpful.
Hey friends, find some sample code for what he's doing, this is my second day coding so its not very good, but this is smooth movement of a polygon on a screen using the arrow keys.
import sys
import pygame
import random
pygame.init()
WIDTH = 1000
HEIGHT = 600
FPS = 60
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
YELLOW = (255,255,0)
BLACK = (0,0,0)
BACKGROUND_COLOR = BLUE
polyx1 = 500
polyy1 = 500
polyx2 = 520
polyy2 = 545
polyx3 = 480
polyy3 = 545
polygon = [(polyx1,polyy1),(polyx2,polyy2),(polyx3,polyy3)]
screen = pygame.display.set_mode((WIDTH,HEIGHT))
game_over = False
clock = pygame.time.Clock()
pygame.key.set_repeat(1,1)
pygame.display.set_caption("Smooth Movement")
while not game_over:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
polyx1 -= 5
polyx2 -= 5
polyx3 -= 5
elif event.key == pygame.K_RIGHT:
polyx1 += 5
polyx2 += 5
polyx3 += 5
elif event.key == pygame.K_UP:
polyy1 -= 5
polyy2 -= 5
polyy3 -= 5
elif event.key == pygame.K_DOWN:
polyy1 += 5
polyy2 += 5
polyy3 += 5
polygon = [(polyx1,polyy1),(polyx2,polyy2),(polyx3,polyy3)]
screen.fill(BACKGROUND_COLOR)
clock.tick(FPS)
pygame.draw.polygon(screen, (YELLOW), polygon, 0)
pygame.display.update()
epic
If anyone is having problems moving the rectangle left and right, here you go. (I cancelled the delay I had some issues).
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 40
height = 60
vel = 5
run = True
while run:
pygame.time.delay(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= vel
elif keys[pygame.K_RIGHT]:
x += vel
elif keys[pygame.K_UP]:
y -= vel
elif keys[pygame.K_DOWN]:
y += vel
#pygame.time.delay(50)
win.fill((0,0,0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()
maybe change your elif to if??
The square in the scene is actually draggable! LOL.. great tutorial!
Really helpful video!! thanks!
hi tim u are the most one to programminger :) I'm turkish so my english is bad Im 14. and ı will be programminger in future. just u can know u are the besttttttttttt!!!!!!!
Thank you!
Python > English :-)
@@dequationblog :D
pygame has no init member error.
please help!
This is the best tutorial I've ever seen........... :)
Thanks, you dont even know that how much u helped me
Nice tutorial senpai!
I agree with you Peter~Kun!
my window only stays open for a second why??? it isnt until i add in the event checking that the window stays up, why does your window stay open at the begining of the video tim??
I think u should add delay
first, in the beginning of the code, write "import time"
then, write in the end of the code "time.sleep (the secs you want the window to wait).
the same happened with me then i checked and it was this if statement, i types () after QUIT thats why python couldn't execute it,
if event.type == pygame.QUIT:
@MegaMogul2 I typed "while True:" then I put his code in but now I cannot get the window that pops up to close, do you know how to fix this?
Never mind, I just had to watch some more of the video lol
OMGGG LOVE YOUR VIDEOS THNXX A LOT
helped a lot, thank you very much
plz keep posting video
pygame.draw.rect(win, (255, 0, 0), (x ,y , width, height)) did not work
Did you define all the variables(win=... , x=...., y=...,width=....,height=... (... Is code inside the variabsles)
@Fazil Ahmed it's defined in the beggining, - win = pygame.display.set_mode((500,500))
Thanks man it really helped me a lot !!!! keep it up
thanks very much for this video
Why does the Pygame window close immediately after running?
did you do the while loop? it shouldn't close if you did it.
I am facing the same problem...... someone answer plz
@@noobstudios4457 I think it's because there's some errors in your code. If there is no error in your code but still keeps closing, try opening your file using Run command by right clicking the windows icon, then selecting 'run'. On the Run command, type your file name, and then adding ' / K' after that. This should stop the window from closing automatically.
Is Pygame more like a bridge, a next step, or an alternative to Scratch?
I have made games with Scratch but I haven't learned python yet ,because I felt lost with the online educational tutorials because they started out too basic. They were too general with out being related to any field of study.
I wanted to get into robotics as a hobby, but just buying a robot with say a Raspberry Pi which uses raspbian to program it wouldn't teach me enough to expand my knowledge past basic robotics.
I couldn't even learn Open CV or anything else like understanding neural networks.
i actually think you can program Raspberry Pi with python
+AlfonsL
👍
i think python is the easyest programming language, learn it from the bases. Neural networks requires python and linear algebra knowledge.
Great tutorial. Thanks!
just, the best tutorial ever
pygame.error : video system not initialized
How to fix this? I already have pygame.init() in my first line of code
hi.
had the same eror.
i worte
if event.type == pygame.quit()
insted of
if event.type == pygame.QUIT
@@shakked95 hey i tried what u said but now it says "intax error" so now what? can u help me?
@@sander15. well i can try. can you copy and paste the error and the code that caused it?
shakked95 dont worry i just searched for many places and i just got the answer thank u!!
My window does not close when I try to quit but no error shows up help.
maybe you did not write it in upper case! (i answer for those who have your same problems! I had it too)
One way to fix it is if you import sys when you import pygame:
import pygame, sys
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
Thanks for the tutorial in IDLE
Thank you for your tutorial!