I'm making a Flappy Bird clone in PyGame and I'm trying to add a moving background image. I'm using a 800x600 image right now, and for some reason, when I blit the image, the performance suffers terribly. Is there something I'm doing wrong that is taking up a lot of resources?
import pygame, sys
import random
from pygame import *
pygame.init()
red = (255, 0, 0)
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("flap it up")
clock = pygame.time.Clock()
MAX_VEL = 5
GAP = 175
WALLSPEED = -2
WALLEVENT = pygame.USEREVENT+1
SCOREEVENT = pygame.USEREVENT+2
pygame.time.set_timer(WALLEVENT, 5000)
pygame.time.set_timer(SCOREEVENT, 2500)
myfont = pygame.font.SysFont("monospace", 18)
class Player(object):
def __init__(self):
self.rect = pygame.Rect(384, 284, 32, 32)
self.xvel = 0
self.yvel = MAX_VEL
self.xcel = 0
self.ycel = 1
def move(self):
self.rect.top += self.yvel
if self.yvel < MAX_VEL:
self.yvel += self.ycel
else:
self.yvel = MAX_VEL
def jump(self):
self.yvel = -15
def draw(self):
pygame.draw.rect(screen, red, self.rect)
class Wall(object):
def __init__(self, y):
self.rect1 = pygame.Rect(800, y, 32, 600-y)
self.rect2 = pygame.Rect(800, 0, 32, y-GAP)
self.xvel = WALLSPEED
def move(self, walls):
self.rect1.x += self.xvel
self.rect2.x += self.xvel
if self.rect1.x < -31:
walls.remove(self)
def draw(self):
pygame.draw.rect(screen, green, self.rect1)
pygame.draw.rect(screen, green, self.rect2)
class BG(object):
def __init__(self, x):
self.x = x
self.xvel = WALLSPEED
self.img = pygame.image.load("bg.jpg")
def move(self, bg):
self.x += self.xvel
if self.x < -799:
bg.remove(self)
bg.append(BG(self.x+1600))
screen.blit(self.img, (self.x, 0))
def lose():
pygame.quit()
quit()
def main(player, walls, bg, score, playing):
while playing:
for event in pygame.event.get():
if event.type == KEYDOWN:
player.jump()
if event.type == WALLEVENT:
numbo = random.randrange(GAP, 600, 25)
walls.append(Wall(numbo))
if event.type == SCOREEVENT:
score += 1
for b in bg:
b.move(bg)
label = myfont.render("Score: " + str(score), 1, (0, 0, 0))
screen.blit(label, (30, 20))
player.move()
player.draw()
for w in walls:
w.move(walls)
w.draw()
if player.rect.colliderect(w.rect1) or player.rect.colliderect(w.rect2):
lose()
playing = False
clock.tick(60)
pygame.display.update()
player = Player()
walls = []
bg = []
score = 0
walls.append(Wall(300))
bg.append(BG(0))
bg.append(BG(800))
playing = True
main(player, walls, bg, score, playing)
Typically, this should not be a problem. You should try to set the FPS manually and see if there is a difference
# Create a clock
clock = pygame.time.Clock()
# Set FPS (frames per second)
clock.tick(50)
Related
This question already has answers here:
How do I detect collision in pygame?
(5 answers)
Closed 1 year ago.
My problem: I am trying to create a vertical ball drop game, and I am testing for collision, which does work. But how would I reset my ball when it hits the hoop? Instead of it detecting and then hitting the bottom of the screen which results in a Game over screen because you lose. Any help is appreciated.
import time, random
from pygame.locals import *
import pygame, sys
pygame.init()
FPS = 60
FramePerSec = pygame.time.Clock()
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
SCREEN_BOTTOM = 0
SPEED = 5
SCORE = 0
font = pygame.font.SysFont("Verdana", 60)
font_small = pygame.font.SysFont("Verdana", 20)
game_over = font.render("Game Over", True, BLACK)
background = pygame.image.load("background.jpg")
DISPLAYSURF = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
DISPLAYSURF.fill(WHITE)
pygame.display.set_caption("Ball Drop")
class Ball(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("Ball.png")
self.rect = self.image.get_rect()
self.rect.center = (random.randint(40, SCREEN_WIDTH - 40), 0)
def move(self):
global SCORE
self.rect.move_ip(0, SPEED)
if (self.rect.bottom > 600):
self.rect.top = 0
self.rect.center = (random.randint(30, 380), 0)
# Need to check PNG for hit detection
class Basket(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("Basket.png")
self.rect = self.image.get_rect()
self.rect.center = (160, 520)
def move(self):
pressed_keys = pygame.key.get_pressed()
if(self.rect.x >= (SCREEN_WIDTH - 145)):
self.rect.x -= 5;
elif(self.rect.x <= -5):
self.rect.x += 5;
else:
if pressed_keys[pygame.K_a]:
self.rect.move_ip(-SPEED, 0)
if pressed_keys[pygame.K_d]:
self.rect.move_ip(SPEED, 0)
class Wall(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("wall.png")
self.rect = self.image.get_rect()
self.rect.center = (0, 670)
B2 = Basket()
B1 = Ball()
W1 = Wall()
balls = pygame.sprite.Group()
balls.add(B1)
# Need to fix wall sprite group
walls = pygame.sprite.Group()
walls.add(W1)
all_sprites = pygame.sprite.Group()
all_sprites.add(B2)
all_sprites.add(B1)
INC_SPEED = pygame.USEREVENT + 1
pygame.time.set_timer(INC_SPEED, 1000)
while True:
for event in pygame.event.get():
if event.type == INC_SPEED:
SPEED += 0.3
if event.type == QUIT:
pygame.quit()
sys.exit()
DISPLAYSURF.blit(background, (0, 0))
scores = font_small.render(str(SCORE), True, BLACK)
DISPLAYSURF.blit(scores, (10, 10))
for entity in all_sprites:
DISPLAYSURF.blit(entity.image, entity.rect)
entity.move()
# NEed to fix collison and Counting stats
if pygame.sprite.spritecollideany(W1, balls):
DISPLAYSURF.fill(RED)
DISPLAYSURF.blit(game_over, (30, 250))
pygame.display.update()
for entity in all_sprites:
entity.kill()
time.sleep(2)
pygame.quit()
sys.exit()
if pygame.sprite.spritecollideany(B2, balls):
print("Hit")
SCORE += 1
pygame.display.update()
pygame.display.update()
FramePerSec.tick(FPS)
pygame.sprite.spritecollideany() returns the hit Sprite (ball) object. Change the position of this ball:
while True:
# [...]
ball_hit = pygame.sprite.spritecollideany(B2, balls)
if ball_hit:
ball_hit.rect.center = (random.randint(30, 380), 0)
SCORE += 1
print("Hit")
# [...]
sprites.py:
import pygame as pg
from settings import *
vec = pg.math.Vector2
# for movement
class Player(pg.sprite.Sprite):
def __init__(self, game):
pg.sprite.Sprite.__init__(self)
self.game = game
self.image = pg.Surface((30, 40))
self.image.fill((255, 255, 153))
self.rect = self.image.get_rect()
self.rect.center = WIDTH / 2, HEIGHT / 2
self.pos = vec(WIDTH / 2, HEIGHT / 2)
self.vel = vec(0, 0)
self.acc = vec(0, 0)
def jump(self):
self.rect.x += 1
hits = pg.sprite.spritecollide(self, self.game.platforms, False)
self.rect.x -= 1
if hits:
self.vel.y = -20
def update(self):
self.acc = vec(0, PLAYER_GRAV)
# pouze zryhlení
keys = pg.key.get_pressed()
if keys[pg.K_LEFT]:
self.acc.x = - PLAYER_ACC
if keys[pg.K_RIGHT]:
self.acc.x = PLAYER_ACC
# apply friction
self.acc.x += self.vel.x * PLAYER_FRICTION
# pohyb tělesa
self.vel += self.acc
self.pos += self.vel + 0.5 * self.acc
self.rect.midbottom = self.pos
if self.pos.x > WIDTH:
self.pos.x = 0
if self.pos.x < 0:
self.pos.x = WIDTH
class Platform(pg.sprite.Sprite):
def __init__(self, x, y, w, h):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((w, h))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
main.py:
import random
import pygame as pg
from settings import *
from sprites import *
class Game:
def __init__(self):
# initialize the game window
self.running = True
pg.init()
pg.mixer.init()
self.screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption('My game')
self.clock = pg.time.Clock()
def new(self):
# to start a new game, reset the pieces
self.all_sprites = pg.sprite.Group()
self.platforms = pg.sprite.Group()
self.player = Player(self)
self.all_sprites.add(self.player)
p1 = Platform(0, HEIGHT - 40, WIDTH, 40)
p2 = Platform(WIDTH / 2 - 50, HEIGHT * 3 / 4, 100, 20)
self.platforms.add(p2)
self.platforms.add(p1)
self.all_sprites.add(p1)
self.all_sprites.add(p2)
self.run()
def run(self):
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.events()
self.update()
self.draw()
def update(self):
self.all_sprites.update()
hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.rect.midbottom = self.player.pos
self.player.vel.y = 0
def events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
self.player.jump()
def draw(self):
self.screen.fill(BLACK)
self.all_sprites.draw(self.screen)
pg.display.flip()
def show_start_screen(self):
pass
def show_go_screen(self):
pass
game = Game()
game.show_start_screen()
while game.running:
game.new()
game.show_go_screen()
pg.quit()
settings.py:
# game settings
WIDTH = 480
HEIGHT = 600
FPS = 60
# player settings
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
PLAYER_GRAV = 0.8
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = ((255, 255, 153))
I have a few questions:
Question n. 1:
Why doesn't the jump method work? And why is it using velocity -20 to jump?
Question n. 2:
I'm not quite sure if I understand the vector coordinates, can someone please try to explain it to me?
I think that this is exactly why I have problems understanding the code.
In pygame, the screen coordinates start at the top left (0,0). Positive Y goes down. Jump is -20 because the player is going up (toward zero). It looks like the player bounces up when it hits an object.
Concerning the jump issue, the game does not start for (Platform not defined) so I can't help there.
Hey I have a problem with my game code. Is there a way to check if, for example, the right side of my player sprite (hero) is colliding with the group obstacle_sprite?
I can only figure out how to check for collision in general but I want only a true output if the right side of the player is colliding wit the obstacle.
In my code I am using a invisible sprite as hitbox and draw the player inside this invisible sprite to check collisions but make it look like the obstacle denies moving of the player.
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PINK = (230, 77, 149)
FPS = 60
window_width = 900
window_height = 600
window_color = WHITE
window = pygame.display.set_mode((window_width, window_height))
window.fill(window_color)
pygame.display.set_caption("Bub - the game")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, velocity, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width + 2*velocity, height + 2*velocity))
self.rect = self.image.get_rect()
self.rect.topleft = (x - velocity, y - velocity)
self.velocity = velocity
self.is_jump = False
self.jump_count = 15
self.fall_count = 1
self.ground = self.rect.bottom
self.body = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, self.body)
def move(self):
key = pygame.key.get_pressed()
if key[pygame.K_a] and self.rect.left >= 0:
self.rect.x -= self.velocity
if key[pygame.K_d] and self.rect.right <= window_width:
self.rect.x += self.velocity
if not self.is_jump:
if key[pygame.K_SPACE] and self.rect.bottom == self.ground:
self.is_jump = True
else:
if self.jump_count >= 0:
self.rect.y -= round((self.jump_count ** 2) * 0.1)
self.jump_count -= 1
else:
self.jump_count = 15
self.is_jump = False
def gravity(self):
if not self.is_jump and self.rect.bottom != self.ground:
self.rect.y += round((self.fall_count ** 2) * 0.1)
if self.fall_count <= 15:
self.fall_count += 1
else:
self.fall_count = 1
def update(self):
self.move()
self.gravity()
pygame.draw.rect(window, BLACK, self.body)
self.body.topleft = (self.rect.x + self.velocity, self.rect.y + self.velocity)
class Obstacle(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((width, height))
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.center = (x, y)
player_sprite = pygame.sprite.Group()
obstacle_sprite = pygame.sprite.Group()
hero = Player(0, 570, 30, 30, 5, BLACK)
player_sprite.add(hero)
obstacle_1 = Obstacle(100, 585, 120, 30, PINK)
obstacle_sprite.add(obstacle_1)
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(window_color)
player_sprite.update()
player_sprite.draw(window)
obstacle_sprite.update()
obstacle_sprite.draw(window)
pygame.display.update()
pygame.quit()
It's easier if you keep track of your player's velocity; this will make handling jumping also less complex.
A common technique AFAIK is to do two collision detection runs: one for the x-axis and one for the y-axis.
Here's how I changed your code. As you can see, checking for the side of a collision is as easy as checking xvel < 0 or xvel > 0:
import pygame
pygame.init()
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PINK = (230, 77, 149)
FPS = 60
window_width = 900
window_height = 600
window_color = WHITE
window = pygame.display.set_mode((window_width, window_height))
window.fill(window_color)
pygame.display.set_caption("Bub - the game")
clock = pygame.time.Clock()
class Toast(pygame.sprite.Sprite):
def __init__(self, *grps):
super().__init__(*grps)
self.image = pygame.Surface((900, 200))
self.image.fill(WHITE)
self.rect = self.image.get_rect(topleft=(10, 10))
self.font = pygame.font.SysFont(None, 32)
def shout(self, message):
self.text = self.font.render(message, True, BLACK)
self.image.fill(WHITE)
self.image.blit(self.text, (0, 0))
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, velocity, color, *grps):
super().__init__(*grps)
self.image = pygame.Surface((width + 2*velocity, height + 2*velocity))
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.topleft = (x - velocity, y - velocity)
self.velocity = velocity
self.on_ground = True
self.xvel = 0
self.yvel = 0
def collide(self, xvel, yvel, obstacle_sprites):
global toast
for p in pygame.sprite.spritecollide(self, obstacle_sprites, False):
if xvel > 0:
self.rect.right = p.rect.left
toast.shout('collide RIGHT')
if xvel < 0:
self.rect.left = p.rect.right
toast.shout('collide LEFT')
if yvel > 0:
self.rect.bottom = p.rect.top
self.on_ground = True
self.yvel = 0
toast.shout('collide BOTTOM')
if yvel < 0:
self.rect.top = p.rect.bottom
self.yvel = 0
toast.shout('collide TOP')
def update(self, obstacle_sprites):
global toast
key = pygame.key.get_pressed()
self.xvel = 0
if key[pygame.K_a]:
self.xvel =- self.velocity
if key[pygame.K_d]:
self.xvel = self.velocity
if self.on_ground:
if key[pygame.K_SPACE]:
toast.shout('JUMPING')
self.on_ground = False
self.yvel = -20
else:
self.yvel += 1
self.rect.left += self.xvel
self.collide(self.xvel, 0, obstacle_sprites)
self.rect.top += self.yvel
self.on_ground = False
self.collide(0, self.yvel, obstacle_sprites)
self.rect.clamp_ip(pygame.display.get_surface().get_rect())
if self.rect.bottom == pygame.display.get_surface().get_rect().bottom:
self.on_ground = True
class Obstacle(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, color, *grps):
super().__init__(*grps)
self.image = pygame.Surface((width, height))
self.image.fill(color)
self.rect = self.image.get_rect(center=(x, y))
all_sprites = pygame.sprite.Group()
player_sprite = pygame.sprite.Group()
obstacle_sprites = pygame.sprite.Group()
toast = Toast(all_sprites)
hero = Player(0, 570, 30, 30, 5, GREEN, all_sprites, player_sprite)
for x in [
(100, 585, 120, 30),
(300, 535, 120, 30),
(500, 485, 120, 30)
]:
Obstacle(*x, PINK, all_sprites, obstacle_sprites)
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(window_color)
all_sprites.update(obstacle_sprites)
all_sprites.draw(window)
pygame.display.update()
pygame.quit()
This question already has answers here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
How do I detect collision in pygame?
(5 answers)
Closed 2 years ago.
I have been trying to create a 2D platformer in pygame, and I have encountered a problem with the collision of the player sprite with the platform. I hope to implement full collision for the platforms, so that the player sprite will stop when it hits the platform from any direction. Currently, the sprite stops when it hits the top of the platforms, but if it collides with the bottom or sides of a platform it instantly jumps to the top of the platform. I have tried various things to solve this, but to no avail. Any help would be appreciated.
I have seperated my code into 3 files.
This is my main file:
import pygame
from settings import *
from sprites import *
#Game Class
class Game:
def __init__(self):
pygame.init()
pygame.mixer.init()
self.gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
self.clock = pygame.time.Clock()
self.gameRunning = True
#Stars the game
def new(self):
self.allSprites = pygame.sprite.Group()
self.platforms = pygame.sprite.Group()
self.player = Player(self)
self.allSprites.add(self.player)
floor = Platform(0, 680, displayWidth, 40)
plat2 = Platform( 500, 400, 100, 40)
self.allSprites.add(floor, plat2)
self.platforms.add(floor, plat2)
self.run()
#Game Loop
def run(self):
self.gameRunning = True
while self.gameRunning == True:
self.clock.tick(FPS)
self.events()
self.update()
self.draw()
#Updates the screen
def update(self):
self.allSprites.update()
hits = pygame.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.spd.y = 0
self.player.rect.midbottom = self.player.pos
if self.player.rect.left >= displayHeight - 200:
self.player.pos.x -= abs(self.player.spd.x)
for plat in self.platforms:
plat.rect.x -= abs(self.player.spd.x)
if self.player.rect.right <= displayHeight / 4:
self.player.pos.x += abs(self.player.spd.x)
for plat in self.platforms:
plat.rect.x += abs(self.player.spd.x)
#Events loop
def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.player.jump()
#Draws things to the screen
def draw(self):
self.gameDisplay.fill(LIGHT_BLUE)
self.allSprites.draw(self.gameDisplay)
pygame.display.update()
def runGame():
game = Game()
game.new()
runGame()
Sprites file:
import pygame
from settings import *
vec = pygame.math.Vector2
#Player Class
class Player(pygame.sprite.Sprite):
def __init__(self, game):
pygame.sprite.Sprite.__init__(self)
self.game = game
self.image = pygame.Surface([40, 40])
self.image.fill(DARK_BLUE)
self.rect = self.image.get_rect()
self.rect.center = (displayWidth / 2, displayHeight / 2)
self.pos = vec(displayWidth / 2, displayHeight / 2)
self.spd = vec(0,0)
self.acc = vec(0,0)
def update(self):
self.acc = vec(0, playerGrav)
keysPressed = pygame.key.get_pressed()
if keysPressed[pygame.K_LEFT]:
self.acc.x = - playerAcc
if keysPressed[pygame.K_RIGHT]:
self.acc.x = playerAcc
self.acc.x += self.spd.x * playerFric
self.spd += self.acc
self.pos += self.spd + 0.5 * self.acc
self.rect.midbottom = self.pos
def jump(self):
self.rect.y +=1
hits = pygame.sprite.spritecollide(self, self.game.platforms, False)
self.rect.y -= 1
if hits:
self.spd.y = -20
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, w, h):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((w, h))
self.image.fill((GREEN))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
Settings File:
import pygame
pygame.font.init()
#Setup
FPS = 60
displayWidth = 1280
displayHeight = 720
pygame.display.set_caption("2D Platformer")
gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
clock = pygame.time.Clock()
#Player
playerAcc = 0.5
playerFric = -0.1
playerGrav = 0.5
#Colour Pallette
BLACK = (0, 0, 0 )
WHITE = (255, 255, 255)
RED = (200, 0, 0 )
GREEN = (0, 200, 0 )
BLUE = (0, 0, 200)
LIGHT_BLUE = (0, 191, 255)
DARK_BLUE = (0, 50, 150)
#Score
score = 0
This is the code that is responsible for collision:
hits = pygame.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.spd.y = 0
self.player.rect.midbottom = self.player.pos
I understand that the reason why the sprite jumps to the top of the platform is due to these lines of code:
if hits:
self.player.pos.y = hits[0].rect.top
However, I don't know how to implement full collision.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pygame
import sys
class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed
def move(self):
global points, score_text
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > screen.get_width():
self.speed[0] = -self.speed[0]
if self.rect.top <= 0:
self.speed[1] = -self.speed[1]
points += 1
score_text = font.render(str(points), 1, (0, 0, 0))
class MyPaddleClass(pygame.sprite.Sprite):
def __init__(self, location=[0, 0]):
pygame.sprite.Sprite.__init__(self)
image_surface = pygame.surface.Surface([100, 20])
image_surface.fill([0, 0, 0])
self.image = image_surface.convert()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
pygame.init()
screen = pygame.display.set_mode([640, 480])
clock = pygame.time.Clock()
ball_speed = [3, 4]
myball = MyBallClass("E:\\python file\\blackball.jpg", ball_speed, [50, 50])
ballgroup = pygame.sprite.Group(myball)
paddle = MyPaddleClass([270, 400])
lives = 3
points = 0
font = pygame.font.Font(None, 50)
score_text = font.render(str(points), 1, (0, 0, 0))
textpos = [10, 10]
done = False
while 1:
clock.tick(30)
screen.fill([255, 255, 255])
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEMOTION:
paddle.rect.centerx = event.pos[0]
if pygame.sprite.spritecollide(paddle, ballgroup, False):
myball.speed[1] = -myball.speed[1]
myball.move()
if not done:
screen.blit(myball.image, myball.rect)
screen.blit(paddle.image, paddle.rect)
screen.blit(score_text, textpos)
for i in range(lives):
width = screen.get_width()
screen.blit(myball.image, [width - 40 * i, 20])
pygame.display.flip()
if myball.rect.top <= screen.get_rect().bottom:
# In get_rect(), you cannot leave out brackets
lives -= 1
if lives == 0:
final_text1 = "Game over!"
final_text2 = 'your final score is' + str(points)
ft1_font = pygame.font.Font(None, 70)
ft2_font = pygame.font.Font(None, 50)
ft1_surface = font.render(final_text1, 1, (0, 0, 0))
ft2_surface = font.render(final_text2, 1, (0, 0, 0))
screen.blit(ft1_surface, [screen.get_width() / 2, 100])
screen.blit(ft2_surface, [screen.get_width() / 2, 200])
pygame.display.flip()
done = True
else:
pygame.time.delay(1000)
myball.rect.topleft = [50, 50]
frame_rate = clock.get_fps()
print(frame_rate)
Here is the pygame window picture of my code:(http://i.stack.imgur.com/SFyBJ.jpg)
Every time I run it, I don't have the time to control the paddle, then it shows game is over. I have been searching for a long time but can't find out why. It seems like the blackball is moving so fast that the game is over in about one second. But I already set the speed to a reasonable range, I am so confused. Can anyone help?
I could rebuild your game, and fixed the problem.
Try inverse condition here
if myball.rect.top >= screen.get_rect().bottom:
and it works fine: I can hit the ball with the bat, make it bounce, ...
I don't know why it took me so long ot figure it out: you lose the game if ball goes off the screen by the bottom. For that, top y must be greater than the bottom of the window (computer screen coordinates are 0,0 from upper left)