r/learnpython • • Jun 01 '20

Built PONG! I am soo happy!

I was doing the course "An Introduction to Interactive Programming in Python (Part 1)" by Rice Uni in coursera and there was a assignment were we had to build the pong game. This is actually something I am really proud of! Took me around 7 hours and lots of messy code!

Would love any code feedback!

PONG GAME

ps: click the run button in the editor

353 Upvotes

66 comments sorted by

50

u/Big_Boss_Bob_Ross Jun 01 '20

The code is pretty good considering its only functions. Good job! My recommendations for improvement.

  • Dont be afraid of functions. They make things really nice. For example, every frame you draw the paddles and other stuff in the exact same way, so perhaps you could separate those into small functions. The ball collision is always done the same way, so same for that maybe :)

  • This isnt really applicable now, but maybe when you get a hold of classes you could come back and do this exact same thing with a class implementation instead.

Otherwise, great work!

10

u/[deleted] Jun 01 '20

Thank you for the feedback! From now on I will try to break the codes into smaller functions. I kind of get scared of them, because when I try to understand the stack, lot's of fucntions make it really hard for 'me' to keep track of them. I think, this will get better as I get more experience.

And, I am learning about classes and oop today! And I am soo excited! I will refactor the code after I have somewhat basic understanding of object :D

Thank you for taking the time and reviewing my code <3

11

u/Big_Boss_Bob_Ross Jun 01 '20

No worries at all my friend! Note that in my opinion, at the top level your functions should be like a high level overview of the program. If you think about it, its just;

  1. Update the ball

  2. Update the paddles

  3. Check collisions

  4. Draw the paddles

  5. Draw the ball

  6. Draw the other line stuff

  7. Draw the midline and gutters

  8. Draw the scores

At least, thats how I like to think about my programs. Good luck

6

u/[deleted] Jun 01 '20

It sounds easy! I will do that and comment the link here later today. Will,be lookong forward to your review again! You're so helpful and reallay thank you for taking the time to guide someone like me (a newby) ♥

2

u/[deleted] Jun 01 '20

when I try to understand the stack, lot's of fucntions make it really hard for 'me' to keep track of them.

I struggle with this too. It makes it hard to understand. Especially in a dynamic language where you don't have type definitions to show you the way.

1

u/[deleted] Jun 02 '20

I think, every beginner faces this problem! The codeskulptor environmrnt has a viz mode to see the stacks and calls. But still, it is really frustrating sometimes!

11

u/CraigAT Jun 01 '20

Great constructive comments too!

Glad to see you mention classes without insisting upon them.

6

u/vtable Jun 01 '20

First off, nice job.

I would try to avoid the global variables. It's much debated whether or not they're "dangerous" but I believe it's a good habit to try to minimize them. As your program grows, or you start to break it into modules so that other apps can share code, globals can get a bit messy.

Since paddle1_pos, for example is at module scope, ie not inside a function or class, any code can use it, even code that imports your file. This can make maintenance harder.

One way to avoid globals is to use classes. Variables like the paddle position are defined in the class. Methods in that class can access them but code outside can't (unless you let them in which case you can control how they use them). This is cleaner. Classes also make initialization much cleaner.

For example, you could have a class "Paddle" with a "pos" variable inside. You would then create an instance of Paddle for each player and the class remembers the "pos" for each one (so you don't get bugs like accidentally using the paddle 2 position for paddle 1).

And if you decide to have a 4-paddle game, without classes, you start getting a lot of variables to keep track of. Classes do a lot of that work for you.

I don't know if you didn't use classes because you're just not that far in the course or not. Some people shy away from them thinking they're scary or too hard. They're just a step or two past what you're already doing. Making a new version of your game to use classes might be a great way to learn them.

4

u/[deleted] Jun 01 '20

Thanks for the simple explanation about why calsses are important! Much appreciated!

In the course they did mention that we should avoid global variables and when I was trying to learn JS all of the teachers were saying that we should not use variables in the global scope. But as I don't know OOP (it made me feel uncomfortable and I always think that I will never understand it), I was never able to create local variables. Though I could use a function but I didn't know how to update a variable inside some other function. So I used globals here.

The course teaches Class and OOP in the second part which I am going through now and after somewhat practice I want to get back to this one and use Pygames instead! Let's see if I can conquer my fear of OOP :D

3

u/mriswithe Jun 01 '20

I felt the same way about classes but now I use them all the time. I think the best way to think about them is they are a great way group relevant data and provide actions to take on that data.

Like a paddle class could have the x/y position and a method for moving the paddle. Maybe the textures for the paddle or color or size.

That way you can have two instances of the paddle class, one is the left paddle one is the right. Can act on them the same way, etc.

2

u/[deleted] Jun 02 '20

As I am learning more and more about programming in general and objects, I think I am staring to love it myself!

1

u/mriswithe Jun 02 '20

Yeah it seems like as a beginner especially the best way to think of classes is that they could be thought of as a portable toolkit with a bunch of related tools packed together. Or just a bucket you put similar crap into hah

3

u/[deleted] Jun 01 '20 edited Jun 01 '20

I'm only about as far into the python crash course book as the exceptions chapter, but I've been building stuff like this.

I'll start writing things top down like normal, then realize I can start breaking chunks of that code into functions, like what you did. Then I realize I can start separating functions into classes, and then all the variables are handled inside the class instead.

When I started doing that, I started realizing I don't really need an order to my code outside of each function. I can rearrange, add, mix and match functions (well, I guess methods once they're inside a class), make many versions of a class really easily just by making an instance of them (VERY easy to do), and that's when it all starts feeling like I'm building Lego blocks to put together however I want, rather than trying to build an entire Lego structure from top to bottom in one go.

I've only been at this a couple of weeks, but I think that's what object oriented programming might be fundamentally about. You're just making a bunch of fundamental Lego pieces you can use however you want. And each lego block can be easily modified without breaking a bunch of other stuff, because it's all modular.

And it's not like I tried to think modularly from the start. It just pushes you naturally in that direction when you force yourself to start by simply organizing code into methods (functions) inside classes. To make all the plugs work when you organize your code by functions, then organize those functions into classes as methods, each little problem you solve to make your code still work ends up with you building a little modular system. Then it's like oh shit, I can easily mix and match things now. You're forced into OOP thinking just by making classes and methods, because the way to pass info in and out and between them is all modular. The "self" word will start making a ton more sense as you force yourself to do it this way.

I might be wrong because I'm just starting out too, but I think that's what object oriented programming is. Thinking in these blocks. Just make the blocks and you'll be forced to solve problems as objects; At least with the basics anyway. I have no idea what's coming up. I still have much to learn.

2

u/[deleted] Jun 02 '20

I am fairly new too. But trust me, I feel that you gave a solid explanation about OOP. It did make me understand some bits about Objects though! You are really good at explaining in your own way! keep it up!

3

u/InYourFace555 Jun 01 '20

this is so true. I have a task of developing new function for a GUI application (just small one for my team) and the previous developers did not use OOP at all. It results in too many redundant codes which are repetitive and like you said, the use of global variables for drawing canvas. I am hesitate to use those but refactor the whole app to OOP at this point seems like not a good idea as well :(

2

u/[deleted] Jun 02 '20

What I think is this would be a great challenge for you to refactor the entire thing! Should be fun as well!

5

u/AnonKS Jun 01 '20

I did this course in 2013. It was a lot of fun. Great job btw 👍🏻

1

u/[deleted] Jun 01 '20

Thank You! I came to know about this course when I was looking for ways to learn about CSE on my own and I found OSSU. From there, I was looking for a way to get the certificate as well. It's expensive for me! Trust me! But got an opportunity to do the entire specialization track for free! Now I'm on Part 2 and seems so fun and has given me an great into to python as well!

1

u/AnonKS Jun 01 '20

Have you started on “Rice Rocks” yet? The asteroid clone. That’s really going to test your nerves and patience but it’s worth it. That course is great for boosting your confidence with python.

1

u/[deleted] Jun 02 '20

No, I have not. I am doing the second week of part two. Completed the meomory game. It's getting harder as they get deep into the stuff.

As you have done this course, what would be a good course/reading/project that I should do after doing this course? What do you think?

2

u/AnonKS Jun 02 '20

Most courses start off with basics. I’d say move to a specialty course. You should understand Python pretty well by the time you’re done so no use in doing another python course. If you want to do web dev, go do a “web dev with python” course or if you wanna do machine learning or data science, find a course for that. Otherwise just keep coding every day. As long as you use it all the time, you can only move forward. If you take a break, you’ll forget stuff very quickly.

1

u/[deleted] Jun 02 '20

Otherwise just keep coding every day

This makes a great programmer. But everyday I feel like I don't have any idea about what to code! That's a "me" problem. I should start making silly small things which will keep me in practice! Thank you so much!

1

u/AnonKS Jun 02 '20

After I did that course I made friends with a Linux developer, who was working on his own distro. There were lots of fun challenges there while practicing python and gaining a deeper understanding of Linux. Contributing to open source projects is an awesome way to practice and you’d be helping out. Also there are lots of programming challenges out there. I just found this one: https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt

You don’t always need to come up with something original to practice.

4

u/[deleted] Jun 01 '20

Good job congratulations

1

u/[deleted] Jun 01 '20

Thank you!

4

u/[deleted] Jun 01 '20

That's awesome and crazy simple. I wonder how that would look like on Pygame.

3

u/[deleted] Jun 01 '20

I was thinking the same when I saw some pygame videos :D I will keep that in my todo. But before I want to learn more about Python and OOP! OOP's sounds scary!

2

u/[deleted] Jun 01 '20 edited Jun 01 '20

OOP in Python really is simpler than it looks, but no one seems to know how to teach it correctly. Theory did not helped me one bit, it seems to just make things needlessly convoluted when you’re starting out. And many resources uses silly metaphors about how OOP is all about mimicking real life objects — that’s not precise. OOP is a practical way to pass the same variables and functions among the members of a class, and self is the object that allows you to do that without directly changing any values outside of the class. It’s a neat organization tool. It seemed way less scary when I realized that.

IMHO the book Python Crash Course achieves a great balance when teaching that subject, and it has a great Pygame project/tutorial to follow.

2

u/[deleted] Jun 02 '20

Though I don't know much about Objects yet but it makes it easy for me to understand it as real life objects. But, the self thing has not make any sense yet. I am learning and reading, let's see if I get some deep understanding!

Thank you for the suggestion about the book btw! I will definitely look into it.

1

u/[deleted] Jun 02 '20 edited Jun 02 '20

it easy for me to understand it as real life objects

That's cool, people learn in different ways. Just understand that this metaphor will only take you so far. I found it easier to understand once I left it behind.

Regarding self, it's not that hard: when you put something after self., like self.my-variable, this means that whatever value you store on self.my-variable is only directly available to the entire class and nothing else. So it's easy to share the same variable between several methods (methods are exactly like functions, but they're inside of a class). You could use global variables and scattered functions, but classes provide a syntax that's useful in some cases. In Pygame, for example, I can have a single object, let's call it self.ship (as in spaceship), that I need to access from several methods. I create it in another class/file and initialize it in my main class (to self.ship). After that, I can access all its parameters and methods from any point in the main class.

This is handy to pass values around -- let's say I want method A to change the position of the ship, method B to check if it collided with an enemy and method C to calculate the hit points from an eventual collision. I'll need to access and manipulate several parameters, and classes allow me to neatly create and visualize this progression.

When you don't put the self before the variable Python won't know that it should be accessible to other methods, so it's a local variable that only that method can access (directly at least). The purpose of self is to differentiate between variables that must be available to the entire class, and variables that should only be accessible to that particular method.

Well, at least that's my understanding. I'm a beginner too. It took me quite a while to understand OOP.

4

u/skellious Jun 01 '20

you've got a solid start here. Is there any reason you're not using python 3 though? 2.7 is pretty damn ancient by now.

In terms of gameplay, your collision detection is missing collisions, particularly with the top of the paddle, that should count from a gameplay perspective. You might need to review exactly how lenient your collision code is.

Secondly, the game will feel a long more rewarding if you make the ball bounce off the paddles as if the paddles are curved. right now, they are like hitting a brick wall, so the player cannot change the direction of the ball based on what part of the paddle it hits.

overall though, very good job!

1

u/[deleted] Jun 02 '20

Is there any reason you're not using python 3 though? 2.7 is pretty damn ancient by now.

The course that I am taking is based on python 2.7 - that's why!

In terms of gameplay, your collision detection is missing collisions, particularly with the top of the paddle, that should count from a gameplay perspective. You might need to review exactly how lenient your collision code is.

Secondly, the game will feel a long more rewarding if you make the ball bounce off the paddles as if the paddles are curved. right now, they are like hitting a brick wall, so the player cannot change the direction of the ball based on what part of the paddle it hits.

I am really new into programming :D I am not sure that I can implement these currently!

3

u/Yassine_kharrat Jun 01 '20

It is good and simple ! even the code doesn't look messy for beginner but it can be improved!

-You can make the ball get faster by time! the game must be challenging

-You can add function that check whether or not one's score is equal to 10. It can determine who is the winner and loser .

There are more you can add and improve but I guess others already mentioned it.

Good luck out there! :)

3

u/[deleted] Jun 01 '20

Thank you for the feedback and I never tought about selecting an winner though! I have to implement that! BUT, I did implement the code for speeding up the ball whenever it hits one one of the paddle. So that each game starts slow and gets faster. 🙂

3

u/teachmehindi Jun 01 '20

I have a question about the course. How did they teach it? Did they explain the fundamentals then tell you to design the logic yourself?

4

u/[deleted] Jun 01 '20

This is a good course. If you know highschool math (I had to watch some khan Academy videos because I forgot a lot of things). At some point I felt frustrated because I was stuck while solving the problems. They'll teach you the basic and then really make you solve a problem which is really hard and it's a good way to learn if you managr to solve the problem.

Totally recommended. But remember, while doing the projects, google will be your best friend. But don't copy the code, understand it and then implement.

Con: It's really hard to get peer reviews. I had to post and comment on the discussion Forum to get 5 reviews.

2

u/kekexaxamimi Jun 01 '20

Damn my basic math level is garbage...

1

u/[deleted] Jun 01 '20

I feel you! But you need it to do some of the calculations! Most of the time the solution is a simple google search away!

3

u/ProV13 Jun 01 '20

Great job on the game. How long have you been coding to be able to do that? I started coding 4 days ago and I couldn't imagine doing something like that yet.

4

u/[deleted] Jun 01 '20

I started in 2013 :D Like literally! I used to watch some programming videos mindlessly without understanding one single thing! Then started learning about HTML and CSS. After that went into JavaScript. Read a lot and watched a lot but did nothing. Not a single project. Maybe because I was not creative enough to think about projects! Then wen't into PHP got stuck in OOP. Then without completing that started building websites using WordPress to make some cash while studying political science in a Uni (currently doing my masters). And a few weeks back, I realised that I do web dev without having any deep understanding of programming. So started pursuing python! Now here I am! Completed something that I feel really proud of.

Now, it can take you some time to get used to coding, but keep at it! Look at others code and please don't be like me! Build anything! You are creative! Everyone is! Good luck in your journey. Hit me up any time, we can talk and go through this together even! Cheers!

3

u/jadacee Jun 01 '20

was the course on coursers free? would love to try it

2

u/[deleted] Jun 01 '20

The course materials are free! But you won't be able to submit any project, quizzes and get grades. Without grades you won't get the certificate!

3

u/Aidensamuel00 Jun 01 '20

That's not entirely accurate for coursera might be for this course but the one I'm doing is free and they give you grades and if I'm not mistaken the free certificate if you pass in all the quizzes and programming assignments.

1

u/[deleted] Jun 02 '20

My answer was not pointed at coursera as a whole. What I waa talking about was the particular course.

3

u/Infreezy Jun 01 '20

2

u/[deleted] Jun 01 '20

Good luck in the journey! How are you liking the course?

3

u/robot_ankles Jun 01 '20

Building a game is a big accomplishment and a great way to learn python programming. I've found it's a good motivator because it's a project that delivers a fun experience that YOU built. Delivering a fully functioning game actually requires solving a lot of common problems.

Next up: consider making a Tetris clone. Add score keeping based on how many lines are cleared. Menu screen. Increasing level difficulty. Two player head-to-head. There's such a variety of little features to explore based on what problem you want to tackle.

2

u/[deleted] Jun 02 '20

it's a project that delivers a fun experience that YOU built

This moment can be priceless!

Next up: consider making a Tetris clone.

I am pretty new! :D I don't think I can handle tetris logic at the time. But that can be a new and challenging experience! Which will also help me learn more!

1

u/robot_ankles Jun 02 '20

I am pretty new! :D I don't think I can handle tetris logic at the time.

So I'll share some additional thoughts. NO intent to pressure anyone into making Tetris, but just some food for thought about how to break down a problem like this.

Watch most Tetris games very closely. Although it looks like blocks moving down, is it really? The blocks 'tick' down in block-sized units. Imagine the playfield is a bunch of light-up boxes and the 'dropping blocks' are really just different lights being turned on and off.

Make a little 5 x 5 array.

Store an 1 or zero (on/off state) in each position of the array.

Display the array on a screen. Maybe offs are represented by little periods and ons are represented by asterisks.

Write a loop that lights up (changes to asterisk) row 4 (top row), pos 2.

..*..
.....
.....
.....
.....

...Then keeps the column position, but reduces the row by one to row 3, pos 2. Oh, and turn off 4,2.

.....
..*..
.....
.....
.....

Then 2,2 on / 3,2 off.

Then 1,2 on / 2,2 off.

Then 0,2 on / 1,2 off.

Finally 0,2 off.

You just made a tiny playfield and had a single block drop from the top, hit the bottom and disappear.

Now add a keyboard check to see if anyone is pressing a left or right arrow key. If the left arrow is pressed, reduce the column position by one.

.....
.*...
.....
.....
.....

Try to steer the block left/right as it drops. What happens if the block is in the left-most column and you press left again?

...

This gets you working on creating the underlying building blocks of Tetris (pun intended) and solving little problems as you go. ie: What happens when you try to 'move' the falling block to an invalid column. Can I spawn a new block after the first block disappears? Can I have the new block spawn at the top of a random column? How do I limit the random range to the number of columns in the array?

You've just made Anampartho's Block Dropper Madness!

Award one point for every block that hits the bottom row and disappears. Display the current score:

..*..
.....
.....
.....
.....
points: 5

3

u/[deleted] Jun 01 '20

I was doing the course "An Introduction to Interactive Programming in Python (Part 1)" by Rice Uni in coursera and there was a assignment were we had to build the pong game. This is actually something I am really proud of! Took me around 7 hours and lots of messy code!

Would love any code feedback!

PONG GAME

​>ps: click the run button in the editor

You're off to a great start, now you can port it to the tablet. What are you doing is a casual game, and mobile devices are a key market of such games.

2

u/[deleted] Jun 02 '20

now you can port it to the tablet. What are you doing is a casual game, and mobile devices are a key market of such games.

;) great idea! :D Let's see what future has in store for me!

2

u/[deleted] Jun 01 '20

excellent!

2

u/[deleted] Jun 01 '20

Thank you!

2

u/hnguyen01122 Jun 01 '20

Great job. Rice Uni is a private institution too. The lectures must have been top notch judging by you have to visit Khan Academy? 😀

I’m very happy for you. If you really like it you should mention more in this subreddit to help others on the same journey like you.

These MOOC truly outstanding and finally open up education for anyone wanting to learn around the globe and to be able to change their lives.

2

u/[deleted] Jun 01 '20

The lectures are really good. I had to look into khan academy because I forgot some of the math terms/rules/theory. I am doing my Masters in Political Science and last I did math was 6 years ago! Now you know why I had to watch khan academy :P

Other then that, the course materials are really good.

I always think about talking about stuff that I learn, but the problem is, "I" feel that, if I talk about something which I learned from google search, I am not actually contributing, I am just copying content that is already available in the internet. That how "I" feel! That's why I was never able to write any post! I fear the judgements I guess.

The MOOCs are great. It has given me the opportunity to get the education that the students get in person. As I said before that I study political science, these moocs opened my door for learning CSE :D

2

u/[deleted] Jun 01 '20

Great work!!

1

u/[deleted] Jun 02 '20

Thank you!

2

u/shiftybyte Jun 01 '20

Looks cool, congratulations!

2

u/[deleted] Jun 01 '20

Thank you!

4

u/[deleted] Jun 01 '20

[removed] — view removed comment

2

u/[deleted] Jun 01 '20

I am sorry that you had to deal with that problem! It's the library the course provides and the submissions had to be done through codeskulptor! I am pretty new in python and don't yet know about how to run in locally! I want to try that out pretty soon though!

2

u/[deleted] Jun 01 '20

[removed] — view removed comment

1

u/[deleted] Jun 02 '20

Solving problems are always so enjoyable!

2

u/[deleted] Jun 02 '20

[removed] — view removed comment

1

u/[deleted] Jun 02 '20

17 experience with Linux

years I guess? Man that's long! You'r name also suggests that you love liux! I did try to use linux sometimes, but as I do some freelance work for livelihood, I use Photoshop and Illustrator and I am not used to in GIMP. So I was never able to fully migrate to linux. But when I get some more into programming then I will obviously move to linux. Windows can be a PITA sometime!