Name:
[17666] Kenny X
Member:
45 months
Authored:
5 videos
Description:
A young Python programmer ...
Pygame tutorial - Gameplay [ID:1793] (3/3)
in series: Using Pygame for Games
video tutorial by Kenny X, added 02/10
Name:
[17666] Kenny X
Member:
45 months
Authored:
5 videos
Description:
A young Python programmer ...
Our authors tell us that feedback from you is a big motivator. Please take a few moments to let them know what you think of their work.
In this tutorial, you will learn how to add actual gameplay in your game.
You will learn about MOUSEBUTTON and how to make mouse input. It will be an extension of the previous tutorial, where when you click the ball it will go faster and your score will increase.
#!/usr/bin/env python
import sys
import pygame
from pygame.locals import *
#---Our variables
black = (0,0,0)
size = (600, 400)
speed = [3,3]
score = 0
#---init pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.png").convert()
ballrect = ball.get_rect()
#---main loop
while True:
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
if ballrect.collidepoint(event.pos):
score += 1
if speed[0] > -1 or speed[1] > -1:
speed[0] += 1
speed[1] += 1
else:
speed[0] -= 1
speed[1] -= 1
else:
score -= 1
if event.type == QUIT:
sys.exit()
ballrect = ballrect.move(speed)
#---check if the ball collides
if ballrect.left < 0 or ballrect.right > size[0]:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > size[1]:
speed[1] = -speed[1]
screen.fill(black)
if pygame.font:
font = pygame.font.Font(None, 26)
text = font.render("%d Score" % score, True, (255, 0, 0))
textpos = text.get_rect(centerx=screen.get_width()/2)
screen.blit(text, textpos)
screen.blit(ball, ballrect)
clock.tick(40)
pygame.display.flip()
Got any questions?
Get answers in the ShowMeDo Learners Google Group.
Video statistics:
- Video's rank shown in the most popular listing
- Video plays: 1305 (since July 30th)
- Plays in last week: 1
- Published: 40 months ago
Thank-yous, questions and comments
If this video tutorial was helpful please take some time to say thank-you to the authors for their hard work. Feel free to ask questions. Let the author know why their video tutorial was useful - what are you learning about? Did the video tutorial save you time? Would you like to see more?
You may also want to see our ShowMeDo Google Group to speak to our active users and authors.
All comments excluding tick-boxed quick-comments
good job. Good video.
Thanks for a nice and genuine video =)
For change speed of the ball:
speed[0] += speed[0] / abs(speed[0])
speed[1] += speed[1] / abs(speed[1])
or in one line:
speed = [speed[0] + (speed[0] / abs(speed[0])), speed[0] + (speed[1] / abs(speed[1]))]
Because your code is:
1. long
2. wrong:
- [1,1] => [2,2]
- [-1, -1] => [-2, -2]
- [1, -1] => [2, 0]
- [-1, 1] => [0, 2]
But good video ^_^
Lovin' it. So much fun to be had, so little time...
Sorry about the bad audio syncing!
