How to Upload Pygame Games to Website
Building a game with PyGame and Replit
So far, nosotros've mainly seen how to write text-based programs, or those with a basic web forepart end. In this tutorial, nosotros'll instead build a second game using PyGame. Y'all'll use animated sprites and larn how to:
- Make these sprites move
- Recognise when a sprite is clicked with the mouse.
The basic premise of the game is every bit follows. You lot're a juggler, learning to juggle. Balls will fall down from the top of the screen, and you'll need to click them to 'throw' them up again. After several successful throws without dropping any balls, more than balls volition be added to make the game harder.
Creating a PyGame repl
Although PyGame is a standard Python library, Replit provides information technology installed as a carve up language. Create a new repl and select PyGame from the language dropdown.
You'll see "Python3 with PyGame" displayed in the default console and a split pane in the Replit IDE where you will be able to see and interact with the game you will create.
The starting time thing we demand is a and so-called "sprite", which is a bones image file that nosotros volition apply in our game. Download the lawn tennis ball file bachelor hither and save it to your local automobile.
Now upload it to your repl using the upload file
push and you should be able to see a preview of the prototype by clicking on it in the files pane.
Displaying the sprite using PyGame
Our first goal is to brandish the tennis ball in a game environment using PyGame. To do this, go back to the main.py
file and add the following lawmaking.
import pygame WIDTH = 800 Acme = 600 BACKGROUND = (0, 0, 0) class Brawl: def __init__(self): self.image = pygame.prototype.load("small_tennis.png") self.rect = self.prototype.get_rect() def main(): pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() brawl = Brawl() while True: screen.fill up(BACKGROUND) screen.blit(ball.paradigm, ball.rect) pygame.display.flip() clock.tick(60) if __name__ == "__main__": master()
This code looks a bit more complicated than it needs to exist because in addition to cartoon the ball to the screen, it also sets up a game loop. While basic 2nd games announced to move objects around the screen, they ordinarily really simulate this effect by redrawing the entire screen many times per second. To account for this we need to run our logic in a while True:
loop.
We start by importing PyGame and setting upwardly some global variables: the size of our screen and the background colour (black). We so define our Ball
, setting upward an object that knows where to find the image for the ball and how to get the default coordinates of where the image should be drawn.
We so prepare PyGame past calling init()
and starting the screen as well as a clock. The clock is necessary because each loop might take a different amount of fourth dimension, based on how much logic needs to run to calculate the new screen. PyGame has congenital-in logic to summate how much time elapses between calls to clock.tick()
to describe frames faster or slower as necessary to keep the game feel smooth.
We offset the game loop and telephone call blit
on our ball. Blitting refers to moving all of the pixels from our sprite file (the tennis ball) to our game environment. The flip()
function updates our screen and the tick(threescore)
telephone call means that our game will redraw the screen effectually 60 times per second.
If y'all run this code, you should see the ball pop up in the top right pane, as shown below.
Making our tennis brawl movement with each frame
Although PyGame has a lot of built-in logic for handling common game operations, you still need to get your easily dirty with calculating some of the basic movements. For every loop, we need to tell our game the new X and Y coordinates to describe the ball. Every bit we want our ball to move at a constant speed, we'll move the X and Y coordinates each loop.
Add two methods to your Ball
grade: update
and move
, and add a speed attribute. The new code for your Ball
grade should look every bit follows.
class Ball: def __init__ (self) : self.image = pygame.prototype.load("small_tennis.png") self.speed = [0, 1] self.rect = self.image.get_rect() def update (cocky) : self.move() def move (cocky) : cocky.rect = cocky.rect.move(self.speed)
Now modify your game loop to include a call to the new update()
method. The loop should await every bit follows.
while True: screen.fill(BACKGROUND) screen.blit(ball.image, ball.rect) ball.update() pygame.display .flip() clock.tick(60)
The (0, 1)
tuple causes the ball to move its Y coordinate by i each loop and keep a constant X coordinate. This has the effect of making the ball drop slowly downward the screen. Run your code over again to cheque that this works.
When the ball gets to the bottom of the screen, information technology'll just continue falling merely that'southward OK for now. Let's see how we can add click detection.
Processing events: Detecting mouse clicks
PyGame records all "events", including mouse clicks, and makes these available through pygame.event.get:()
. Nosotros demand to check what events happened in each game loop and see if whatsoever of them were important.
If the user clicks on an empty space, that will withal be recorded but we will simply ignore it. If the user clicks on a falling ball, nosotros desire it to change direction.
At the start of the loop, right after the line that reads while True
, add the following lines of code.
for event in pygame.event .go(): if issue.type == pygame.MOUSEBUTTONDOWN: if brawl.rect .collidepoint(pygame.mouse .get_pos()): ball.speed = [0,-1]
With this code, we loop through all events and cheque for left click (MOUSEBUTTONDOWN
) events. If we find i, we check if the click happened on top of the ball (using collidepoint()
which checks for overlapping coordinates), and in this case we contrary the direction of the brawl (still no ten-axis or horizontal move, but nosotros make the ball movement negatively on the y-axis, which is up.)
If yous run this code again, you should at present be able to click on the brawl (let it fall for a while first) and see information technology modify direction until information technology goes off the height of the screen.
Making the ball bounce off the edges and movement randomly
To simulate juggling, we desire the ball to bounce of the "roof" (height border of the screen) and "walls" (left and correct edge). If the ball touches the "floor" (bottom edge) we want to kill it and remove it from the game equally a dropped ball.
To achieve this, we'll add together logic to our update()
method (this is why nosotros kept it separate from our move()
method before). Add together 2 lines of code to update()
to make it expect every bit follows.
def update (self) : if self.rect.tiptop < 0: self.speed = [0, 1] self.movement()
This checks to encounter if the top of the brawl is above the top of the screen. If it is, we set up the speed dorsum to (0, i)
(moving downward).
So far, we have restricted the brawl to moving vertically, but we can apply the aforementioned principles and move it horizontally or diagonally too. Let'south also add some randomness into the mix and so that information technology'south less predictable (and harder for the player to press). The ball will randomly change its horizontal movement when it bounces off the ceiling and each time we throw it.
Import the random
module at the top of your file and use the random.randrange()
part to specify the range of acceptable horizontal motility. Likewise modify the update()
part to observe if the ball is falling off the left or right edges and reverse its horizontal movement in this case.
Finally, modify the collision detection department to add together randomness in that location besides.
Your full lawmaking should now look as follows.
import pygame import random WIDTH = 800 Summit = 600 BACKGROUND = (0, 0, 0) class Ball: def __init__(self): cocky.image = pygame.image.load("small_tennis.png") self.speed = [random.uniform(-4,4), 2] self.rect = self.image.get_rect() def update(self): if self.rect.pinnacle < 0: self.speed[ane] = -self.speed[1] self.speed[0] = random.uniform(-iv, 4) elif cocky.rect.left < 0 or self.rect.right > WIDTH: self.speed[0] = -self.speed[0] cocky.movement() def move(cocky): cocky.rect = cocky.rect.move(cocky.speed) def primary(): clock = pygame.fourth dimension.Clock() ball = Ball() pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) while True: for consequence in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if ball.rect.collidepoint(pygame.mouse.get_pos()): ball.speed[0] = random.compatible(-4, iv) ball.speed[1] = -2 screen.fill(Background) screen.blit(ball.epitome, ball.rect) ball.update() pygame.brandish.flip() clock.tick(60) if __name__ == "__main__": main()
If you run your code again, yous should exist able to juggle the ball around by clicking on it and watch it randomly bounce off the ceiling and walls.
Adding more balls
Juggling with i brawl is no fun, so let'due south add some more. Because nosotros used Object Oriented Programming (OOP), nosotros tin create more balls past instantiating more Ball()
objects. We'll need to keep rail of these then we'll add them to an array. For each iteration of the game loop, we'll need to update the position of each ball, so we'll need 1 more than loop to account for this.
We also want to start keeping track of which of our assurance is "alive" (that is, hasn't hitting the ground), so add together an attribute for this to the Ball
class as well, in the __init__
function.
cocky.alive = Truthful
In the main()
function, straight before the while True:
line, add together the following lawmaking.
ball1 = Ball() ball2 = Ball() ball3 = Ball() balls = [ball1, ball2, ball3]
At present remove the ball=Ball()
, brawl.update()
and screen.blit(...)
lines and replace them with a loop that updates all of the balls and removes the dead ones (even though we haven't written the logic yet to stop the balls from ever being alive.)
for i, ball in enumerate(assurance): if ball.live: screen.blit(ball.paradigm, ball.rect) ball.update() if non ball.live: del balls[i]
You lot'll also need to business relationship for multiple balls in the the event detection loop. For each result, loop through all of the assurance and cheque if the mouse click collided with whatever of them.
At this point, the total main()
function should look as follows.
def main(): clock = pygame.time.Clock() pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) ball1 = Brawl() ball2 = Ball() ball3 = Ball() assurance = [ball1, ball2, ball3] while Truthful: for effect in pygame.outcome.get(): if event.blazon == pygame.MOUSEBUTTONDOWN: for ball in balls: if ball.rect.collidepoint(pygame.mouse.get_pos()): ball.speed[0] = random.randrange(-4, four) ball.speed[one] = -two break screen.fill(BACKGROUND) for i, ball in enumerate(assurance): if brawl.alive: screen.blit(ball.image, brawl.rect) ball.update() if non ball.alive: del assurance[i] pygame.brandish.flip() clock.tick(60)
To kill balls when they fall through the floor, we tin add together some other cheque to the update()
role as follows.
elif self.rect.bottom > Tiptop: self.alive = False
Run the code again and you should be able to juggle three assurance. Run across how long you can keep them in the air.
If you want a harder version, add a counter to keep track of how many successful throws the player has achieved and add together a new ball for every three successful throws.
Now the game is to see how many balls yous can juggle with. If it's also easy, change the speeds and angles of the assurance.
Make information technology your own
If you followed along, you lot'll already accept your own version of the repl to extend. If non, start from ours. Fork it from the embed below.
Where next?
You've learned how to make 2d games using PyGame. If you lot want to brand more games but are stuck for ideas, check out PyGame's extensive collection of examples.
You could also extend the juggling game more. For case, make the balls advance as they fall, or increment the speed of all balls over time.
Source: https://docs.replit.com/tutorials/07-building-a-game-with-pygame
0 Response to "How to Upload Pygame Games to Website"
Post a Comment