Moving a Sprite in the direction of an angle in Pygame [duplicate] - pygame

This question already has answers here:
How to turn the sprite in pygame while moving with the keys
(1 answer)
Image rotation while moving
(2 answers)
Closed 2 years ago.
Im trying to move a sprite in the direction of an angle in pygame, using the left & right arrow keys to change the direction of the sprite but when I press the up key, the sprite just moves right. I have 2 variables that take speed and a velocity calculation and adds them together (vel_x & vel_y), I then add this to the position (orientation) of the sprite but it isnt following the sprite orientation when it moves forward (if keybd_tupl[K_UP]).
import pygame
import random
import math
from pygame.locals import *
window_wid = 800
window_hgt = 600
frame_rate = 50
delta_time = 1 / frame_rate
STATE_READY = 2
def game_loop_inputs():
# look in the event queue for the quit event
quit_ocrd = False
for evnt in pygame.event.get():
if evnt.type == QUIT:
quit_ocrd = True
return quit_ocrd
def game_loop_update(circle_hitbox):
# start by assuming that no collisions have occurred
circle_hitbox["col"] = False
# return the new state of the rotating line and the circle hitbox
return circle_hitbox
def game_loop_render(circle_hitbox, window_sfc):
# clear the window surface (by filling it with black)
window_sfc.fill( (0,0,0) )
# draw the circle hitbox, in red if there has been a collision or in white otherwise
if circle_hitbox["col"]:
#pygame.draw.circle(window_sfc, (255, 0, 0), circle_hitbox["pos"], circle_hitbox["rad"])
rotated_damage = pygame.transform.rotate(circle_hitbox["damage"], circle_hitbox["angle"])
window_sfc.blit(rotated_damage, circle_hitbox["pos"])
else:
#pygame.draw.circle(window_sfc, (255, 255, 255), circle_hitbox["pos"], circle_hitbox["rad"])
rotated_image = pygame.transform.rotate(circle_hitbox["sprite"], circle_hitbox["angle"])
window_sfc.blit(rotated_image, circle_hitbox["pos"])
# update the display
pygame.display.update()
def main():
# initialize pygame
pygame.init()
# create the window and set the caption of the window
window_sfc = pygame.display.set_mode( (window_wid, window_hgt) )
pygame.display.set_caption('"Toy" for the MDA Exercise')
# create a clock
clock = pygame.time.Clock()
# this is the initial game state
game_state = STATE_READY
#####################################################################################################
# these are the initial game objects that are required (in some form) for the core mechanic provided
#####################################################################################################
# this game object is a circulr
circle_hitbox = {}
circle_hitbox["pos"] = (window_wid // 2, window_hgt // 2)
circle_hitbox["rad"] = 30
circle_hitbox["col"] = False
circle_hitbox["sprite"] = pygame.image.load("cars_racer_{}.png".format(random.randint(1, 3)))
circle_hitbox["damage"] = pygame.image.load("cars_racer_red.png")
circle_hitbox["crash"] = pygame.image.load("explosion.png")
circle_hitbox["damaged"] = False
circle_hitbox["angle"] = 0
speed = 10.0
vel_x = speed * math.cos(circle_hitbox["angle"] * (math.pi / 180))
vel_y = speed * math.sin(circle_hitbox["angle"] * (math.pi / 180))
# the game loop is a postcondition loop controlled using a Boolean flag
closed_flag = False
while not closed_flag:
#####################################################################################################
# this is the "inputs" phase of the game loop, where player input is retrieved and stored
#####################################################################################################
closed_flag = game_loop_inputs()
keybd_tupl = pygame.key.get_pressed()
if keybd_tupl[K_UP]:
circle_hitbox["pos"] = (circle_hitbox["pos"][0] + vel_x, circle_hitbox["pos"][1] + vel_y)
print(vel_y)
if keybd_tupl[K_LEFT]:
circle_hitbox["angle"] = (circle_hitbox["angle"] + 10.0)
if keybd_tupl[K_RIGHT]:
circle_hitbox["angle"] = (circle_hitbox["angle"] - 10.0)
#####################################################################################################
# this is the "update" phase of the game loop, where the changes to the game world are handled
#####################################################################################################
circle_hitbox = game_loop_update(circle_hitbox)
#####################################################################################################
# this is the "render" phase of the game loop, where a representation of the game world is displayed
#####################################################################################################
game_loop_render(circle_hitbox, window_sfc)
# enforce the minimum frame rate
clock.tick(frame_rate)
if __name__ == "__main__":
main()
It just isnt working & I dont know why.

You have to calculate the vel_x and vel_y in the while loop.
while not closed_flag:
closed_flag = game_loop_inputs()
keybd_tupl = pygame.key.get_pressed()
if keybd_tupl[K_UP]:
circle_hitbox["pos"] = (circle_hitbox["pos"][0] + vel_x, circle_hitbox["pos"][1] + vel_y)
print(vel_y)
if keybd_tupl[K_LEFT]:
circle_hitbox["angle"] -= 1.0
if keybd_tupl[K_RIGHT]:
circle_hitbox["angle"] += 1.0
# `math.radians` can be used instead of `* (math.pi / 180)`
vel_x = speed * math.cos(math.radians(circle_hitbox["angle"]))
vel_y = speed * math.sin(math.radians(circle_hitbox["angle"]))
Also, pass the negative angle to pygame.transform.rotate in the game_loop_render function:
rotated_damage = pygame.transform.rotate(circle_hitbox["damage"], -circle_hitbox["angle"])
The rotation probably still doesn't look right (I'm using some replacement images and they don't rotate correctly). Take a look at this answer if you want to know how to rotate pygame sprites and images around their center in pygame.

Related

Pygame square not showing up because of sprites [duplicate]

This question already has answers here:
Pygame Drawing a Rectangle
(6 answers)
Closed 5 months ago.
I try to print a square for use as a hitbox because the collision detection doesn't work on images. But when I try to draw a test square in setup it doesn't appear. I have tried moving the command, and changing it but nothing worked. And that is only for the square. The images appear and move perfectly. I am pretty sure it has something to do with the sprites because without them everything works perfectly.
import pygame
import sys
pygame.init()
fps = 30
fpsclock=pygame.time.Clock()
window = pygame.display.set_mode((600, 600))
x = 275
y = 375
BulletX = x + 10
BulletY = y - 15
color = (250,210,240)
ship_img = pygame.image.load('spaceship.png')
ship = pygame.transform.scale(ship_img,(32,32))
bullet_img = pygame.image.load('bullet (2).png')
bullet = pygame.transform.scale(bullet_img,(12,12))
# main application loop
run = True
while run:
# limit frames per second
fpsclock.tick(fps)
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
key_input = pygame.key.get_pressed() #key inputs
if key_input[pygame.K_LEFT]:
x -= 5
if key_input[pygame.K_RIGHT]:
x += 5
# clear the display
window.fill(0)
window.blit(ship,(x,y))
pygame.draw.rect(window,color,pygame.rect(200,200,30,30))
window.blit(bullet,(BulletX,BulletY))
BulletY = BulletY - 20
if(BulletY <= -10):
BulletY = y - 10
BulletX = x + 10
# update the display
pygame.display.flip()
pygame.quit()
exit()
The only problem with your code is a lowercase 'r' instead of of uppercase one. Change the appropriate line to:
pygame.draw.rect(window, color, pygame.Rect(200,200,30,30) )
and have fun implementing the collision.

How to get tile selected with mouse?

New to pygame, and game development in general.
This is my main loop and I am trying to blit just a tile selector image on top of the current tile that the mouse is pointing to by using collisionpoint detection. However, as seen in the picture, it partially select everything around the tile I am pointing at. Attached pics are examples of what happens and the selector tile I am using. I am not sure how to adjust the mouse coordinates appropriately and would love advice on what to do with it.
image_list[3] points to the image class that contains details about the selector tile.
def loop(display, screen, image_list, map_data):
# initialise conditions used in loop
display_mouse_coords = False
player_in_grasslands = True
font = pygame.font.Font(pygame.font.get_default_font(), 13)
while True:
display.fill(constants.COLOURS["BLACK"])
# display map
for y, row in enumerate(map_data):
for x, tile in enumerate(row):
if tile != 0:
tile_rect = display.blit(image_list[tile - 1].img_surf, (150 + x * 10 - y * 10, 100 + x * 5 + y * 5))
pos = pygame.mouse.get_pos()
# take the mouse position and scale it, too
screen_rect = screen.get_rect()
display_rect = display.get_rect()
ratio_x = (screen_rect.width / display_rect.width)
ratio_y = (screen_rect.height / display_rect.height)
scaled_pos = (pos[0] / ratio_x, pos[1] / ratio_y)
if tile_rect.collidepoint(scaled_pos):
display.blit(image_list[3].img_surf, tile_rect)
Here are the textures that I used for this example (respectively cursor.png, right.png, top.png, left.png:
You can use the code below for a working example of pygame.mask:
import pygame
from pygame.locals import *
class Map:
def __init__(self, width, height, origin):
self.top_image = pygame.image.load('top.png')
self.left_image = pygame.image.load('left.png')
self.right_image = pygame.image.load('right.png')
self.cursor = pygame.image.load('cursor.png')
# create the Mask for the top image
# (only activate when the selected pixel is non-transparent)
self.top_image_mask = pygame.mask.from_surface(self.top_image)
origin[0] -= 20*width
origin[1] += 5*height
self.map = []
for x in range(width):
for y in range(height):
tile_x, tile_y = origin
tile_x += 20*x + 20*y
tile_y += 10*y - 10*x
self.map.append(Tile(tile_x, tile_y))
# draw the sides textures if needed
if not x:
self.map[-1].left = True
if y+1 == height:
self.map[-1].right = True
def update(self):
for tile in self.map:
tile.update()
def draw(self):
for tile in sorted(self.map, key=lambda tile: tile.selected):
tile.draw()
class Tile:
def __init__(self, x, y):
self.x = x
self.y = y
# make rect to check for rough collision
self.rect = pygame.Rect(x, y, 40, 48)
self.left = False
self.right = False
self.selected = False
def update(self):
self.selected = False
x, y = pygame.mouse.get_pos()
if self.rect.collidepoint((x, y)):
# the mask needs relative coordinates
x -= self.rect.x
y -= self.rect.y
if map.top_image_mask.get_at((x, y)):
self.selected = True
def draw(self):
pos = self.rect.x, self.rect.y
screen.blit(map.top_image, pos)
if self.left:
screen.blit(map.left_image, pos)
if self.right:
screen.blit(map.right_image, pos)
if self.selected:
screen.blit(map.cursor, pos)
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
map = Map(15, 15, [320, 100])
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
screen.fill((230, 250, 255))
map.update()
map.draw()
pygame.display.flip()
clock.tick(60) # limit the framerate
Screenshot of the example:
It namely uses classes to store the tiles, which are generated by Map.__init__ according to an original position, a width and height values. The code in Map.__init__ determines the position of each tile, stored as a Tile object. They sometimes get the order to draw the left or right textures, to make the map look more 3D-ish.
But the most important part is the use of the Map.top_image_mask variable. This is a mask created from the Map.top_image Surface. Its get_at function is used, which returns True if the relative point in the mask is opaque, or False if not. For example, with this image, mask.get_at((0, 0)) will return False, because the pixel on the very top left of the image is transparent, but it will return True if you ask for mask.get_at((20, 10)) for example.
I make sure to check for a pygame.Rect collision before checking the mask, because calling mask.get_at with a point outside of the texture will return an error. The first step is then to check if the absolute mouse position collides with the rect of the texture of a specific tile, then if it "touches" it, check if the touched pixel is not transparent by the use of relative mouse coordinates and the mask.get_at function.
I hope that helps.

Trying to display an image and move it on a timer, but only while the camera the image is on [duplicate]

I've been searching for some good tutorial about making simple sprite animation from few images in Python using Pygame. I still haven't found what I'm looking for.
My question is simple: how to make an animated sprite from few images (for an example: making few images of explosion with dimensions 20x20px to be as one but animated)
Any good ideas?
There are two types of animation: frame-dependent and time-dependent. Both work in similar fashion.
Before the main loop
Load all images into a list.
Create three variable:
index, that keeps track on the current index of the image list.
current_time or current_frame that keeps track on the current time or current frame since last the index switched.
animation_time or animation_frames that define how many seconds or frames should pass before switching image.
During the main loop
Increment current_time by the amount of seconds that has passed since we last incremented it, or increment current_frame by 1.
Check if current_time >= animation_time or current_frame >= animation_frame. If true continue with 3-5.
Reset the current_time = 0 or current_frame = 0.
Increment the index, unless if it'll be equal or greater than the amount of images. In that case, reset index = 0.
Change the sprite's image accordingly.
A full working example
import os
import pygame
pygame.init()
SIZE = WIDTH, HEIGHT = 720, 480
BACKGROUND_COLOR = pygame.Color('black')
FPS = 60
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
def load_images(path):
"""
Loads all images in directory. The directory must only contain images.
Args:
path: The relative or absolute path to the directory to load images from.
Returns:
List of images.
"""
images = []
for file_name in os.listdir(path):
image = pygame.image.load(path + os.sep + file_name).convert()
images.append(image)
return images
class AnimatedSprite(pygame.sprite.Sprite):
def __init__(self, position, images):
"""
Animated sprite object.
Args:
position: x, y coordinate on the screen to place the AnimatedSprite.
images: Images to use in the animation.
"""
super(AnimatedSprite, self).__init__()
size = (32, 32) # This should match the size of the images.
self.rect = pygame.Rect(position, size)
self.images = images
self.images_right = images
self.images_left = [pygame.transform.flip(image, True, False) for image in images] # Flipping every image.
self.index = 0
self.image = images[self.index] # 'image' is the current image of the animation.
self.velocity = pygame.math.Vector2(0, 0)
self.animation_time = 0.1
self.current_time = 0
self.animation_frames = 6
self.current_frame = 0
def update_time_dependent(self, dt):
"""
Updates the image of Sprite approximately every 0.1 second.
Args:
dt: Time elapsed between each frame.
"""
if self.velocity.x > 0: # Use the right images if sprite is moving right.
self.images = self.images_right
elif self.velocity.x < 0:
self.images = self.images_left
self.current_time += dt
if self.current_time >= self.animation_time:
self.current_time = 0
self.index = (self.index + 1) % len(self.images)
self.image = self.images[self.index]
self.rect.move_ip(*self.velocity)
def update_frame_dependent(self):
"""
Updates the image of Sprite every 6 frame (approximately every 0.1 second if frame rate is 60).
"""
if self.velocity.x > 0: # Use the right images if sprite is moving right.
self.images = self.images_right
elif self.velocity.x < 0:
self.images = self.images_left
self.current_frame += 1
if self.current_frame >= self.animation_frames:
self.current_frame = 0
self.index = (self.index + 1) % len(self.images)
self.image = self.images[self.index]
self.rect.move_ip(*self.velocity)
def update(self, dt):
"""This is the method that's being called when 'all_sprites.update(dt)' is called."""
# Switch between the two update methods by commenting/uncommenting.
self.update_time_dependent(dt)
# self.update_frame_dependent()
def main():
images = load_images(path='temp') # Make sure to provide the relative or full path to the images directory.
player = AnimatedSprite(position=(100, 100), images=images)
all_sprites = pygame.sprite.Group(player) # Creates a sprite group and adds 'player' to it.
running = True
while running:
dt = clock.tick(FPS) / 1000 # Amount of seconds between each loop.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.velocity.x = 4
elif event.key == pygame.K_LEFT:
player.velocity.x = -4
elif event.key == pygame.K_DOWN:
player.velocity.y = 4
elif event.key == pygame.K_UP:
player.velocity.y = -4
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
player.velocity.x = 0
elif event.key == pygame.K_DOWN or event.key == pygame.K_UP:
player.velocity.y = 0
all_sprites.update(dt) # Calls the 'update' method on all sprites in the list (currently just the player).
screen.fill(BACKGROUND_COLOR)
all_sprites.draw(screen)
pygame.display.update()
if __name__ == '__main__':
main()
When to chose which
Time-dependent animation allows you to play the animation at the same speed, no matter how slow/fast the frame-rate is or slow/fast your computer is. This allows your program to freely change the framerate without affecting the animation and it'll also be consistent even if the computer cannot keep up with the framerate. If the program lags the animation will catch up to the state it should've been as if no lag had happened.
Although, it might happen that the animation cycle don't synch up with the framerate, making the animation cycle seem irregular. For example, say that we have the frames updating every 0.05 second and the animation switch image every 0.075 second, then the cycle would be:
Frame 1; 0.00 seconds; image 1
Frame 2; 0.05 seconds; image 1
Frame 3; 0.10 seconds; image 2
Frame 4; 0.15 seconds; image 1
Frame 5; 0.20 seconds; image 1
Frame 6; 0.25 seconds; image 2
And so on...
Frame-dependent can look smoother if your computer can handle the framerate consistently. If lag happens it'll pause in its current state and restart when the lag stops, which makes the lag more noticeable. This alternative is slightly easier to implement since you just need to increment current_frame with 1 on each call, instead of dealing with the delta time (dt) and passing it to every object.
Sprites
Result
You could try modifying your sprite so that it swaps out its image for a different one inside update. That way, when the sprite is rendered, it'll look animated.
Edit:
Here's a quick example I drew up:
import pygame
import sys
def load_image(name):
image = pygame.image.load(name)
return image
class TestSprite(pygame.sprite.Sprite):
def __init__(self):
super(TestSprite, self).__init__()
self.images = []
self.images.append(load_image('image1.png'))
self.images.append(load_image('image2.png'))
# assuming both images are 64x64 pixels
self.index = 0
self.image = self.images[self.index]
self.rect = pygame.Rect(5, 5, 64, 64)
def update(self):
'''This method iterates through the elements inside self.images and
displays the next one each tick. For a slower animation, you may want to
consider using a timer of some sort so it updates slower.'''
self.index += 1
if self.index >= len(self.images):
self.index = 0
self.image = self.images[self.index]
def main():
pygame.init()
screen = pygame.display.set_mode((250, 250))
my_sprite = TestSprite()
my_group = pygame.sprite.Group(my_sprite)
while True:
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
# Calling the 'my_group.update' function calls the 'update' function of all
# its member sprites. Calling the 'my_group.draw' function uses the 'image'
# and 'rect' attributes of its member sprites to draw the sprite.
my_group.update()
my_group.draw(screen)
pygame.display.flip()
if __name__ == '__main__':
main()
It assumes that you have two images called image1.png and image2.png inside the same folder the code is in.
You should have all your sprite animations on one big "canvas", so for 3 20x20 explosion sprite frames you will have 60x20 image. Now you can get right frames by loading an area of the image.
Inside your sprite class, most likely in update method you should have something like this (hardcoded for simplicity, I prefer to have separate class to be responsible for picking the right animation frame). self.f = 0 on __init__.
def update(self):
images = [[0, 0], [20, 0], [40, 0]]
self.f += 1 if self.f < len(images) else 0
self.image = your_function_to_get_image_by_coordinates(images[i])
For an animated Sprite a list of images (pygame.Surface objects) must be generated. A different picture of the list is displayed in each frame, just like in the pictures of a movie. This gives the appearance of an animated object.
One way to get a list of images is to load an animated GIF (Graphics Interchange Format). Unfortunately, PyGame doesn't offer a function to load the frames of an animated GIF. However, there are several Stack Overflow answers that address this issue:
How can I load an animated GIF and get all of the individual frames in PyGame?
How do I make a sprite as a gif in pygame?
Pygame and Numpy Animations
One way is to use the popular Pillow library (pip install Pillow). The following function loads the frames of an animated GIF and generates a list of pygame.Surface objects:
from PIL import Image, ImageSequence
def loadGIF(filename):
pilImage = Image.open(filename)
frames = []
for frame in ImageSequence.Iterator(pilImage):
frame = frame.convert('RGBA')
pygameImage = pygame.image.fromstring(
frame.tobytes(), frame.size, frame.mode).convert_alpha()
frames.append(pygameImage)
return frames
Create a pygame.sprite.Sprite class that maintains a list of images. Implement an update method that selects a different image in each frame.
Pass the list of images to the class constructor. Add an index attribute that indicates the index of the current image in the list. Increase the index in the Update method. Reset the index if it is greater than or equal to the length of the image list (or use the modulo (%) operator). Get the current image from the list by subscription:
class AnimatedSpriteObject(pygame.sprite.Sprite):
def __init__(self, x, bottom, images):
pygame.sprite.Sprite.__init__(self)
self.images = images
self.image = self.images[0]
self.rect = self.image.get_rect(midbottom = (x, bottom))
self.image_index = 0
def update(self):
self.image_index += 1
if self.image_index >= len(self.images):
self.image_index = 0
self.image = self.images[self.image_index]
See also Load animated GIF and Sprite
Example GIF (from Animated Gifs, Animated Image):
Minimal example: repl.it/#Rabbid76/PyGame-SpriteAnimation
import pygame
from PIL import Image, ImageSequence
def loadGIF(filename):
pilImage = Image.open(filename)
frames = []
for frame in ImageSequence.Iterator(pilImage):
frame = frame.convert('RGBA')
pygameImage = pygame.image.fromstring(
frame.tobytes(), frame.size, frame.mode).convert_alpha()
frames.append(pygameImage)
return frames
class AnimatedSpriteObject(pygame.sprite.Sprite):
def __init__(self, x, bottom, images):
pygame.sprite.Sprite.__init__(self)
self.images = images
self.image = self.images[0]
self.rect = self.image.get_rect(midbottom = (x, bottom))
self.image_index = 0
def update(self):
self.image_index += 1
self.image = self.images[self.image_index % len(self.images)]
self.rect.x -= 5
if self.rect.right < 0:
self.rect.left = pygame.display.get_surface().get_width()
pygame.init()
window = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()
ground = window.get_height() * 3 // 4
gifFrameList = loadGIF('stone_age.gif')
animated_sprite = AnimatedSpriteObject(window.get_width() // 2, ground, gifFrameList)
all_sprites = pygame.sprite.Group(animated_sprite)
run = True
while run:
clock.tick(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
all_sprites.update()
window.fill((127, 192, 255), (0, 0, window.get_width(), ground))
window.fill((255, 127, 64), (0, ground, window.get_width(), window.get_height() - ground))
all_sprites.draw(window)
pygame.display.flip()
pygame.quit()
exit()

pygame Pong - how to attribute my scoring system and collision detection

Hey I'm working on pong and regardless of how hard I try, I keep facing the same problem; the scoring system doesn't appear on the window when I run the code.
I was told I need to initialize attributes such as scoring system, ball and paddles and I guess I did so for the ball and paddle even though I don't really get what that means since this course is the farthest thing from being kind to students who are new to python. But I guess I didn't do so for the scoring system since it's not appearing on the screen.
I've been struggling with these past few weeks and still haven't found a way to fix this and I need to hand in this next week which is making me freak out.
I would appreciate it if you can explain me what did I do wrong and what initializing attribute means and also check my codes for collision detection!
Thank you all SO MUCH!! (By the way, this always happens and confuses me a lot since I get no error message but the scoring system is just not working as I expected)
# Pong V2
# Pong game needs two players and players try to prevent the ball from hitting
# the edge of the screen of their side. If the ball hits the edge of the window,
# the counterpart of the player who couldn't defence the wall gains a point.
# When one of the players reach 11 points, game ends and the player with higher
# points win the game. Players and move the paddles of their own by pressing
# some keys and ball bounces off when the ball has hit the front part of the
# paddle but passes through when they hit the back part of the paddle.
# wall, game continuing until the player presses 'x' button to close the window,
# paddles on the screen but cannot be moved.
# Version 2 of Pong implies the scoring system and game ending when someone hits
# 11 scores. Also, now collision detection for the paddles and the ball has been
# added as a new feature even though still player cannot move the paddles.
import pygame
from random import randint
def main():
# initialize all pygame modules (some need initialization)
pygame.init()
# create a pygame display window
pygame.display.set_mode((500, 400))
# set the title of the display window
pygame.display.set_caption('Pong')
# get the display surface
w_surface = pygame.display.get_surface()
# create a game object
game = Game(w_surface)
# start the main game loop by calling the play method on the game object
game.play()
# quit pygame and clean up the pygame window
pygame.quit()
class Game:
def __init__(self, surface):
# Initialize a Game.
self.surface = surface
self.bg_color = pygame.Color('black')
self.FPS = 60
self.game_Clock = pygame.time.Clock()
self.close_clicked = False
self.continue_game = True
#iniotialize the ball
self.ball = Ball('white', 5, [250, 200], [1, 2], self.surface)
self.max_frames = 150
self.frame_counter = 0
# initialize paddles
self.paddleA = pygame.Rect((70, 170), (10, 60))
self.paddleB = pygame.Rect((415, 170), (10, 60))
# initialize paddles
self.scoreA = 0
self.scoreB = 0
def draw_score_A(self):
# this method draws the player's score in the top-left corner of the
# game window.
strscoreA = str(self.scoreA)
font_color = pygame.Color('white')
font_bg = pygame.Color('black')
font = pygame.font.SysFont("arial", 72)
text_img = font.render(strscoreA, True, font_color, font_bg)
text_pos = (0, 0)
self.surface.blit(text_img, text_pos)
def draw_score_B(self):
# this method draws the player's score in the top-right corner of the
# game window.
strscoreB = str(self.scoreB)
font_color = pygame.Color('white')
font_bg = pygame.Color('black')
font = pygame.font.SysFont("arial", 72)
text_img = font.render(strscoreB, True, font_color, font_bg)
text_pos = (425,0)
self.surface.blit(text_img, text_pos)
def update_score(self):
# check if the ball has hit the left or right side edge and update score
# if the ball hit left side, scoreB goes up by 1 and if the ball hit the right
# side the scoreA goes up by 1.
if self.ball.center[0] < self.ball.radius:
self.scoreB += 1
if self.ball.center[0] + self.ball.radius > self.surface.get_width():
self.scoreA += 1
return self.scoreA, self.scoreB
def play(self):
# Play the game until the player presses the close box.
# - self is the Game that should be continued or not.
while not self.close_clicked: # until player clicks close box
# play frame
self.handle_events()
self.draw()
self.update_score()
self.draw_score_A()
self.draw_score_B()
if self.continue_game:
self.update()
self.decide_continue()
self.game_Clock.tick(self.FPS) # run at most with FPS Frames Per Second
def handle_events(self):
# Handle each user event by changing the game state appropriately.
# - self is the Game whose events will be handled
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
self.close_clicked = True
def draw(self):
# Draw all game objects.
self.surface.fill(self.bg_color) # clear the display surface first
# draw ball on the surface
self.ball.draw()
# draw both paddles on the surface
paddleA = pygame.Rect((70, 170), (10, 60))
self.paddleA = pygame.draw.rect(self.surface, (255, 255, 255), paddleA)
paddleB = pygame.Rect((415, 170), (10, 60))
self.paddleB = pygame.draw.rect(self.surface, (255, 255, 255), paddleB)
pygame.display.update() # make the updated surface appear on the display
def collision_detection(self):
# figure out if the paddle and the ball has collide or not.
# If the ball has hit the front of the paddle, it is recognizes as
# a collision and bounces off to the opposite direction. However
# if the ball has hit the backside of the paddle, this is not
# considered as a collision and this will not make the ball bounce of but
# go through the paddle.We need to check if the center of the ball has passed
# the center of the paddle or not and for this we will use rect.collidepoint
if self.paddleA.collidepoint(self.center) and self.velocity[index] > 0 is True:
self.velocity[index] = self.velocity[index]
elif self.paddleA.collidepoint(self.center) and self.velocity[index] < 0 is True:
self.velocity[index] = - self.velocity[index]
elif self.paddleB.collidepoint(self.center) and self.velocity[index] > 0 is True:
self.velocity[index] = - self.velocity[index]
elif self.paddleB.collidepoint(self.center) and self.velocity[index] < 0 is True:
self.velocity[index] = self.velocity[index]
def update(self):
# Update the game objects for the next frame.
self.ball.move()
self.frame_counter += self.frame_counter
def decide_continue(self):
# Check and remember if the game should continue
# if the score of one of the players reaches 11, the game should end.
# thus we need to check if anyone's score has reached 11 or not and
# decide if we'll continue the game or not.
if self.scoreA == 11 or self.scoreB == 11 :
self.continue_game = False
class Ball:
# An object in this class represents a ball that moves
def __init__(self, ball_color, ball_radius, ball_center, ball_velocity,
surface):
# Initialize a ball.
# - self is the ball to initialize
# - color is the pygame.Color of the ball
# - center is a list containing the x and y int
# coords of the center of the dot
# - radius is the int pixel radius of the ball
# - velocity is a list containing the x and y components
# - surface is the window's pygame.Surface object
self.color = pygame.Color(ball_color)
self.radius = ball_radius
self.center = ball_center
self.velocity = ball_velocity
self.surface = surface
def move(self):
# Change the location of the ball by adding the corresponding
# speed values to the x and y coordinate of its center
# we need the height and width of the screen to determine when ball
# should change their direction of motion (bounce)
screen_width = self.surface.get_width()
screen_height = self.surface.get_height()
# updates the ball's position based on its velocity and also bounces the
# ball off a wall if it gets too close
screen_size = (screen_width, screen_height)
for index in range(0, len(self.center)):
self.center[index] += self.velocity[index]
if (self.center[index] <= 0 + self.radius or self.center[index] >=
screen_size[index] - self.radius):
self.velocity[index] = -self.velocity[index]
def draw(self):
# Draw the ball on the surface
pygame.draw.circle(self.surface, self.color, self.center, self.radius)
main()
The code is calling draw() (to repaint and flush the screen), and then calling draw_score_A() and draw_score_B() without flushing. So the changes made by the draw_score_ functions are never seen by the user.
If you have a function draw() - make it draw everything. This keeps all the drawing and flushing operations in a single place. Sure the draw() function calls other functions to do the painting, but it's all starts from one place.
def draw( self ):
# Draw all game objects.
# clear the display surface first
self.surface.fill( self.bg_color )
# draw ball on the surface
self.ball.draw()
# draw both paddles on the surface
pygame.draw.rect( self.surface, ( 255, 255, 255 ), self.paddleA )
pygame.draw.rect( self.surface, ( 255, 255, 255 ), self.paddleB )
# Paint the scores
self.draw_score_A()
self.draw_score_B()
# make the updated surface appear on the display
pygame.display.update()
Also, your draw() function seems to be re-defining paddleA and paddleB as part of the drawing. I corrected this in the version above.

Pygame breaking code, creating a wall of bricks [duplicate]

This question already has answers here:
How do I detect collision in pygame?
(5 answers)
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
Closed 2 years ago.
This is my first time using pygame and I apologize for possible misunderstandings and 'silly' questions. I am developing a breaking game, consisting of a ball ,a paddle and a wall of bricks. So far I ve the ball, and that s fine. I am trying to implement my code in order to get the wall, but I am missing something and it doesn t show up on the screen when I run it. Could anyone help me? The bricks are 50x60, 3 rows. Thank you in advance. (If anyone would also recommend something about creating the paddle and making the ball stick to it, that would be highly appreciated.)
Here is my code so far:
""""BREAKING GAME"""
#Import and initialize pygame
import pygame as pg
pg.init()
#Set the colour of the background and store the ball data
backgroundcolour = (50,50,50)
randomcolour=(205,55,0)
ballimg = pg.image.load("ball.gif")
ballimage = ballimg.get_rect()
#Set the frame
xmax = 800
ymax = 800
screen = pg.display.set_mode((xmax,ymax))
#Starting values
horizontalposition = 400. #pixels (unit f length of computer)
verticalposition = 400. #pixels
v_x = 400. #pixels
v_y = 300. #pixels
#Set the clock of the computer
t0 = float(pg.time.get_ticks())/1000.
# Create wall of bricks
position_Bricks_x=[0,50,100,150,200,250,300,350,400,450,500,550,600,650,700,750]
position_Bricks_y = [16,32,48]
i = 0
j = 0
#Infinite loop
running = True
while running:
t = float(pg.time.get_ticks())/1000.
dt = min(t-t0, 0.1)
t0 = t
# Motion of the ball
horizontalposition = horizontalposition+v_x*dt
verticalposition = verticalposition+v_y*dt
#Bounce the ball on the edges of the screen
if horizontalposition > xmax:
v_x=-abs(v_x)
elif horizontalposition < 0:
v_x= abs(v_x)
if verticalposition > ymax:
v_y = -abs(v_y)
elif verticalposition<0:
v_y = abs(v_y)
# Draw the frame
screen.fill(backgroundcolour)
ballimage.centerx = int(horizontalposition)
ballimage.centery = int(verticalposition)
screen.blit(ballimg,ballimage)
while i < len(position_Bricks_x):
if j < len(position_Bricks_y):
pg.draw.rect(screen,randomcolour,[position_Bricks_x[i],position_Bricks_y[j],50,16])
j = j + 1
else:
j=0
i=i+1
pg.display.update()
pg.display.flip()
# Event handling
pg.event.pump()
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
Quit pygame
pg.quit()
print "Ready"