Learning Pygame by making Pong
Вставка
- Опубліковано 29 вер 2024
- A fairly simple Pong game to help you learn the basics of Pygame. We will talk about the fundamentals of Pygame and then incrementally add more elements.
Files can be found at:
github.com/cle...
i am just 2 mins in and so many information that nobody would say that. thanks a lot this really helped me. never know why small channels are always most helpful
honestly, its these small coding channels that provide the most useful information, especially to self learning coders like me. Props to u!
i am with yo
@@NavjotSingh-zx3we reply to a reply
GELOMILF
U are not alone, we all are here👍👍
It's not small anymore🎉
your explanation is so clear this is amazing !
This video is amazing, you really know how to explain the code!
Do you know what software he was using?
Best explained tutorial ever. U R really a gifted teacher. Wish I had found something similar when I started. Please keep up the good work. Best wishes from D. R.
Thank you so much 🙂
Could you please make a tutorial on string manipulation ; let's say, moving text on the screen using Python or better pygame?
Thanks in advance.
I've been trying to make a game without an engine (yet my brain stops working when I open VSCode) and this was a lifesaver and helped me start out with a small project
My first Python project, thank you very much, Good Sir!
You're welcome and glad you liked it :) I made lots more pygame tutorials and I will make a video on a much better pong game in about a week!
BEST EVER EXPLANATION FOR PROGRAMMING. PLZ MAKE VIDEOS ON PYTHON MACHINE LEARNING, DEEPLEARNING AND COMPUTER VISION WITH PYTHON🙏🏽🙏🏽
Your teaching outline is good to begin with
Really helpful and very well explained, i did this and some of your other tutorial-projects and it's a great way to learn, please keep going with the great job
To solve the problem with keydown:
Use
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
This way the player will move as long as the key (w in this case) is held down. Do this after checking for events (and don't check the movement keys in the events section.)
With this method, my player's speed seems inconsistent and/or slower than it should be as if for some frames it's missing that the button is held down.
Subscribed, awesome, perfect,wonderful and really understandable, Thank you Clear Code for this amazing Content.
No words to appreciate Clear Code. Is this a teamwork or all are done by yourself?
hey, yes I am making it by myself (looks much harder than it actually is tbh)
very useful, thank you so much!!!!
thanks! this was my first project so i had a lot of bugs but it was really fun! i will do part 2 soon!
Thanks for this tutorial. Having absolutely no code experience, I was able to follow along and get a game working with some small changes so I have two players. I used ai to add a score game ender and mouse control - like I said, no code experience. I am hoping to use this for a setup using two bicycles mounted on a frame that control the paddle movement. I have a working prototype now. The only thing I'd like to add is changing the ball graphic to a small pixel graphic of the grinch's face. Is this a possibility? Could you point me in the right direction to look if it is? Thanks for this again.
this was a really good tutorial!
Your the best, i watched someone else and he made my pygame so it looked blocky and 30 fps. But with your vid its smooooooooth
great tutorial, loved it
The ball_animations function does not allow the player and opponent variables to operate correctly. As far as the computer is concerned, those variables only exist outside of this function. How do you go about solving this issue?
If you u want a big nice screen in a laptop use - 1000 width and use 700 height
very well made and helpful :) cheers mate
thanks for the video, but I have an error in PowerShell at the beginning
For me arrow keys is not moving it. I am using a laptop do I have to change something?
Hey, Thanks for the video. I have a question about the code though. Why does ball_speed_x and ball_speed_y need to be global but player_speed doesnt need to be global?
When using the player_speed variable it is only used by the player_animation function, the function does not change the value (so if you wanted to change the speed of the player from the function you would need to declare it a global variable. Both the ball_speed variables change the variable from within the function; i.e. you are trying to change a global variable from a local scope. Hope that makes sense :)
@@ClearCode Yeah that makes sense. Thanks very much
Yo i set the ball speed to 1, but it's still too fast when i run it, but when i set it to 0.5 or .5, it doesn't move, any solution?
Edit: and also when i grouped the ball animation, it doesnt even open the game
I'm learning pygame by making River Raid 😊
the code is word for word yet my paddle just drops to the ground and i dont understand why, any help?
When i run the code I don’t get any window pops up
My restart command is not working any suggestions
brb gonna win ludum dare 50
the tutorial is great and i followed it, but when i finished the colors for everything and i ran it,it just shown a black screen,i am on linux so if anyone could help me i would be very thankfull
Great tutorial! but isn't more convenient to get input using function pygame.key.get_pressed()?
what IDE are you using and what theme is that?
actually its
sublime text 3
0:18 Installing Pygame
0:51 How Pygame works
5:37 Drawing
13:26 Animations
20:24 Input
24:27 Opponent 'AI'
25:47 Basic Scoring
Thanks
That was really helpful. I knew how to make basics but i mainly needed to learn animation and opponent AI. Thank you very much!
Amazing clarity, someone who clearly not only knows how to execute the code, but has a thorough understanding in it.
"If you can't explain it simply, you don't understand it well enough." - Mr Einstein
Thank you!
Mr Einstein's words in German "Wenn du es nicht simpel erklären kannst, hast du es nicht gut genug verstanden."
@@thepaulcraft957 Thats because Einstien's German, Yeah..!!
@@kaneki_ken_07 Einstein's dying wish was to be referred to as "A rock", other than "The rock" as we all know as Dwayne "The Rock" Johnson, "A rock" in German is "Ein Stein". A singular rock can make a difference, we should respect that.
@@yuka8286 Well, there was some other conversation going on and I see some comments are deleted. So, I think you didn't understand the topic because of deleted comments.
You’ve done better explaining PyGame than the 90% of PyGame tutorials I’ve watched.
yes,tech with tim and other coding channels were tooooo hard and explained complicated,i almost felt like quitting game devolopment but luckily in time i found clear code
Yeah man really
To be honest, I've read the book 'Beginning Game Development with Python and Pygame (2007)', but this man accurately and more clearly explained all of that in just 4 videos that too in a concise manner. Thanks a lot. You are awesome.man()
the function at the end really completed it lol
One of the best programming videos I've seen, super clear and concise explanations
Your Chanel deserves to grow!....
You content is so awesome to understand, it has good clarity, you make the learning seems easy..
Greatly looking forward for new uploads
I am having python 3.7.0 version on my mac. So will it work after installing pi game using terminal to make the pong game?
Please reply fast
Yes please tell
you truly live up to your channel name. clear coding indeed!
honestly, if I could give you more than one like I would.
please keep it up and if you could cover some AI topics and applications that would be amazing
Thanks for the tutorial. I just don't get one simple part. Why don't we need to declare player_speed as a global inside the player_animation finction but we need to declare ball_speed_x and ball_speed_y variables as globals inside the ball_animation function?
Very use full sir!
And please tell me how to create this game for mobile phones!
I'm having a problem, every time I run it it's just black I can't see anything.. here is my code can anyone see what I did wrong btw I didn't finish the code im around 13 minutes in the video, but when he ran the code it showed the ball thanks.
i probably made a spelling error but idk
import pygame, sys
pygame.init()
clock = pygame.time.Clock()
pygame.display.set_mode()
#Screen and window
screen_width = 1000
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("pong game test")
# Game Drawing / Rectangles
ball = pygame.Rect(screen_width/2 - 15, screen_height/2 - 15,30,30)
player = pygame.Rect(screen_width - 20,screen_height/2 - 70,10,140)
opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140)
bg_color = pygame.Color("grey12")
light_grey = (200,200,200)
while True:
# handling input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Update Windows "Tics"
pygame.display.flip()
clock.tick(60)
# Visuals
screen.fill(bg_color)
pygame.draw.rect(screen,light_grey, player)
pygame.draw.rect(screen,light_grey, opponent)
pygame.draw.ellipse(screen,light_grey, ball)
pygame.draw.aaline(screen, light_grey, (screen_width/2,0), (screen_width/2,screen_height))
You need to put Visuals into While
I hope you make more videos, was struggling with pygame trying stuff on my own just reading the documentation but was sooo off with rect collisions, this explained it perfectly!
Thank you, glad it helped :) check out my channel, I already made lots more pygame tutorials
I don't know what python was like 3 years ago, but now I was able to make player moving by this lines:
keys = pygame.key.get_pressed()
''''if key[pygame.K_UP:
''''''''self.player.x += 7
and this works even when you hold the button :)
why did you global the 'ball_speed_x' and 'ball_speed_y' variable, yet you not global the 'ball' variable on the define statement?
Thanks so much man, I'm a 3rd-year student in college learning computer science. I am very interested in game development/coding and this helped a lot. Hope you make more :)
I'm in 2nd year I'm into web development (front. End)
N PyGame too
Hope will go any of these twos route
Before I mess up in ma mind
Rather your channel name(Clear Code) specifies your coding skills 😊
Hey! I really gained a lots of information. CAN YOU PL GUIDE ME HOW TO ADD SOUND EFFECTS AND TIMER???
Glad you like it! and check out my channel, I made a couple of sequels for this game and timers and sound effects are covered there.
Can someone type the full codes in my comment?PLS!!!
You can get the full code in the description, just click on the github link and open the python script there
Why does ball_speed_x and ball_speed_y need a global definition but not player_speed?
Nevermind, I saw your reply in another comment. Thank you!
Clear Code
2 years ago
When using the player_speed variable it is only used by the player_animation function, the function does not change the value (so if you wanted to change the speed of the player from the function you would need to declare it a global variable. Both the ball_speed variables change the variable from within the function; i.e. you are trying to change a global variable from a local scope. Hope that makes sense :)
Module 'pygame' has no 'init' member
Can you help me with this, please?
can i see full error
I'm at about 12:58, and when I run it to test, I see this prntscr.com/t9ia6v. I looked through all the code and I think I got it right, heres what i have:
import pygame, sys
# Setup
pygame.init()
clock= pygame.time.Clock()
# Main Window
screen_height=1080
screen_width= 1920
screen=pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Pong')
# Game rectangles
ball = pygame.Rect(screen_width/2 - 15,screen_height/2 -15,30,30)
player = pygame.Rect(screen_width - 20,screen_height/2 - 70,10,140)
opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140)
bg_color = pygame.Color('grey12')
light_grey = (200, 200, 200)
while True:
# Handling input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Visuals
screen.fill(bg_color)
pygame.draw.rect(screen,light_grey, player)
pygame.draw.rect(screen,light_grey, opponent)
pygame.draw.ellipse(screen, light_grey, ball)
pygame.draw.aaline(screen, light_grey, (screen_width/2,0), (screen_width/2,screen_height))
# Updating the window
pygame.display.flip()
clock.tick(60)
When I run it with a console, I get the error
pygame 1.9.6
Hello from the pygame community. www.pygame.org/contribute.html
C:\Users\Owner\Desktop\Programming\PythonPrograms\UI EXES and scripts\Pong\Pong.py:14: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
ball = pygame.Rect(screen_width/2 - 15,screen_height/2 -15,30,30)
C:\Users\Owner\Desktop\Programming\PythonPrograms\UI EXES and scripts\Pong\Pong.py:15: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
player = pygame.Rect(screen_width - 20,screen_height/2 - 70,10,140)
C:\Users\Owner\Desktop\Programming\PythonPrograms\UI EXES and scripts\Pong\Pong.py:16: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
opponent = pygame.Rect(10, screen_height/2 - 70, 10, 140)
I tried your code, it seems to work fine, the one mistake I could find in your code is that the stuff under updating the window, so the last three lines, need to be indented to be inside the while loop of the game.
@@ClearCode That seems to fix it! Thanks
I think it should of been made more clear how important indentations are in Python. (Maybe I missed that part)
Other than that great video.
For anybody having an error with the keys at 23:20 getting the error "K_DOWN not defined". All you have to do is at the top say "from pygame import *" and it should fix it.
should this work in repl.it? cause im trying to do it on there (my computer just doesnt want to recognize that pygame is downloaded so i have to use something online) and i am only getting like the top left quadrant of the screen.
So repl does support pygame but I am not sure how large of a window it supports. Maybe try different window sizes and see what fits. Are you getting an error message for pygame on your computer?
@@ClearCode i am getting an error message saying that no setup file exists (i have a screenshot of the whole error message) and also i have not thought about if replit only supports a certain size window, thanks!
can someone explain to me why we needed to increment player _speed at every loop when the key is pressed down instead of directly incrementing the y coordinates of player when the same happens?
He explain it at 21:25
@@heysiri_official yeah, i know he mentioned it...but i still couldn't get why exactly. A little expansion would help
This guy is so clear...he definitely deserves million of subscribers
Help! it says error: File "F:\PythonSachen\Scripts\PongPy\Pongpy.py", line 28, in opponent_ai
if opponent.top < ball.y:
UnboundLocalError: local variable 'opponent' referenced before assignment
i got an error saying that:
AttributeError: 'builtin_function_or_method' object has no attribute 'tick'
i used python 3.9.1 to code this
I've been watching your tutorials for a while and you are simply amazing!! Really, you can't imagine how helpful your channel has been for me.
Why didn't you have to declare global variables for the player movement like you had to for the ball movement?
18:46
Like cant we also add arguments, ballxspeed and ballyspeed for the function ball_animation() instead of global variables
That was a really great video thank you very much for making this great video.
did anybody have trouble where the code worked but was way too slow? my fps is definitely not 60 but idk why, running on a decent computer that can run things like minecraft relatively well.
edit: i even tried downloading his exact code from github incase i did something wrong but it runs the same
This was so crisp and clear. I've seen other tutorials where they just guide you through the code without explaining the underlying concepts but this was definitely what I needed. Thanks!
Why does ball_speed_x and ball_speed_y have to be included as global variables in ball_animation, but player_speed not have to be included in player_movement?
how I learned this is hilarious, I first followed along tutorial and then the nextday i tried to do it without tutorial and comeback for where I am stuck, the funny thing I am very understanding it for the second time
Excellent video! Nice and clear to follow.
Pygame now has a new discord community server: discord.gg/ZuB2RySPRJ
Thank you so much, you explain things so simply and intuitively compared to the other ressources I was trying to use
for some reason I have written the code properly but when i press the arrow keys it doesn't always register it and I thought it was a matter of multiplying with deltatime but it still doesn't work. Can someone help?
pygame doesnt work.
red code pops up in the command prompt and 2 lines of yellow code. I use windows 10 and downloaded python 3.9 Can someone please tell me what to do?
Awesome video! You walked through it all really well and it was easy to follow along to. One change i made to the code though, that made the AI smarter, is i changed the opponent_ai function to compare the opponent center y with the ball instead of opponent bottom and opponent top respectively. This made it so the opponent tried to align its middle with the ball instead of its bottom/top.
def opponent_ai():
if opponent.centery < ball.y:
opponent.centery += opponent_speed
if opponent.centery > ball.y:
opponent.centery -= opponent_speed
if opponent.top = screen_height:
opponent.bottom = screen_height
great explanation...hate other tutorials that just try to have you copy their code without explanation
where do i get this code as i wanted to work on this
can someone comment down the code, I am having some issues and I wanna make sure I have everything right
for the opponent, you could have just set the opponent.y to ball.y
actually im zero in programing. i like to become hero in programing, like you. thank you
Your presentation style is incredibly intuitive, tysm :D
nothing happend its just a black screen for me
may be you spelled something wrong. even if you spell wrong for the colour, you may get empty screen. that happened to me also. i wrote "greay12" instead of "grey12". be patient and continue coding. goodluck
@@niveds9090 i cheked all my code and nothinng was wrong
all the tutorials i done even ones that use diffrent coding languages i still have somthing wrong
@@PrinterPaper255 if you really want my help you can provide me the source code, through my Instagram Direct male. My IG: _ni_ve_d. Hope I can help you. It is really frustrating when there is an error in the code, be patient. Take your own time to understand the mistake. There is way to fix every mistake.
I got this 'first argument must be a dict' when I was trying to define the ball animation.
How did you get this black bacground in python
How do you not have like a million subs? just a question, HOW!?
I think it is a new channel
0:49 For me it says: No module named pygame, even after installing it again.
Very informative and instructive tutorial! Thank you
Just made this after watching your flappy bird video. These tutorials are incredible
But you can do the same thing 10 times easier with a game engine like Godot
Thanks very much for this video. It was really helpful :)
looks like I need to learn python before start with Pygame
can somebody put the full code in the comments plz
19:38... But... We did not create that variable in a function right? I don't understand... I thought that we just made it when the code ran... SOMEONE PLEASE EXPLAIN?
yeah, we did. Whenever you assign a value to a variable name (can be + or something like += ) you create a new variable.
Why do you not have 1+ million subs, people get this man too 1mil
Best tutorial video I've ever seen!
Hats off to this guy
can i do to opponent as 2player like he can control anotehr pad with like wasd
Thanks so much for this pog tutorial. Also if you want to make the AI a bit better in the opponent_ai function instead of opponent.top < ball.y:, you can use opponent.centery. This is more efficient as it checks if the ball is lower or higher than the center of the opponent Rect.
thanks it really made the program better but you also need to replace ' opponent.bottom ' with 'opponent.centerx'
@@IGOverkill yh, soz I forgot that. Good luck on your pygame journey
All the code so u can copy paste
import turtle
# Window
wn = turtle.Screen()
wn.title("Table Tennis")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0) # stops the window from updating
# Score
score_a = 0
score_b = 0
# Middle Line
# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.penup()
paddle_a.goto(-350, 0)
# Paddle B
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.penup()
paddle_b.goto(350, 0)
# Ball
ball = turtle.Turtle()
ball.speed(3)
ball.shape("circle")
ball.color("white")
ball.penup()
ball.goto(0, 0)
# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Player A: 0 Player B: 0", align="centre", font=("Courier", 24, "normal"))
# Movements:
# X Movement
ball.dx = 1 # 'd' means change
# Y Movement
ball.dy = -1 # Moves by 2 pixels
# Functions:
# Paddle A
def paddle_a_up():
y = paddle_a.ycor()
y += 20
paddle_a.sety(y)
def paddle_a_down():
y = paddle_a.ycor()
y -= 20
paddle_a.sety(y)
# Paddle B
def paddle_b_up():
x = paddle_b.ycor()
x += 20
paddle_b.sety(x)
def paddle_b_down():
y = paddle_b.ycor()
y -= 20
paddle_b.sety(y)
# Keyboard Binding
wn.listen()
#Paddle A
wn.onkeypress(paddle_a_up, "w")
wn.onkeypress(paddle_a_down, "s")
# Paddle B
wn.onkeypress(paddle_b_up, "Up")
wn.onkeypress(paddle_b_down, "Down")
# Main Game Loop
while True:
wn.update()
# Move the ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border
# Top
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1 # Reverses the direction
# Bottom
if ball.ycor() < -290:
ball.sety(-290)
ball.dy *= -1
# Left
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
score_a += 1
pen.clear()
pen.write("Player A: {} Player B: {}".format(score_a , score_b),align="centre", font=("Courier", 24, "normal"))
# Right
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
score_b += 1
pen.clear()
pen.write("Player A: {} Player B: {}".format(score_a , score_b),align="centre", font=("Courier", 24, "normal"))
# Paddle and Ball Collisions
if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40) :
ball.setx(340)
ball.dx *= -1
if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40) :
ball.setx(-340)
ball.dx *= -1
clock.tick(60)
AttributeError: 'builtin_function_or_method' object has no attribute 'tick'
clock = pygame.time.Clock()
this is the best python tutorial i've ever seen in my life
It's PyGame