Related
Im replicating a basic pong game and my paddles are opposite. My left paddle moves with the arrows while the right paddle moves with wsad, so when you play the players play they have to move the opposite paddle that they are on the side of. Also, I'm trying to make the ball come back when its off the screen and I was playing around with it and now there's collision with the wall as well as the paddle causing it to be a never ending game instead of rounded pong.
# import the necessary modules
import pygame
import sys
import time
#initialize pygame
pygame.init()
screenSize=(700,500)
screen=pygame.display.set_mode((screenSize), 0)
# set the caption for the screen
pygame.display.set_caption("Meryem's 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)
# set the size for the surface (screen)
screen_h = screen.get_height()
screen_w = screen.get_width()
cx = int(screen_w/2)
cy = int(screen_h/2)
#initialize variables for player
#variables for first rectangle
R1x = 660
R1y = 300
R1w = 10
R1h = 132
R1dx = 0
R1dy = 0
R1_score = 0
#variables for second rectangle
R2x = 10
R2y = 2
R2w = 10
R2h = 132
R2dx = 0
R2dy = 0
R2_score = 0
#ball variables
bx = cx
by = cy
dby = 3
dbx = 3
br = 5
cy = screen.get_height()/2
cx = screen.get_width()/2
# variable for scores
R1_score = 0
R2_score = 0
playerRect = pygame.Rect(R2x,R2y,R2w, R2h)
playerRect2 = pygame.Rect(R1x,R1y,R1w, R1h)
ballRect = pygame.Rect (cx,cy,30,30)
#speed
speed = 3
fontsize = 50
fontScore = pygame.font.SysFont('arial', 50)
fontScore = pygame.font.SysFont('arial', 50)
R1Score = fontScore.render(str(R1_score), True, (WHITE))
R2Score = fontScore.render(str(R2_score), True, (WHITE))
# speed of object "clock"
clock = pygame.time.Clock()
FPS_easy = 30 # set frames per second for easy level
FPS_medium = 80 # set frames per second for medium level
FPS_progressive = 100 # set frames per second for progressive level
# 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
playerRect.y = playerRect.y + R1dy
playerRect2.y = playerRect2.y + R2dy
ballRect.move_ip(dbx,dby)
#collision of ball
if ballRect.top <= 0:
dby = -dby
if ballRect.bottom >= screen_h:
dby = -dby
if ballRect.left <= 0:
dbx = -dbx
if ballRect.right >= screen_w:
dbx = -dbx
if ballRect.colliderect(playerRect2):
dbx = -dbx
if ballRect.colliderect(playerRect):
dbx = -dbx
screen.fill(BLACK)
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE,(playerRect),0)
pygame.draw.rect(screen, WHITE,(playerRect2),0)
pygame.draw.circle(screen, RED,ballRect.center,br,0)
screen.blit(R1Score, (280,10))
screen.blit(R2Score, (400,10))
# 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()
fixed your issues:
# import the necessary modules
import pygame
import sys
import time
#initialize pygame
pygame.init()
screenSize=(700,500)
screen=pygame.display.set_mode((screenSize), 0)
# set the caption for the screen
pygame.display.set_caption("Meryem's 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)
# set the size for the surface (screen)
screen_h = screen.get_height()
screen_w = screen.get_width()
cx = int(screen_w/2)
cy = int(screen_h/2)
#initialize variables for player
#variables for first rectangle
R1x = 660
R1y = 300
R1w = 10
R1h = 132
R1dx = 0
R1dy = 0
R1_score = 0
#variables for second rectangle
R2x = 10
R2y = 2
R2w = 10
R2h = 132
R2dx = 0
R2dy = 0
R2_score = 0
#ball variables
bx = cx
by = cy
dby = 1
dbx = 1
br = 5
cy = screen.get_height()/2
cx = screen.get_width()/2
# variable for scores
R1_score = 0
R2_score = 0
playerRect = pygame.Rect(R2x,R2y,R2w, R2h)
playerRect2 = pygame.Rect(R1x,R1y,R1w, R1h)
ballRect = pygame.Rect (cx,cy,30,30)
#speed
speed = 3
fontsize = 50
fontScore = pygame.font.SysFont('arial', 50)
fontScore = pygame.font.SysFont('arial', 50)
R1Score = fontScore.render(str(R1_score), True, (WHITE))
R2Score = fontScore.render(str(R2_score), True, (WHITE))
# speed of object "clock"
clock = pygame.time.Clock()
FPS_easy = 30 # set frames per second for easy level
FPS_medium = 80 # set frames per second for medium level
FPS_progressive = 100 # set frames per second for progressive level
# 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:
R2dx = 0
R2dy = -speed
elif event.key == pygame.K_DOWN:
R2dx = 0
R2dy = speed
if event.key == pygame.K_w:
R1dx = 0
R1dy = -speed
elif event.key == pygame.K_s:
R1dx = 0
R1dy = speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
R2dx = 0
R2dy = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
R1dx = 0
R1dy = 0
playerRect.y = playerRect.y + R1dy
playerRect2.y = playerRect2.y + R2dy
ballRect.move_ip(dbx,dby)
#collision of ball
if ballRect.top <= 0:
dby = -dby
if ballRect.bottom >= screen_h:
dby = -dby
if ballRect.left <= 0:
dbx = -dbx
if ballRect.right >= screen_w:
dbx = -dbx
if ballRect.colliderect(playerRect2):
dbx = -dbx
if ballRect.colliderect(playerRect):
dbx = -dbx
screen.fill(BLACK)
# draw the shapes, in this case the blue rectangles
pygame.draw.rect(screen, WHITE,(playerRect),0)
pygame.draw.rect(screen, WHITE,(playerRect2),0)
pygame.draw.circle(screen, RED,ballRect.center,br,0)
screen.blit(R1Score, (280,10))
screen.blit(R2Score, (400,10))
# we are using .flip() here, it basically works the same as .update()
# we will discuss this more in class (you can use either one)
time.sleep(0.005)
pygame.display.flip()
# quit pygame and exit the program (i.e. close everything down)
pygame.quit()
sys.exit()
must say the code you gave isn't very pretty
You have confused R1x, R1y, R1w, R1h and R2x, R2y, R2w, R2h when you create the pygame.Rect objects playerRect respectively playerRect2
playerRect = pygame.Rect(R2x,R2y,R2w, R2h)
playerRect2 = pygame.Rect(R1x,R1y,R1w, R1h)
playerRect = pygame.Rect(R1x, R1y, R1w, R1h)
playerRect2 = pygame.Rect(R2x, R2y, R2w, R2h)
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()
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
I was working on a game, similar to Pong on pygame, and I had come across the problem of wall collision detection. It works with the two paddles, but does not work with the ball itself. The code makes sense, but it doesn't actually work.
import pygame, sys
from pygame.locals import *
x = 25
xc = 404
yc = 300
y = 225
x1 = 740
movey1 = 0
y1 = 225
movex = 0
movey = 0
movebx = 2
moveby = 2
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,128)
RANDOM = (255,0, 0)
BLACK = (0,0,0)
width = 600
pygame.init()
display = pygame.display.set_mode((800,600))
pygame.display.set_caption("Pong!")
img = pygame.image.load("pongbg.jpg")
pygame.mixer.music.load("stay.mp3")
pygame.mixer.music.play(0)
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
pygame.mixer.music.load("stay.mp3")
pygame.mixer.music.play(0)
if event.key == pygame.K_w:
movey = -2
pygame.display.flip()
if y <= 0 or y>=600:
print "hello"
movey = -movey
if event.key == pygame.K_s:
movey = 2
pygame.display.flip()
if y >= 600 or y <0:
print "hello"
movey = -movey
if event.key == pygame.K_UP:
movey1 = -2
if y1 <= 0 or y1> 600:
print "hello"
movey1 = -movey1
if event.key == pygame.K_DOWN:
movey1 = 1.5
if y1 <= 0 or y1> 600:
print "hello"
movey1 = -movey1
if yc < 0 or yc >= 600 or yc >= 500:
print "hello"
moveby = -moveby
if xc < 0 or xc > 800:
print "hello"
moveby = -moveby
if event.type == pygame.KEYUP:
movey1 = 0
movey = 0
if event.type == QUIT:
pygame.quit()
sys.exit()
x += movex
y += movey
y1 += movey1
xc+=movebx
yc+=moveby
#xc += movey
#yc +=movey1
pygame.display.flip()
display.blit(img, (0,0))
asdf = pygame.draw.rect(display, RANDOM, (x,y,34, 154))
ghjk = pygame.draw.rect(display,RANDOM, (x1,y1,34,154))
qwerty = pygame.draw.circle(display,GREEN, (xc,yc), 25,0)
pygame.display.flip()
pygame.display.update()
Everything else is pretty much done, I have looked around in stack overflow, but could not find a detailed answer.
Thanks,
AJ
Read up about pygame.rect and pygame.rect.colliderect
you could make the walls rects and put rects on the bumpers and detect when the bumper collides with the wall.
Sorry about the short answer.
You can use rects or you can use loads of if's statments.
you know the ball's x and the ball's y. you know the ball's width and height, and the paddles' too.
all you have to do is check if the ball's right (xc+25) is greater than the right paddle's left (x1). same with the left paddle.
with rects in pygame, you can use the function b.colliderect(a) which returns True if b and a collide.
I'm afraid you paddle detection does not work as well. My advice would be to divide your code into classes. This way the paddles will be informed of the intent of moving, but they will decide if it is possible to move. I have also noticed that you are flipping the screen inside the event loop. The event loop should not update the screen, only move the sprites around.
Here is something you can start with:
class Paddle:
def __init__(self,x,y):
self.vy = 0
self.y = y
self.x = x
def move(self):
if( self.vy == 1 and canMoveUp(self.y) or self.vy == -1 and canMoveDown(self.y):
self.y+=vy
def draw(self,screen):
screen.blit()
class Ball:
def __init__(self,x,y):
self.vx = 1
self.vy = 0
self.x = y
self.y = x
def move(self):
#check for collisions same as with paddles
def draw(self,screen):
screen.blit()
I can just say how my program with collision work:
import pygame
from pygame.locals import*
import sys
pygame.init()
screen = pygame.display.set_mode((1200, 700))
ticket1 = True
f = [0, 0]
pa = 600
pb = 650
a = 600
b = 650
color = (100, 180, 100)
while ticket1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
ticket1 = False
pygame.quit()
sys.exit()
screen.fill((255, 250, 245))
pygame.draw.circle(screen, color, (a, b), 50)
pa += f[0]
pb += f[1]
a = int(pa)
b = int(pb)
if a-50 < 0:
f[0] = -f[0]
a = 51
pa = 51
elif a+50 > 1200:
f[0] = -f[0]
a = 1149
pa = 1149
if b-50 < 0:
f[1] = -f[1]
b = 51
pb = 51
elif b+50 > 700:
f[1] = -f[1]
b = 650
pb = 650
If you think that this is bad answer this program works so maybe you have to write
if yc < 0 or yc >= 600 or yc >= 500:
print "hello"
moveby = -moveby
if xc < 0 or xc > 800:
print "hello"
moveby = -moveby
outside of:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
but I'm not sure.
For the paddles I think that answers before have good idea.
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