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
Related
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()
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)
I'm making a game with pygame, Space Invaders, and now I'm doing the collisions between the shoot of the eneimies and the player (those are images), but it doesn't work all time and I'd like to know why, and what's the solution.
Thanks for attention!
Here's the code:
# -*- coding: cp1252 -*-
import sys
import random
import pygame
import time
print pygame.init()
x_player, y_player = 650, 440
screen = pygame.display.set_mode((700, 500))
pygame.display.set_caption("Space Invaders v1.0.0")
invaders = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders- my_own\\space-invaders.jpeg").convert_alpha()
player = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\28006.png").convert_alpha()
mother_ship = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\mother_ship.png").convert_alpha()
lifes = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\28007.png").convert_alpha()
shoot_enemie = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\shots_and_bombs2.png").convert_alpha()
shoot = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\shots_and_bombs2.png").convert_alpha()
pygame.font.init()
clock = pygame.time.Clock()
move_x = 0
x_invaders, y_invaders = 60, 60
lifes_list = [lifes, lifes, lifes]
x_mother = 0
invaders_matrix = [[invaders] * 11] * 5
existe_nave = False
start = True
tru = False
tru3= True
x_shoot = x_player
y_shoot = 0
tru2 = True
shoot_enemie1, shoot_enemie2, shoot_enemie3 = shoot_enemie, shoot_enemie, shoot_enemie
shoot_list = [shoot_enemie1, shoot_enemie2, shoot_enemie]
tiros = {
"se1" : [0, 0],
"se2" : [0, 0],
"se3" : [0, 0]
}
cont = 0
while True:
invaders_matrix = [[invaders] * 11] * 5
if len(lifes_list) > 0:
clock.tick(40)
screen.fill((0, 0, 0))
screen.blit(player, ((x_player / 2), y_player))
if not tru:
invaders = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\space- invader-motif.png"
).convert_alpha()
tru = True
else:
invaders = pygame.image.load(
"C:\\Users\\bernardo\\Documents\\IFC\\Programação\\SpaceInvaders-my_own\\space-invaders.jpeg"
).convert_alpha()
tru = False
x_invaders, y_invaders = 105, 125
for invader in range(len(invaders_matrix)):
for invad in range(len(invaders_matrix[invader])):
screen.blit(invaders_matrix[invader][invad], (x_invaders, y_invaders))
x_invaders += 45
x_invaders = 105
y_invaders += 30
if tru2:
for i in tiros.keys():
tiros[i][0] += tiros[i][0] + random.randint(0, 10) * 45 + 105
tiros[i][1] += tiros[i][1] + random.randint(0, 4) * 45 + 125
tru2 = False
elif tiros["se1"][1] >= 600 and tiros["se2"][1] >= 600 and tiros["se3"][1] >= 600:
tiros["se1"][1], tiros["se2"][1], tiros["se3"][1], \
tiros["se1"][0], tiros["se2"][0], tiros["se3"][0] = 0, 0, 0, 0, 0, 0
for i in tiros.keys():
tiros[i][0] += tiros[i][0] + random.randint(0, 10) * 45 + 105
tiros[i][1] += tiros[i][1] + random.randint(0, 4) * 45 + 125
for i in shoot_list:
for j in tiros.keys():
screen.blit(i, (tiros[j][0], tiros[j][1]))
for i in tiros.keys():
tiros[i][1] += 4
if existe_nave and (x_mother < 700):
screen.blit(mother_ship, [x_mother, 35])
x_mother += 4.5
screen.blit(mother_ship, [x_mother, 35])
elif random.randint(0, 800) == 0:
existe_nave = True
x_mother = 0
width_for_lifes = 680
for icon_lifes in lifes_list:
width_for_lifes -= 50
screen.blit(icon_lifes, (width_for_lifes, 15))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 10
if event.key == pygame.K_RIGHT:
move_x += 10
if tru3:
if event.key == pygame.K_SPACE:
y_shoot = y_player - player.get_height()
x_shoot = x_player / 2 + 20
tru3 = False
elif not tru3:
if y_shoot <= 0 and event.key == pygame.K_SPACE:
y_shoot = y_player - player.get_height()
x_shoot = x_player / 2 + 20
if event.type == pygame.KEYUP and (event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT):
move_x = 0
if y_shoot > -50:
screen.blit(shoot, (x_shoot, y_shoot))
y_shoot -= 10
if x_player >= 1280:
x_player = 1280
if x_player <= 25:
x_player = 25
x_player += move_x
font = pygame.font.Font(None, 36)
text = font.render("Lifes", 1, (0, 255, 85))
screen.blit(text, (450, 15))
font = pygame.font.Font(None, 36)
text = font.render("Score", 1, (0, 255, 85))
screen.blit(text, (20, 15))
#Here is the problem
player_rect = pygame.Rect(x_player, y_player, player.get_height(), player.get_width())
shoot_enemie1_rect = pygame.Rect(tiros["se1"][0], tiros["se1"][1], shoot_enemie1.get_height(),
shoot_enemie1.get_width())
shoot_enemie2_rect = pygame.Rect(tiros["se2"][0], tiros["se2"][1], shoot_enemie2.get_height(),
shoot_enemie2.get_width())
shoot_enemie3_rect = pygame.Rect(tiros["se3"][0], tiros["se3"][1], shoot_enemie3.get_height(),
shoot_enemie3.get_width())
if player_rect.colliderect(shoot_enemie1_rect) or player_rect.colliderect(shoot_enemie2_rect) or \
player_rect.colliderect(shoot_enemie3_rect):
print True
print player_rect
pygame.display.update()
Here is a collision detection code that will sense if one rectangle collides with another rectangle, if the enemy's shot hits the player:
if player x < shot x + player width and player x + shot width > shot x and player y < shot y + player height and shot height + player_y > shot y:
It works by sensing if any of the edges of the bullet are touching any edges of the character. I hope this helps.
Well In a game I am working on I have recently allowed mouse click to shoot wherever the mouse is. But the bullets will only shoot at either a 0 degree angle or 45 degree angle. I am wanting to try and make this to be 360 degrees. Here is the code for my main game file:
import pygame, sys
import random
import pygame.mixer
import Funk, math
from time import sleep
from player import *
from zombie import *
from level import *
from bullet import *
from constants import *
from Drops import *
from menus import *
from meteors import *
import menu as dm
class Game():
def __init__(self):
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('data/sounds/menugame.ogg')
pygame.mixer.music.set_volume(0.5)
pygame.mixer.music.play(-1)
# A few variables
self.gravity = .50
self.red = (255, 0, 0)
self.darkred = (200, 0, 0)
self.darkblue = (0, 0, 200)
self.darkgreen = (0, 200, 0)
self.gameover = pygame.image.load('data/images/gameover.png')
self.victory = pygame.image.load('data/images/victory.png')
# Bullets and Drops
self.bullets = []
self.gameDrops = []
# Screen
icon = pygame.image.load('data/icons/moonsurvival.bmp')
size = SCREEN_WIDTH, SCREEN_HEIGHT
self.screen = pygame.display.set_mode(size)
pygame.display.set_caption('Moon Survival!')
pygame.display.set_icon(icon)
self.screen_rect = self.screen.get_rect()
# Moon / Background
self.moon = Background()
self.text1 = pygame.image.load('data/images/TextSlides/Text1.jpg')
self.text2 = pygame.image.load('data/images/TextSlides/Text2.jpg')
# Zombies and boss
self.zombies = []
self.bosses = []
#for i in range(15):
# self.zombies.append( Zombie(random.randint(0,1280), random.randint(0,0)) )
self.zombieskilled = 0
# Spawn time
self.last_spawn_time = 0
# Meteors
self.meteors = []
# Menus
self.menuStartGame = MenuStartGame(self.screen, self)
self.menuAbout = MenuAbout(self.screen, self)
#self.menuSettings = MenuSettings(self.screen, self)
self.menuScene = MenuScene(self.screen, self)
self.menuGameOver = MenuGameOver(self.screen, self)
#self.menuGameFinish = MenuGameFinish(self.screen, self)
# Player
self.player = Player(25, 320, self.gravity)
# Font for text
self.font = pygame.font.SysFont(None, 72)
self.point = self.player.rect.x, self.player.rect.y
self.max_radius = math.hypot(self.screen_rect.w, self.screen_rect.h)
self.mouse_angle = (0, 0)
# game over
self.gameover_text = self.font.render("The Aliens Are Too Good", -1, (255, 0, 0))
self.gameover_rect = self.gameover_text.get_rect(center=self.screen.get_rect().center)
# game state
self.game_state = STATE_MENU
def run(self):
clock = pygame.time.Clock()
# "state machine"
RUNNING = True
PAUSED = False
GAME_OVER = False
# Game loop
while RUNNING:
# (all) Events
if self.game_state == STATE_INGAME:
print(self.mouse_angle)
for event in pygame.event.get():
if event.type == pygame.QUIT:
RUNNING = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
if self.player.power == POWER_TRIBULLETS:
self.bullets.append(Bullet(self.player.rect.x + 35, self.player.rect.y + 35, self.mouse_angle))
self.bullets.append(Bullet(self.player.rect.x + 30, self.player.rect.y + 30, self.mouse_angle))
self.bullets.append(Bullet(self.player.rect.x + 35, self.player.rect.y + 25, self.mouse_angle))
else:
self.bullets.append(Bullet(self.player.rect.x + 30, self.player.rect.y + 30, self.mouse_angle))
if event.key == pygame.K_ESCAPE:
RUNNING = False
elif event.key == pygame.K_p:
# set state to paused
self.game_state = STATE_PAUSED
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if self.player.power == POWER_TRIBULLETS:
self.bullets.append(Bullet(self.player.rect.x + 35, self.player.rect.y + 35, self.mouse_angle))
self.bullets.append(Bullet(self.player.rect.x + 30, self.player.rect.y + 30, self.mouse_angle))
self.bullets.append(Bullet(self.player.rect.x + 35, self.player.rect.y + 25, self.mouse_angle))
else:
self.bullets.append(Bullet(self.player.rect.x + 30, self.player.rect.y + 30, self.mouse_angle))
# Player/Zombies events
self.player.handle_events(event)
# (all) Movements / Updates
self.player_move()
self.player.update()
for z in self.zombies:
self.zombie_move(z)
z.update(self.screen.get_rect())
for boss in self.bosses:
self.boss_move(boss)
boss.update(self.screen.get_rect())
for b in self.bullets:
b.update()
for tile in self.moon.get_surrounding_blocks(b):
if tile is not None:
if pygame.sprite.collide_rect(b, tile):
# Destroy block
x = tile.rect.x / tile.rect.width
y = tile.rect.y / tile.rect.height
self.moon.levelStructure[x][y] = None
try:
self.bullets.remove(b)
except:
continue
for m in self.meteors:
m.update()
for tile in self.moon.get_surrounding_blocks(m):
if tile is not None:
if pygame.sprite.collide_rect(m, tile):
# Destroy block
x = tile.rect.x / tile.rect.width
y = tile.rect.y / tile.rect.height
self.moon.levelStructure[x][y] = None
self.moon.levelStructure[x + 1][y + 1] = None
self.moon.levelStructure[x - 1][y - 1] = None
self.moon.levelStructure[x + 2][y + 2] = None
self.moon.levelStructure[x - 2][y - 2] = None
try:
self.meteors.remove(m)
except:
continue
self.check_game_state()
# (all) Display updating
self.moon.render(self.screen)
for z in self.zombies:
z.render(self.screen)
for boss in self.bosses:
boss.render(self.screen)
for b in self.bullets:
b.render(self.screen)
for m in self.meteors:
m.render(self.screen)
for drop in self.gameDrops:
drop.render(self.screen)
self.player.render(self.screen)
self.updateMousePosition(self.screen, pygame.mouse.get_pos())
Funk.text_to_screen(self.screen, 'Level 1', 5, 675)
Funk.text_to_screen(self.screen, 'Health: {0}'.format(self.player.health), 5, 0)
Funk.text_to_screen(self.screen, 'Score: {0}'.format(self.player.score), 400, 0)
Funk.text_to_screen(self.screen, 'Time: {0}'.format(self.player.alivetime), 750, 0)
Funk.text_to_screen(self.screen, 'Kills: {0}'.format(self.zombieskilled), 5, 50)
Funk.text_to_screen(self.screen, 'Lives: {0}'.format(self.player.lives), 300, 50)
elif self.game_state == STATE_GAMEOVER:
self.menuGameOver.draw()
self.menuGameOver.update()
elif self.game_state == STATE_SETTINGS:
self.menuSettings.draw()
self.menuSettings.update()
elif self.game_state == STATE_ABOUT:
self.menuAbout.draw()
self.menuAbout.update()
elif self.game_state == STATE_SCENE:
self.menuScene.draw()
self.menuScene.update()
elif self.game_state == STATE_MENU:
self.menuStartGame.draw()
self.menuStartGame.update()
elif self.game_state == STATE_PAUSED:
# (all) Display updating
if self.game_state == STATE_INGAME:
if event.type == pygame.QUIT:
RUNNING = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
RUNNING = False
choose = dm.dumbmenu(self.screen, [
'Resume Game',
'Menu',
'Quit Game'], 200, 200,'orecrusherexpanded',100,0.75,self.darkred,self.red)
if choose == 0:
print "You choose 'Start Game'."
# set state to ingame
self.game_state = STATE_INGAME
elif choose == 1:
print "You choose 'Controls'."
if choose == 2:
print "You choose 'Quit Game'."
pygame.quit()
sys.exit()
#for event in pygame.event.get():
self.moon.render(self.screen)
for z in self.zombies:
z.render(self.screen)
for boss in self.bosses:
boss.render(self.screen)
for b in self.bullets:
b.render(self.screen)
for m in self.meteors:
m.render(self.screen)
self.player.render(self.screen)
pygame.display.update()
# FTP
clock.tick(100)
# --- the end ---
pygame.quit()
def updateMousePosition(self, surface, mouse):
x_comp, y_comp = mouse[0] - self.point[0], mouse[1] - self.point[1]
self.mouse_angle = math.atan2(y_comp, x_comp)
x = self.max_radius * math.cos(self.mouse_angle) + self.point[0]
y = self.max_radius * math.sin(self.mouse_angle) + self.point[1]
pygame.draw.line(surface, pygame.Color("white"), self.point, (x, y))
def check_game_state(self):
elapsed_time = pygame.time.get_ticks()
if elapsed_time > self.last_spawn_time + 10:
# Spawn aliens
if len(self.zombies) <= 10:
self.zombies.append(Zombie(random.randint(0,1280), random.randint(0,0)))
# Spawned! Change last spawn time!
self.last_spawn_time = elapsed_time
meteor_time = pygame.time.get_ticks()
if meteor_time > self.last_spawn_time + random.randint(1000, 3000):
# Spawn meteors
if len(self.meteors) <= 1:
self.meteors.append(Meteor(random.randint(0,1280), random.randint(-100,0)))
# Spawned! Change last spawn time!
self.last_spawn_time = meteor_time
def player_move(self):
# Line start
self.point = self.player.rect.x + 30, self.player.rect.y + 30
# add gravity
self.player.do_jump()
# simulate gravity
self.player.on_ground = False
if not self.player.on_ground and not self.player.jumping:
self.player.velY = 4
# Drops
for drop in self.gameDrops:
if pygame.sprite.collide_rect(self.player, drop):
if type(drop) == HealthDrop:
self.player.health += 50
self.gameDrops.remove(drop)
elif type(drop) == SuperHealthDrop:
self.player.health += 1000
self.gameDrops.remove(drop)
elif type(drop) == TriBullets:
self.player.power = POWER_TRIBULLETS
self.gameDrops.remove(drop)
elif type(drop) == ShieldDrop:
self.player.power = POWER_SHIELD
self.gameDrops.remove(drop)
# Health
for zombie in self.zombies:
if pygame.sprite.collide_rect(self.player, zombie):
if self.player.power == POWER_SHIELD:
self.player.health -= 1
else:
self.player.health -= 5
# check if we die
if self.player.health <= 0:
self.player.power = POWER_NONE
self.player.lives -= 1
self.player.rect.x = 320
self.player.rect.y = 320
self.player.health += 200
if self.player.lives <= 0:
self.game_state = STATE_GAMEOVER
# move player and check for collision at the same time
self.player.rect.x += self.player.velX
self.check_collision(self.player, self.player.velX, 0)
self.player.rect.y += self.player.velY
self.check_collision(self.player, 0, self.player.velY)
def zombie_move(self, zombie_sprite):
# add gravity
zombie_sprite.do_jump()
percentage = random.randint(0, 100)
# simualte gravity
zombie_sprite.on_ground = False
if not zombie_sprite.on_ground and not zombie_sprite.jumping:
zombie_sprite.velY = 4
# Zombie damage
for zombie in self.zombies:
for b in self.bullets:
if pygame.sprite.collide_rect(b, zombie):
#The same bullet cannot be used to kill
#multiple zombies and as the bullet was
#no longer in Bullet.List error was raised
zombie.health -= 10
self.bullets.remove(b)
if zombie.health <= 0:
if (percentage >= 0) and (percentage < 40):
self.gameDrops.append(HealthDrop(zombie.rect.x + 10, zombie.rect.y + 30))
elif (percentage >= 0) and (percentage < 1):
self.gameDrops.append(SuperHealthDrop(zombie.rect.x + 20, zombie.rect.y + 30))
elif (percentage >= 1) and (percentage < 20):
self.gameDrops.append(TriBullets(zombie.rect.x + 30, zombie.rect.y + 30, self.player.direction))
elif (percentage >= 1) and (percentage < 50):
self.gameDrops.append(ShieldDrop(zombie.rect.x + 40, zombie.rect.y + 30))
self.zombieskilled += 1
self.player.score += 20
self.zombies.remove(zombie)
break
# move zombie and check for collision
zombie_sprite.rect.x += zombie_sprite.velX
self.check_collision(zombie_sprite, zombie_sprite.velX, 0)
zombie_sprite.rect.y += zombie_sprite.velY
self.check_collision(zombie_sprite, 0, zombie_sprite.velY)
def check_collision(self, sprite, x_vel, y_vel):
# for every tile in Background.levelStructure, check for collision
for block in self.moon.get_surrounding_blocks(sprite):
if block is not None:
if pygame.sprite.collide_rect(sprite, block):
# we've collided! now we must move the collided sprite a step back
if x_vel < 0:
sprite.rect.x = block.rect.x + block.rect.w
if type(sprite) is Zombie:
# the sprite is a zombie, let's make it jump
if not sprite.jumping:
sprite.jumping = True
sprite.on_ground = False
if x_vel > 0:
sprite.rect.x = block.rect.x - sprite.rect.w
if type(sprite) is Zombie:
# the sprite is a zombie, let's make it jump
if not sprite.jumping:
sprite.jumping = True
sprite.on_ground = False
if y_vel < 0:
sprite.rect.y = block.rect.y + block.rect.h
if y_vel > 0 and not sprite.on_ground:
sprite.on_ground = True
sprite.rect.y = block.rect.y - sprite.rect.h
#---------------------------------------------------------------------
Game().run()
Here is the code for the bullets:
import pygame, math
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, angle):
self.image = pygame.image.load('data/images/Sprites/laser.png')
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.velX = math.cos(angle * math.pi / 180) * 8
self.velY = math.sin(angle * math.pi / 180) * 8
# self.velX = 8
# self.velX = -8
# Bullet updates
def update(self):
# Velocity
self.rect.x += self.velX
self.rect.y += self.velY
def render(self, surface):
surface.blit(self.image, self.rect)
self.mouse_angle is already in radians. If you multiply it again by math.pi / 180, as you do in Bullet.__init__(), it will always give a value very close to zero.
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