pygame sprites move in constant line - python

I'm trying (badly) to write a very succinct program in pygame like Pong, but I seem to be stuck trying to move my paddles vertically. Moreover, while they do move... they only move in constant line.
Example Image
#python code
import pygame, sys
#Screen Width/Height
screen = pygame.display.set_mode((800,600))
#Background Image
background_image = pygame.image.load("tennis.jpg").convert()
screen.blit(background_image, [0,0])
#Frame Rate
clock = pygame.time.Clock()
#Paddles
paddle_player1 = pygame.Rect(5,50,5,60)
paddle_player2 = pygame.Rect(790,50,5,60)
#Process Player Input
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
player1_up = pygame.key.get_pressed()[pygame.K_w]
player1_down = pygame.key.get_pressed()[pygame.K_s]
player2_up = pygame.key.get_pressed()[pygame.K_UP]
player2_down = pygame.key.get_pressed()[pygame.K_DOWN]
#Updating Game State Logic
if player1_up:
paddle_player1.y += -50
if player1_down:
paddle_player1.y += 50
if player2_up:
paddle_player2.y += -50
if player2_down:
paddle_player2.y += 50
if paddle_player1.y < 0:
paddle_player1.y = 0
if paddle_player2.y < 0:
paddle_player2.y = 0
if paddle_player1.y > screen.get_height() - paddle_player1.height:
paddle_player1.y = screen.get_height() - paddle_player1.height
if paddle_player2.y > screen.get_height() - paddle_player2.height:
paddle_player2.y = screen.get_height() - paddle_player2.height
#Rendering
pygame.draw.rect(screen,(0,0,0), paddle_player1)
pygame.draw.rect(screen,(0,0,0), paddle_player2)
clock.tick(50)
pygame.display.flip()

You need to call you blit inside your game loop, like so:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
player1_up = pygame.key.get_pressed()[pygame.K_w]
player1_down = pygame.key.get_pressed()[pygame.K_s]
player2_up = pygame.key.get_pressed()[pygame.K_UP]
player2_down = pygame.key.get_pressed()[pygame.K_DOWN]
#Updating Game State Logic
if player1_up:
paddle_player1.y += -50
if player1_down:
paddle_player1.y += 50
if player2_up:
paddle_player2.y += -50
if player2_down:
paddle_player2.y += 50
if paddle_player1.y < 0:
paddle_player1.y = 0
if paddle_player2.y < 0:
paddle_player2.y = 0
if paddle_player1.y > screen.get_height() - paddle_player1.height:
paddle_player1.y = screen.get_height() - paddle_player1.height
if paddle_player2.y > screen.get_height() - paddle_player2.height:
paddle_player2.y = screen.get_height() - paddle_player2.height
screen.blit(background_image, [0,0]) #move your blit here
pygame.draw.rect(screen,(0,0,0), paddle_player1)
pygame.draw.rect(screen,(0,0,0), paddle_player2)

Related

How would I make the ball move faster? [duplicate]

This question already has an answer here:
Sometimes the ball doesn't bounce off the paddle in pong game
(1 answer)
Closed 2 years ago.
I am recreating a basic pong game.. and I am unable to figure out how to make the ball more faster. I have tried modifying speed but that was unsuccessful. Also, when the ball hits the paddle it goes through the paddle instead of bouncing back. I am trying to use collision to allow the ball to bounce back.
# import the necessary modules
import pygame
import sys
#initialize pygame
pygame.init()
screenSize=(700,500)
screen=pygame.display.set_mode((screenSize), 0)
# set the size for the surface (screen)
screen_h = screen.get_height()
screen_w = screen.get_width()
screen = pygame.display.set_mode((screen_w,screen_h),0)
# set the caption for the screen
pygame.display.set_caption("Pong Game")
# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)
playerRect = pygame.Rect(100,100,50,50)
playerRect2 = pygame.Rect(300,300,50,50)
#initialize variables for player
#variables for first rectangle
R1x = 740
R1y = 300
R1w = 30
R1h = 132
R1dx = 0
R1dy = 0
#variables for second rectangle
R2x = 10
R2y = 300
R2w = 30
R2h = 132
R2dx = 0
R2dy = 0
#ball variables
bx = 100
by = 150
dby = 1
dbx = 1
br = 15
cy = screen.get_height()/2
cx = screen.get_width()/2
#speed
speed = 5
fontsize = 50
fontTitle = pygame.font.SysFont('arial',fontsize)
textTitle = fontTitle.render("Left paddle score ="+str(R1x),True, (YELLOW))
clock = pygame.time.Clock()
FPS = 300
# set main loop to True so it will run
main = True
# main loop
while main:
for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
main = False # set the "main" variable to False to exit while loop
if event.type ==pygame.KEYDOWN:
if event.key == pygame.K_UP:
R1dx = 0
R1dy = -speed
elif event.key == pygame.K_DOWN:
R1dx = 0
R1dy = speed
if event.key == pygame.K_w:
R2dx = 0
R2dy = -speed
elif event.key == pygame.K_s:
R2dx = 0
R2dy = speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
R1dx = 0
R1dy = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
R2dx = 0
R2dy = 0
clock.tick(FPS)
R1x = R1dx + R1x
R2x = R2dx + R2x
bx = dbx + bx
by = dby + by
if R1x >= screen.get_height() - 80 or R1x < 0:
R1dx = 0
if R2x >= screen.get_height() - 80 or R2x < 0:
R2dx = 0
if by >= screen.get_height() - br:
dby = -1
if by <= 15:
dby = 1
if bx >= R2x - br and by - R2x > 0 and by - R2x < 100:
dbx = -1
if bx <= R1x + br and by - R1x > 0 and by - R1x < 100:
dbx = 1
if bx == 1:
R2xscore = R1xscore + 1
pause = True
if bx == 799:
left_paddlescore = left_paddlescore + 1
pause = True
# check collision
collided = playerRect.colliderect(playerRect2)
if collided == True:
playerRect.x = oldX
playerRect.y = oldY
# move the x and y positions of the rectangles
R1y = max(0, min(screen_h-R1h, R1y + R1dy))
R2y = max(0, min(screen_h-R2h, R2y + R2dy))
R1x = max(0, min(screen_w-R1w, R1x + R1dx))
R2x = max(0, min(screen_w-R2w, R2x + R2dx))
screen.fill(BLACK)
playerRect.move_ip(R1dx,R1dy)
playerRect2.move_ip(R2dx,R2dy)
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)
pygame.draw.circle(screen, RED,(bx,by),br,0)
# we are using .flip() here, it basically works the same as .update()
# we will discuss this more in class (you can use either one)
pygame.display.flip()
# quit pygame and exit the program (i.e. close everything down)
pygame.quit()
sys.exit()
The movement of the ball has to be computed in the application loop, rather than the event loop. Use pygame.Rect obejcts for the paddles and the ball. Detect a collision between the ball and the paddles by colliderect(). If the ball hits the right paddle, then the right border of the ball has to be set by the left border of the paddle. If the ball hits the left paddle, then the left border of the ball has to be set by the right border of the paddle. e.g.:
while main:
for event in pygame.event.get():
if event.type == pygame.QUIT:
main = False
# [...]
clock.tick(FPS)
R1x = R1dx + R1x
R2x = R2dx + R2x
bx = bx + dbx * speed
by = by + dby * speed
# move the x and y positions of the rectangles
R1y = max(0, min(screen_h-R1h, R1y + R1dy))
R2y = max(0, min(screen_h-R2h, R2y + R2dy))
R1x = max(0, min(screen_w-R1w, R1x + R1dx))
R2x = max(0, min(screen_w-R2w, R2x + R2dx))
playerRect = pygame.Rect(R1x, R1y, R1w, R1h)
playerRect2 = pygame.Rect(R2x, R2y, R2w, R2h)
ballRect = pygame.Rect(bx-br, by-br, br*2, br*2)
if ballRect.top <= 0:
dby = abs(dby)
if ballRect.bottom >= screen.get_height():
dby = -abs(dby)
if ballRect.colliderect(playerRect2):
ballRect.left = playerRect2.right
dbx = abs(dbx)
if ballRect.colliderect(playerRect):
ballRect.right = playerRect.left
dbx = -abs(dbx)
bx, by = ballRect.center
screen.fill(BLACK)
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE, playerRect)
pygame.draw.rect(screen, WHITE, playerRect2)
pygame.draw.circle(screen, RED, ballRect.center, br)
# we are using .flip() here, it basically works the same as .update()
# we will discuss this more in class (you can use either one)
pygame.display.flip()

Trying to control the speed of my loop for Pong

I'm trying to get my pong game to run the loop at a certain fps, but I've tried a couple things and it hasn't worked and I wasn't taught how to use pygame speed/clock so I gotta figure it out on my own
I'm trying to make the loop run at a certain speed to make it look smoother, because if I edit the dx or the position it goes to when you change it, it looks chunky, so instead of a paddle 10 x down (looks chunky) i want to move it 1 x down a bunch of times so it moves down just as fast as 10 x but smoother
Full Code
import pygame #how to fix paddle widths from hitting ball
import sys
pygame.init()
screenSize = (800,600)
screen = pygame.display.set_mode((screenSize),0)
pygame.display.set_caption("HajarPongBasicCollision")
# colours
WHITE = (255,255,255)
BLACK = (0, 0, 0)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
PURPLE = (154, 136, 180)
screen.fill(BLACK)
pygame.display.update()
# retrieve screen measurements
screenw = screen.get_width()
screenh = screen.get_height()
# retrieve position of center of screen
centerx= 400 #tried not to use hard coded values but program gives me an error when i use screenw/2 ASK MR H TO HELP WITH NO HARD CODED VALUES (HCV)
centery= 300
# variables for first paddle
p1x = 10
p1y = 10
p1w = 10
p1h = 100
p1dy = 0
p1_score = 0
# variables for second paddle
p2w = 10
p2h = 100
p2x = screenw - 20
p2y = 10
p2dy = 0
p2_score = 0
# variable for ball
bx = 400 #HCV
by = 300 #HCV
br = 9
bdx = 1
bdy = 1
# speed of loop
fpsClock = pygame.time.Clock()
FPS = 60
go = True
while go:
fpsClock.tick(FPS)
for event in pygame.event.get():
if event.type ==pygame.QUIT:
go = False
elif event.type == pygame.KEYDOWN:
# control for the first paddle
if event.key == pygame.K_w:
p1dy = -1
elif event.key == pygame.K_s:
p1dy = 1
# controls for the second paddle
elif event.key == pygame.K_UP:
p2dy = -1
elif event.key == pygame.K_DOWN:
p2dy = 1
elif event.key == pygame.K_q:
go = False
# stops rectangles from going continously
if event.type == pygame.KEYUP:
if event.key == pygame.K_w or event.key == pygame.K_s:
p1dy = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
p2dy = 0
# stops paddle one from going off the screen
if (p1y < 0):
p1dy = 0
p1y = 0
if (p1y + p1h > screenh):
p1dy = 0
p1y = screenh - p1h
# stops paddle two from going off the screen
if (p2y < 0):
p2dy = 0
p2y = 0
if (p2y + p2h > screenh):
p2dy = 0
p2y = screenh - p2h
# stops ball from going off the screen
if (bx + br >= screenw):
bx = centerx
by = centery
elif (bx <= br):
bx = centerx
by = centery
if (by + br >= screenh):
bdy = -bdy
elif (by <= br):
bdy = -bdy
# detects if ball hit paddles
if bx - br <= p1x + p1w and by >= p1y and by <= p1y + p1h:
bdx = -bdx
if bx + br >= p2x and by >= p2y and by <= p2y + p2h:
bdx = -bdx
# moves the rectangles
p1y = p1y + p1dy
p2y = p2y + p2dy
# moves the ball
bx = bx + bdx
by = by + bdy
# removes screen trail
screen.fill(BLACK)
# draws the rectangles
pygame.draw.rect(screen, WHITE,(p1x, p1y, p1w, p1h))
pygame.draw.rect(screen, WHITE,(p2x, p2y, p2w, p2h))
pygame.draw.circle(screen, WHITE, (bx, by), br, 0)
pygame.display.update()
pygame.quit()
sys.exit()
Uncouple the speed of your objects from the fps.
That way you don't need to change your fps if you want objects to move faster, you just increase the speed of the object.
and if a computer has performance issues and can't keep a reliable fps. Your game still runs at the same speed, it just shows less frames.
import time
...
# speed of objects
ball_speed = 50
paddle_speed = 200
...
last_update = time.time()
while True:
...
dt = time.time() - last_update
...
# moves the ball
bx += bdx * ball_speed * dt
...
pygame.draw.circle(screen, WHITE, (int(bx), int(by)), br, 0)
...
last_update = time.time()

Pygame Multiple bullets not spawning

So im new at pygame and coding my first project- a side scrolling shooter. The issue im having is with my bullets: when i press the space key, some of the bullets will show up but there are times when nothing happens, and no bullets spawn when i jump. Not quite sure how to go about fixing this issue- any ideas would be greatly appreciated.
Code is as follows:
import pygame
import math, random, sys, pygame.mixer
from pygame.locals import *
pygame.init()
pygame.mixer.pre_init(44100, -16, 2, 8192)
pygame.mixer.init()
jump = False
jump_offset = 0
jump_height = 250
k = pygame.key.get_pressed()
def events():
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
def do_jumping():
global jump_height
global jump
global jump_offset
if jump:
jump_offset += 3
if jump_offset >= jump_height:
jump = False
elif jump_offset > 0 and jump == False:
jump_offset -= 3
#Defining colours
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
#Window Settings
w = 1280
h = 720
half_w = w /2
half_h = h /2
AREA = w*h
#Initialising the window
pygame.init()
display = pygame.display.set_mode((w,h)) #Sets the size of the window
pygame.display.set_caption("Cattleman") #Sets the title of the window
Clock = pygame.time.Clock() #clockspeed for the game ie. 60fps
FPS = 600
#pygame.mouse.set_visible(True) #Allows the mouse to be shown in the game window.
background = pygame.image.load("background.png").convert()
backgroundWidth, backgroundHeight = background.get_rect().size
stageWidth = backgroundWidth*2 #sets the area which the player can move in
stagePosX = 0 #Records position of stage as the player moves
startScrollPosX = half_w
circleRadius = 25
circlePosX = circleRadius
playerPosX = circleRadius
playerPosY = 602
playerVelocityX = 0
playersprite = pygame.image.load("player_spriteR2.png").convert_alpha()
playersprite = pygame.transform.scale(playersprite, (130,130))
bullets = []
bulletSprite = pygame.image.load("Bullet1.png").convert_alpha()
bulletSprite = pygame.transform.scale(bulletSprite, (20,10))
#Sounds
#gunSounds = ["pew1.wav", "pew2.wav", "pew3.wav", "pew4.wav"]
#SOUNDS
shot = pygame.mixer.Sound("pew1.wav")
#------------------------MAIN PROGRAM LOOP------------------------#
while True:
events()
do_jumping()
k = pygame.key.get_pressed()
if k[K_RIGHT]:
playerVelocityX = 2 #Moves the player right
playersprite = pygame.image.load("player_spriteR2.png").convert_alpha()
playersprite = pygame.transform.scale(playersprite, (130,130))
if k[K_LEFT]:
playerVelocityX = -2 #Moves the player left
playersprite = pygame.image.load("player_spriteL2.png").convert_alpha()
playersprite = pygame.transform.scale(playersprite, (130,130))
if k[K_UP] and jump == False and jump_offset == 0:
jump = True
if not k[K_RIGHT] and not k[K_LEFT]:
playerVelocityX = 0 #If no input detected, the player does not move
if k[K_SPACE]:
for event in pygame.event.get():
bullets.append([circlePosX-100, playerPosY-20])
shot.play()
playerPosX += playerVelocityX
if playerPosX > stageWidth - circleRadius-25: playerPosX = stageWidth - circleRadius-25 #Checks if the player trie to go past the right boundary
if playerPosX < circleRadius+55:playerPosX = circleRadius+55 #Checks if the player tries to go past the left boundary
if playerPosX < startScrollPosX: circlePosX = playerPosX
elif playerPosX > stageWidth - startScrollPosX: circlePosX = playerPosX - stageWidth + w
else:
circlePosX = startScrollPosX
stagePosX += -playerVelocityX
for b in range(len(bullets)):
bullets[b][0] -= 3
for bullet in bullets[:]:
if bullet[0] < 0:
bullets.remove(bullet)
rel_x = stagePosX % backgroundWidth
display.blit(background,(rel_x - backgroundWidth, 0))
if rel_x < w:
display.blit(background, (rel_x, 0))
for bullet in bullets:
display.blit(bulletSprite, pygame.Rect(bullet[0], bullet[1], 0, 0,))
#pygame.draw.circle(display,WHITE, (int(circlePosX),playerPosY - jump_offset), circleRadius, 0)
display.blit(playersprite, (int(circlePosX-80),playerPosY-100 - jump_offset))
pygame.display.update()
Clock.tick(FPS)
display.fill(BLACK)
I have done this in my code that leaves multiple balls similar like bullets :
class Bullet():
def __init__(self, x, y):
# self.image = pygame.image.load("SingleBullet.png")
self.image = pygame.image.load("ball.png")
self.image = pygame.transform.scale(self.image, (25, 25))
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.is_alive = True
# --------------------
def update(self):
self.rect.y -= 15
if self.rect.y < 0:
self.is_alive = False
# --------------------
def draw(self, screen):
screen.blit(self.image, self.rect.topleft)
for getting keyboard :
def event_handler(self, event):
if event.type == KEYDOWN:
if event.key == K_LEFT:
self.move_x = -5
elif event.key == K_RIGHT:
self.move_x = 5
elif event.key == K_SPACE:
if len(self.shots) < self.max_shots:
self.shots.append(Bullet(self.rect.centerx, self.rect.top))
if event.type == KEYUP:
if event.key in (K_LEFT, K_RIGHT):
self.move_x = 0

add a stopwatch to a game in pygame

i want to add a stopwatch in my pygame. I am planning to modify this code and add in my pygame:
Sec += 1
print(str(Min) + " Mins " + str(Sec) + " Sec ")
if Sec == 60:
Sec = 0
Min += 1
print(str(Min) + " Minute")
Should i add a timer box in my def init part and create a new def for the timer code? I want to have the timer without using the code tick since my game is running clock.tick(60) so it does not effect the tick
UPDATED
So here is my game code:
import sys, pygame, random
class Breakout():
def main(self):
xspeed_init = 6
yspeed_init = 6
max_lives = 5
bat_speed = 30
score = 0
bgcolour = 0x2F, 0x4F, 0x4F # darkslategrey
size = width, height = 640, 480
pygame.init()
screen = pygame.display.set_mode(size)
#screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
bat = pygame.image.load("bat.png").convert()
batrect = bat.get_rect()
ball = pygame.image.load("ball.png").convert()
ball.set_colorkey((255, 255, 255))
ballrect = ball.get_rect()
pong = pygame.mixer.Sound('Blip_1-Surround-147.wav')
pong.set_volume(10)
wall = Wall()
wall.build_wall(width)
# Initialise ready for game loop
batrect = batrect.move((width / 2) - (batrect.right / 2), height - 20)
ballrect = ballrect.move(width / 2, height / 2)
xspeed = xspeed_init
yspeed = yspeed_init
lives = max_lives
clock = pygame.time.Clock()
pygame.key.set_repeat(1,30)
pygame.mouse.set_visible(0) # turn off mouse pointer
while 1:
# 60 frames per second
clock.tick(60)
# process key presses
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
sys.exit()
if event.key == pygame.K_LEFT:
batrect = batrect.move(-bat_speed, 0)
if (batrect.left < 0):
batrect.left = 0
if event.key == pygame.K_RIGHT:
batrect = batrect.move(bat_speed, 0)
if (batrect.right > width):
batrect.right = width
# check if bat has hit ball
if ballrect.bottom >= batrect.top and \
ballrect.bottom <= batrect.bottom and \
ballrect.right >= batrect.left and \
ballrect.left <= batrect.right:
yspeed = -yspeed
pong.play(0)
offset = ballrect.center[0] - batrect.center[0]
# offset > 0 means ball has hit RHS of bat
# vary angle of ball depending on where ball hits bat
if offset > 0:
if offset > 30:
xspeed = 7
elif offset > 23:
xspeed = 6
elif offset > 17:
xspeed = 5
else:
if offset < -30:
xspeed = -7
elif offset < -23:
xspeed = -6
elif xspeed < -17:
xspeed = -5
# move bat/ball
ballrect = ballrect.move(xspeed, yspeed)
if ballrect.left < 0 or ballrect.right > width:
xspeed = -xspeed
pong.play(0)
if ballrect.top < 0:
yspeed = -yspeed
pong.play(0)
# check if ball has gone past bat - lose a life
if ballrect.top > height:
lives -= 1
# start a new ball
xspeed = xspeed_init
rand = random.random()
if random.random() > 0.5:
xspeed = -xspeed
yspeed = yspeed_init
ballrect.center = width * random.random(), height / 3
if lives == 0:
msg = pygame.font.Font(None,70).render("Game Over", True, (0,255,255), bgcolour)
msgrect = msg.get_rect()
msgrect = msgrect.move(width / 2 - (msgrect.center[0]), height / 3)
screen.blit(msg, msgrect)
pygame.display.flip()
# process key presses
# - ESC to quit
# - any other key to restart game
while 1:
restart = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
sys.exit()
if not (event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT):
restart = True
if restart:
screen.fill(bgcolour)
wall.build_wall(width)
lives = max_lives
score = 0
break
if xspeed < 0 and ballrect.left < 0:
xspeed = -xspeed
pong.play(0)
if xspeed > 0 and ballrect.right > width:
xspeed = -xspeed
pong.play(0)
# check if ball has hit wall
# if yes yhen delete brick and change ball direction
index = ballrect.collidelist(wall.brickrect)
if index != -1:
if ballrect.center[0] > wall.brickrect[index].right or \
ballrect.center[0] < wall.brickrect[index].left:
xspeed = -xspeed
else:
yspeed = -yspeed
pong.play(0)
wall.brickrect[index:index + 1] = []
score += 10
screen.fill(bgcolour)
scoretext = pygame.font.Font(None,40).render(str(score), True, (0,255,255), bgcolour)
scoretextrect = scoretext.get_rect()
scoretextrect = scoretextrect.move(width - scoretextrect.right, 0)
screen.blit(scoretext, scoretextrect)
for i in range(0, len(wall.brickrect)):
screen.blit(wall.brick, wall.brickrect[i])
# if wall completely gone then rebuild it
if wall.brickrect == []:
wall.build_wall(width)
xspeed = xspeed_init
yspeed = yspeed_init
ballrect.center = width / 2, height / 3
screen.blit(ball, ballrect)
screen.blit(bat, batrect)
pygame.display.flip()
class Wall():
def __init__(self):
self.brick = pygame.image.load("brick.png").convert()
brickrect = self.brick.get_rect()
self.bricklength = brickrect.right - brickrect.left
self.brickheight = brickrect.bottom - brickrect.top
def build_wall(self, width):
xpos = 0
ypos = 60
adj = 0
self.brickrect = []
for i in range (0, 52):
if xpos > width:
if adj == 0:
adj = self.bricklength / 2
else:
adj = 0
xpos = -adj
ypos += self.brickheight
self.brickrect.append(self.brick.get_rect())
self.brickrect[i] = self.brickrect[i].move(xpos, ypos)
xpos = xpos + self.bricklength
if __name__ == '__main__':
br = Breakout()
br.main()
You can use for example pygame.time.get_ticks() to get the number of milliseconds since pygame.init() was called, and then use simple division to get the seconds and minutes etc from that number.
Here's a simple example:
import pygame
import pygame.freetype
def main():
pygame.init()
screen=pygame.display.set_mode((400, 300))
clock=pygame.time.Clock()
font=pygame.freetype.SysFont(None, 34)
font.origin=True
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT: return
screen.fill(pygame.Color('grey12'))
ticks=pygame.time.get_ticks()
millis=ticks%1000
seconds=int(ticks/1000 % 60)
minutes=int(ticks/60000 % 24)
out='{minutes:02d}:{seconds:02d}:{millis}'.format(minutes=minutes, millis=millis, seconds=seconds)
font.render_to(screen, (100, 100), out, pygame.Color('dodgerblue'))
pygame.display.flip()
clock.tick(60)
if __name__ == '__main__': main()
If you want to have your stopwatch "to start later", you could store the output of pygame.time.get_ticks() at this moment and simply substract it from the result of further calls (something like starttime=pygame.time.get_ticks() and ticks=pygame.time.get_ticks()-starttime later in the loop, you'll get the idea).
If your game is running on while loop, with fps of 60, you can get minutes and seconds by doing so:
frame_count = 0
frame_rate = 60
... while block of game running 60 fps
# Every second passes 60 frames, so you get seconds by dividing
# by 60
seconds = total_seconds // 60
# Because 1 second is 60 frames, minute is 60 seconds * 60 frames.
# So you divide by 60 * 60 = 3600
minutes = total_seconds // 3600 # Because every second is 60 fps
output_string = "Time: {0:02}:{1:02}".format(minutes, seconds)
frame_count += 1
I found this solution here

How to make Pacman's ghost randomly move around in Python?

How do I make a ghost in Pacman move around randomly? I figured out how to move your own player. I tried using the random.randiant command but instead it kept coming up with a blank screen. I tried bliting all the images but it still keeps coming up with a blank screen. I just want to experiment with the ghost first before I program it to kill the player. I'm running Window 7, Python 3.1 and Pygame 3.1.
import pygame, sys
from pygame.locals import *
pygame.init()
windowSurface = pygame.display.set_mode((640,480), 0, 32)
pygame.display.set_caption('Pacman')
background = pygame.image.load('back.jpg').convert()
pacman = pygame.image.load('aimball.png').convert_alpha()
ghost = pygame.image.load('ghosts.png').convert_alpha()
food = pygame.image.load('food.png').convert_alpha()
windowSurface.blit(background, (0,0))
windowSurface.blit(pacman, (0,0))
windowSurface.blit(pacman,(x,y))
windowSurface.blit(ghost, (100,100))
windowSurface.blit(ghost, (x,y ))
windowSurface.blit(food, (0,0))
def pacman():
x, y = 0,0
movex, movey = 0,0
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_q:
pygame.quit()
sys.exit()
elif event.key == K_LEFT:
movex = -1
elif event.key == K_RIGHT:
movex = +1
elif event.key == K_UP:
movey = -1
elif event.key == K_DOWN:
movey = +1
elif event.type == KEYUP:
if event.key == K_LEFT:
movex = 0
elif event.key == K_RIGHT:
movex = 0
elif event.key == K_UP:
movey = 0
elif event.key == K_DOWN:
movey = 0
x+=movex
y+=movey
def ghosts():
x, y = 0,0
movex, movey = 0,0
while True:
random.randiant = move(1,2,3,4)
if random.randiant == 1:
movex=-1
elif random.randiant == 2:
movex=+1
elif random.randiant == 3:
movey=-1
elif random.randiant == 4:
movey=+1
x+=movex
y+=movey
windowSurface.blit(background,(0,0))
windowSurface.blit(pacman,(x,y))
windowSurface.blit(pacman, (0,0))
windowSurface.blit(ghost, (x,y ))
windowSurface.blit(ghost, (100,100))
windowSurface.blit(food, (0,0))
pygame.display.update()
pygame.display.flip()
NOTE: I will not be making boundaries for my Pacman game. The ghost can move freely around the Pygame screen display.
so here is my pacman game, i hope it helps
import pygame
from pygame.locals import *
from sys import exit
import random as r
import time
# SET CHARECTERS POSITIONS START
player_x = 400
player_y = 200
ghost_1_x = -50
ghost_1_y = r.randint(1, 400)
ghost_2_x = r.randint(1, 800)
ghost_2_y = -50
ghost_3_x = 850
ghost_3_y = r.randint(1, 400)
ghost_4_x = r.randint(1, 800)
ghost_4_y = 450
point_x = r.randint(50, 750)
point_y = r.randint(10, 390)
# SET CHARECTERS POSITIONS END
# EXTRA VARIABLES START
points = .2
speed = points
running = True
size = 20
# EXTRA VARIABLES END
# START THE BEGINING OF THE MAIN PYTHON CODE START
pygame.init()
# START THE BEGINING OF THE MAIN PYTHON CODE END
# SET SCREEN SIZE START
screen = pygame.display.set_mode((800, 400))
# SET SCREEN SIZE END
# SET TITLE START
pygame.display.set_caption('my pac_man')
# SET TITLE END
# LOADING THE IMAGES OF THE CHARACTARS START
player = pygame.image.load ('pacman.png').convert()
ghost_1 = pygame.image.load('ghost1.png').convert()
ghost_2 = pygame.image.load('ghost2.png').convert()
ghost_3 = pygame.image.load('ghost1.png').convert()
ghost_4 = pygame.image.load('ghost2.png').convert()
point = pygame.image.load('Star.png').convert()
# LOADING THE IMAGES OF THE CHARECTERS END
# DEFINING DIRECTIONS START
up = 1
down = 2
left = 3
right = 4
# DEFINING DIRECTIONS END
# DEFINING STARTING DIRECTION VARIABLE START
direction = up
# DEFINING STARTING DIRECTION VARIABLE END
# MAIN GAME LOOP START
while running:
# TRANSFORMING THE IMAGES SO THAT THEY FIT ON THE SCREEN START
player = pygame.transform.scale(player, (size, size))
ghost_1 = pygame.transform.scale(ghost_1, (size, size))
ghost_2 = pygame.transform.scale(ghost_2, (size, size))
ghost_3 = pygame.transform.scale(ghost_1, (size, size))
ghost_4 = pygame.transform.scale(ghost_2, (size, size))
point = pygame.transform.scale(point, (size, size))
# TRANSFORMING THE IMAGES SO THAT THEY FIT ON THE SCREEN END
# EXTRA VARIABLES NEEDED IN GAME LOOP START
speed = points
# EXTRA VARIABLES NEEDED IN GAME LOOP END
# LOOK FOR EVENTS IN PYGAME START
for event in pygame.event.get():
# CHECK IF THE MOUSE HITS THE X START
if event.type == pygame.QUIT:
# IF THE MOUSE HITS THE X THEN EXIT START
pygame.quit()
exit()
# IF THE MOUSE HITS THE X THEN EXIT END
#CHECK IF THE MOUSE HITS THE X END
# SENCE A KEY IS PRESSED START
if event.type == pygame.KEYDOWN:
# SENCE IF AN ARROW KEY IS PRESSED
if event.key == pygame.K_LEFT:
direction = left
if event.key == pygame.K_RIGHT:
direction = right
if event.key == pygame.K_UP:
direction = up
if event.key == pygame.K_DOWN:
direction = down
# SENCE IF AN ARROW KEY IS PRESSED END
# SENCE IF A KEY IS PERSSED END
# LOOK FOR EVENTS IN PYGAME END
# PLAYER MOVEMENT START
if direction == up:
player_y -= speed
if direction == down:
player_y += speed
if direction == left:
player_x -= speed
if direction == right:
player_x += speed
# PLAYER MOVEMENT END
# PLAYER EDGE SENCING START
if player_x >= 800:
running = False
if player_x <= 0:
running = False
if player_y >= 400:
running = False
if player_y <= 0:
running = False
# PLAYER EDGE SENCING END
# GHOST 1 MOVEMENT START
if ghost_1_x <= player_x:
ghost_1_x += speed / 2
if ghost_1_x >= player_x:
ghost_1_x -= speed / 2
if ghost_1_y <= player_y:
ghost_1_y += speed / 2
if ghost_1_y >= player_y:
ghost_1_y -= speed / 2
# GHOST 1 MOVEMSNT END
# GHOST 2 MOVEMENT START
if ghost_2_x <= player_x:
ghost_2_x += speed / 2
if ghost_2_x >= player_x:
ghost_2_x -= speed / 2
if ghost_2_y <= player_y:
ghost_2_y += speed / 2
if ghost_2_y >= player_y:
ghost_2_y -= speed / 2
# GHOST 2 MOVEMSNT END
# GHOST 3 MOVEMENT START
if ghost_3_x <= player_x:
ghost_3_x += speed / 2
if ghost_3_x >= player_x:
ghost_3_x -= speed / 2
if ghost_3_y <= player_y:
ghost_3_y += speed / 2
if ghost_3_y >= player_y:
ghost_3_y -= speed / 2
# GHOST 3 MOVEMSNT END
# GHOST 4 MOVEMENT START
if ghost_4_x <= player_x:
ghost_4_x += speed / 2
if ghost_4_x >= player_x:
ghost_4_x -= speed / 2
if ghost_4_y <= player_y:
ghost_4_y += speed / 2
if ghost_4_y >= player_y:
ghost_4_y -= speed / 2
# GHOST 4 MOVEMSNT END
# BACKGROUND COLOR START
screen.fill((0, 0, 0))
# BACKGROUND COLOR END
# collision sencing format
# if rect_1 x < rect_2 x + rect_1 width and rect_1 x + rect_2 width > rect_2 x and rect_1 y < rect_2 y + rect_1 height and rect_1 height + rect_1 y > rect_2 y
# CHECKING FOR COLLISION START
if player_x < ghost_1_x + size and player_x + size > ghost_1_x and player_y < ghost_1_y + size and size + player_y > ghost_1_y:
running = False
if player_x < ghost_2_x + size and player_x + size > ghost_2_x and player_y < ghost_2_y + size and size + player_y > ghost_2_y:
running = False
if player_x < ghost_3_x + size and player_x + size > ghost_3_x and player_y < ghost_3_y + size and size + player_y > ghost_3_y:
running = False
if player_x < ghost_4_x + size and player_x + size > ghost_4_x and player_y < ghost_4_y + size and size + player_y > ghost_4_y:
running = False
if player_x < point_x + size and player_x + size > point_x and player_y < point_y + size and size + player_y > point_y:
points += 0.1
size += 5
point_x = r.randint(50, 750)
point_y = r.randint(10, 390)
# CHECKING FOR COLLISION END
# PLACE CHARACTERS START
screen.blit(player, (player_x, player_y))
screen.blit(ghost_1, (ghost_1_x, ghost_1_y))
screen.blit(ghost_2, (ghost_2_x, ghost_2_y))
screen.blit(ghost_3, (ghost_3_x, ghost_3_y))
screen.blit(ghost_4, (ghost_4_x, ghost_4_y))
screen.blit(point, (point_x, point_y))
# PLACE CHARECTERS END
# SHOW SCORE START
font = pygame.font.Font(None, size)
if size == 20:
text = font.render(('20'), 1, (255, 0, 0))
if size == 25:
text = font.render(('25'), 1, (255, 0, 255))
if size == 30:
text = font.render(('30'), 1, (255, 255, 0))
if size == 35:
text = font.render(('35'), 1, (0, 255, 0))
if size == 40:
text = font.render(('40'), 1, (0, 0, 255))
if size == 45:
text = font.render(('45'), 1, (255, 0, 255))
if size == 50:
text = font.render(('50'), 1, (255, 255, 255))
if size == 55:
text = font.render(('55'), 1, (255, 255, 255))
if size == 60:
text = font.render(('YOU WIN'), 1, (255, 255, 255))
screen.blit(text, (200,200))
# SHOW SCORE END
# UPDATE CHANGES IN CODE, VARIABLES, PICTURES, ECT... IN PYGAME START
pygame.display.update()
# UPDATE CHANGES IN CODE, VARIABLES, PICTURES, ECT... IN PYGAME END
# MAIN GAME LOOP END
I think what you're asking for is
class Ghost():
def __init__(self):
self.x, self.y = 0, 0
self.movex, self.movey = 0, 0
def move(self):
# move in random directions.
self.movex = random.randint(-1,1)
self.movey = random.randint(-1,1)
self.x += movex
self.y += movey

Categories