so i wrote this game from a pygame intro tutorial, added menus and all to modify it. whenever i run the game on my MBP 17, it runs extremely slow. i googled it, and tried all solutions, to no avail. also, typing in my event.unicode works extremely horribly, i have to press the same key more than once for it to register. any help is appreciated.
import sys
import pygame
import random
import math
import mysql.connector as mysql
import pygame_textinput
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Die Alien Die')
#database requirements
msql = mysql.connect(user='root', password='7014403396', database='gamer')
cursor = msql.cursor()
#background
background = pygame.image.load('back.png').convert()
pygame.mixer.music.load('y2mate.com - Star Wars_ Sith Battle Theme Music_XS4_5xlA3Ls_320kbps.mp3')
pygame.mixer.music.play(-1)
clock = pygame.time.Clock()
#millenium falcom
playerimg = pygame.image.load('mfc.png')
playerX = 350
playerY = 480
dx = 0
dy = 0
#alien die
alienimg = []
alienX =[]
alienY =[]
adx = []
ady = []
no_of_aliens = 8
for i in range(no_of_aliens):
alienimg.append(pygame.image.load('spaceship.png'))
alienX.append(random.randint(0,735))
alienY.append(random.randint(50,250))
adx.append(0.3)
ady.append(random.randint(20,43))
#bullets
bulletimg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bdx = 0
bdy = 1
visibility = False
score = 0
font=pygame.font.Font('freesansbold.ttf',32)
font2 = pygame.font.Font('freesansbold.ttf',25)
font3 = pygame.font.Font('freesansbold.ttf',22)
# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)
click = False
def EnterUser():
texty = ''
global click
while True:
screen.fill((255, 255, 255))
textinput = pygame_textinput.TextInput()
events = pygame.event.get()
textinput.update(events)
screen.blit(textinput.get_surface(), (50, 150))
buttong = pygame.Rect(50, 330, 200, 50)
mx, my = pygame.mouse.get_pos()
pygame.draw.rect(screen, (255, 0, 0), buttong)
draw_text('enter username', font, (0, 0, 0), screen, 20, 20)
draw_text("Press Enter", font2, (0, 0, 0), screen, 50, 200)
draw_text("If you leave username blank", font2, (0, 0, 0), screen, 50, 250)
draw_text("your score wont register", font2, (0, 0, 0), screen, 50, 280)
text_surface = font.render(texty, True, (0,0,0))
screen.blit(text_surface, (50, 150))
draw_text('Lets Go', font2, (0, 0, 0), screen, 52, 340)
if buttong.collidepoint((mx, my)):
if click:
main_menu()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
texty += event.unicode
if event.key == pygame.K_BACKSPACE:
texty = texty[:-1]
if event.key == pygame.K_ESCAPE:
pygame.quit()
if event.type == pygame.K_RETURN:
main_menu()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
def draw_text(text, font, color, surface, x, y):
textobj = font.render(text, 1, color)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
def player(x, y):
screen.blit(playerimg, (x, y))
def alien(x,y,i):
screen.blit(alienimg[i],(x,y))
def shoot(x,y):
global visibility
visibility = True
screen.blit(bulletimg,(x+25,y+10))
def collide(bulletX,bulletY,alienX,alienY):
distance = math.sqrt(math.pow(alienX-bulletX,2)+math.pow(alienY-bulletY,2))
if distance < 27:
return True
else:
return False
def showscore(x,y):
sscore=font.render('Score: '+str(score),True,(141,27,31))
screen.blit(sscore,(x,y))
def game_over_text():
over_text = over_font.render("GAME OVER", True, (255, 255, 255))
screen.blit(over_text, (200, 250))
fscore = score
save_score()
def save_score():
t = "INSERT INTO alien VALUES('{}', '{}')".format(texty, str(score))
#val = (texty, str(score))
cursor.execute(t)
msql.commit()
#def show_high():
def main_menu():
while True:
screen.fill((0, 0, 0))
draw_text('Main Menu', font, (255, 255, 255), screen, 20, 20)
mx, my = pygame.mouse.get_pos()
button_1 = pygame.Rect(50, 100, 200, 50)
button_2 = pygame.Rect(50, 200, 200, 50)
if button_1.collidepoint((mx, my)):
if click:
game()
if button_2.collidepoint((mx, my)):
if click:
options()
pygame.draw.rect(screen, (255, 0, 0), button_1)
pygame.draw.rect(screen, (255, 0, 0), button_2)
draw_text('Alien Destroyer', font2, (0,0,0), screen, 52, 110)
draw_text('Show high scores', font3, (0,0,0), screen, 52, 206)
draw_text('for Alien Destroyer', font3, (0,0,0), screen, 52, 230)
click = False
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_ESCAPE:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
# game loop
def game():
global dx
global dy
global adx
global ady
global bdx
global bdy
global playerY
global playerX
global alienX
global alienY
global bulletY
global bulletX
global visibility
global score
running = True
while running:
clock.tick(60)
screen.fill((0, 0, 0))
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dx = -1
if event.key == pygame.K_RIGHT:
dx = 1
if event.key == pygame.K_SPACE:
pygame.mixer.music.load('laser.wav')
pygame.mixer.music.play()
bulletX = playerX
shoot(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
dx = 0
playerX += dx
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
for i in range(no_of_aliens):
if alienY[i] > 440:
for j in range(no_of_aliens):
alienY[j] = 2000
game_over_text()
break
alienX[i] += adx[i]
if alienX[i] <= 0:
adx[i] = 0.3
alienY[i] += ady[i]
elif alienX[i] >= 736:
adx[i] = -0.3
alienY[i] += ady[i]
death = collide(bulletX, bulletY, alienX[i], alienY[i])
if death:
pygame.mixer.music.load('explosion.wav')
pygame.mixer.music.play()
bulletY = 480
visibility = False
score += 1
alienX[i] = random.randint(0, 735)
alienY[i] = random.randint(30, 130)
alien(alienX[i], alienY[i], i)
if bulletY <= 0:
bulletY = 480
visibility = False
if visibility is True:
shoot(bulletX, bulletY)
bulletY -= bdy
showscore(10, 10)
player(playerX, playerY)
pygame.display.update()
EnterUser()
The problem is that you are calling pygame.event.get() multiple times (Lines: 89, 174, 208). This causes different events queues to disagree and causes problems. There is an easy fix.
In you main application loop, call pygame.event.get() once.
def game:
while running:
#omitted code
events = pygame.event.get()
for event in events:
#...
Then, you can pass events variable to other functions as an argument.
Related
I am confused on how I add gravity to my platformer game. I am using pygame for this project. I am relatively new to coding, but anyways here's my code.
import pygame
pygame.init()
win = pygame.display.set_mode((800, 500))
pygame.display.set_caption("Platformer")
x = 200
y = 200
width = 20
height = 20
vel = 5
run = True
FPS = 30
fpsClock = pygame.time.Clock()
while run:
pygame.time.delay(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and x > 0:
x -= vel
if keys[pygame.K_d] and x < 800 - width:
x += vel
if keys[pygame.K_w] and y > 0:
y -= vel
if keys[pygame.K_s] and y < 500 - height:
y += vel
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.display.update()
fpsClock.tick(FPS)
I hope someone can help me get some sort of gravity function working, anything helps. (also what is the best way to make pixelated art, not very relevant to the question)
Gravity just means that the object is moved down a little in each frame:
gravity = 3
while run:
# [...]
y += gravity
if y > win.get_height() - 20:
y = win.get_height() - 20
I suggest to use a pygame.Rect object to represent the player:
import pygame
pygame.init()
win = pygame.display.set_mode((800, 500))
pygame.display.set_caption("Platformer")
player = pygame.Rect(200, 200, 20, 20)
vel = 5
gravity = 3
run = True
FPS = 30
fpsClock = pygame.time.Clock()
while run:
fpsClock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
player.x += (keys[pygame.K_d] - keys[pygame.K_a]) * vel
if player.left < 0:
player.left = 0
if player.right > win.get_width():
player.right = win.get_width()
player.y += gravity
if player.bottom > win.get_height():
player.bottom = win.get_height()
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), player)
pygame.display.update()
pygame.quit()
I want to display text on the text box that says if I hit and how much damage I do and vice versa for the enemy, but I just can't figure out how to make the text to display in this manner.
Here is the code I'm working on:
def textBox(textv):
lText = []
text = font.render(str(textv),True,(1,1,1))
lText.append(text)
if len(lText) >= 10:
lText.pop(9)
screen.blit(lText[0],(20,400))
screen.blit(lText[1],(20,380))
while True:
battle_screen()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.blit(enemy_background,(20,20))
player.drawPlayer()
enemy.newEnemy()
textBox("Daniel")
textBox("Jenny")
pygame.display.update()
Rendere the text an add the rendered text into a list:
text_surf_list = []
text_surf = font.render("Daniel", True, (255, 255, 0))
text_surf_list.append(text_surf)
text_surf = font.render("Jenny", True, (255, 255, 0))
text_surf_list.append(text_surf)
Define a rectangular area for the text box:
text_box_rect = pygame.Rect(20, 20, 250, 360)
Iterate through list in reversed order. Draw the text from the bottom up. Remove the text from the list if it is not in the box (see How to remove items from a list while iterating?):
text_y = box_rect.bottom - font.get_height()
for text_surf in reversed(text_surf_list[:]):
if text_y <= box_rect.top:
text_surf_list.remove(text_surf)
else:
surf.blit(text_surf, (box_rect.left + 10, text_y))
text_y -= font.get_height()
Set a temporary clipping area while drawing the text box withpygame.Surface.set_clip:
# set clipping
surf.set_clip(box_rect)
# draw text box
# [...]
# disable clipping
surf.set_clip(None)
Minimal example:
import pygame, random
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
def draw_scroll_text_box(surf, font, box_rect, text_surf_list):
surf.set_clip(box_rect)
text_y = box_rect.bottom - font.get_height() - 10
for text_surf in reversed(text_surf_list[:]):
if text_y <= box_rect.top:
text_surf_list.remove(text_surf)
else:
surf.blit(text_surf, (box_rect.left + 10, text_y))
text_y -= font.get_height()
pygame.draw.rect(surf, (164, 164, 164), box_rect, 5)
surf.set_clip(None)
font = pygame.font.SysFont(None, 50)
text_box_rect = pygame.Rect(20, 20, 250, 360)
text_surf_list = []
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, 200)
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *background.get_size(), (32, 32, 32), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
[pygame.draw.rect(background, color, rect) for rect, color in tiles]
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == timer_event:
names = ["Daniel", "Jenny", "Patrick", "Sandy", "Bob"]
text_surf = font.render(random.choice(names), True, (255, 255, 0))
text_surf_list.append(text_surf)
window.blit(background, (0, 0))
draw_scroll_text_box(window, font, text_box_rect, text_surf_list)
pygame.display.flip()
clock.tick(60)
pygame.quit()
exit()
So I was cleaning up my code by adding in classes, in order to put certain tools that I will be using in my game, into other files. SO as I was kinda learning and implementing, I stumbled upon an easy error that I can't find out for the life of me.
So I have my core.py and pyWMouse.py in the same folder. My pyWMouse.py just has my mouse tools that I created. I keep getting this error:
Traceback (most recent call last):
File "G:/Python/pygameDevelopment/core.py", line 115, in <module>
game_Loop()
File "G:/Python/pygameDevelopment/core.py", line 100, in game_Loop
if userMouse.MouseLeftClickDown and userMouse.MouseDrag:
AttributeError: type object 'MouseTools' has no attribute 'MouseLeftClickDown'
Here is the class in pyWMouse.py
import pygame
COLOR_RED = (255, 0, 0)
class MouseTools:
def __init__(self):
self.MouseInitXY = (0, 0)
self.MouseFinalXY = (0, 0)
self.MouseLeftClickDown = False
self.MouseRightClickDown = False
self.MouseDrag = False
self.CharacterSelected = False
self.CharacterMove = False
self.CharacterMoveTo = (0, 0)
def selection(self, screen, unitX, unitY):
# Draw lines #
pygame.draw.lines(screen, COLOR_RED, True, ((self.MouseInitXY[0], self.MouseInitXY[1]),
(self.MouseFinalXY[0], self.MouseInitXY[1]),
(self.MouseFinalXY[0], self.MouseFinalXY[1]),
(self.MouseInitXY[0], self.MouseFinalXY[1])), 3)
# Check if anything is inside the selection area from any direction the mouse highlights #
if unitX >= self.MouseInitXY[0] and unitX <= self.MouseFinalXY[0] and unitY >= \
self.MouseInitXY[1] and unitY <= self.MouseFinalXY[1]:
return True
elif unitX <= self.MouseInitXY[0] and unitX >= self.MouseFinalXY[0] and unitY <= \
self.MouseInitXY[1] and unitY >= self.MouseFinalXY[1]:
return True
elif unitX >= self.MouseInitXY[0] and unitX <= self.MouseFinalXY[0] and unitY <= \
self.MouseInitXY[1] and unitY >= self.MouseFinalXY[1]:
return True
elif unitX <= self.MouseInitXY[0] and unitX >= self.MouseFinalXY[0] and unitY >= \
self.MouseInitXY[1] and unitY <= self.MouseFinalXY[1]:
return True
else:
return False
And finally my core.py
import pygame
import pyWMouse
pygame.init()
pygame.display.set_caption('PyWorld')
DISPLAY_WIDTH = 1080
DISPLAY_HEIGHT = 920
COLOR_BLACK = (0, 0, 0)
COLOR_BROWN = (100, 50, 0)
COLOR_GREEN = (0, 102, 0)
COLOR_RED = (255, 0, 0)
COLOR_WHITE = (255, 255, 255)
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
fpsClock = pygame.time.Clock()
class Character:
def __init__(self, XPos, YPos): # Always called when object is created, always have self variable #
self.X = XPos
self.Y = YPos
self.ImageUnselected = pygame.image.load('mainChar.png')
self.ImageSelected = pygame.image.load('mainCharSelected.png')
self.Speed = 2.5
self.YChange = 0
self.XChange = 0
def render_Unselected(self):
screen.blit(self.ImageUnselected, (self.X, self.Y))
def render_Selected(self):
screen.blit(self.ImageSelected, (self.X, self.Y))
class Worker:
def __init__(self, XPos, YPos):
self.X = XPos
self.Y = YPos
self.ImageUnselected = pygame.image.load('worker.png')
self.ImageSelected = pygame.image.load('workerSelected.png')
def worker_Unselected(self):
screen.blit(self.ImageUnselected, (self.X, self.Y))
def worker_Selected(self):
screen.blit(self.ImageSelected, (self.X, self.Y))
character = Character(DISPLAY_WIDTH/2, DISPLAY_HEIGHT/2)
userMouse = pyWMouse.MouseTools
def game_Loop():
gameExit = False
while not gameExit:
screen.fill(COLOR_BROWN)
# Keyboard Handling #
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_w]:
character.YChange = -character.Speed
if keys_pressed[pygame.K_a]:
character.XChange = -character.Speed
if keys_pressed[pygame.K_s]:
character.YChange = character.Speed
if keys_pressed[pygame.K_d]:
character.XChange = character.Speed
if keys_pressed[pygame.K_w] and keys_pressed[pygame.K_a]:
character.XChange = (-character.Speed/1.5)
character.YChange = (-character.Speed/1.5)
if keys_pressed[pygame.K_a] and keys_pressed[pygame.K_s]:
character.XChange = (-character.Speed / 1.5)
character.YChange = (character.Speed / 1.5)
if keys_pressed[pygame.K_s] and keys_pressed[pygame.K_d]:
character.XChange = (character.Speed / 1.5)
character.YChange = (character.Speed / 1.5)
if keys_pressed[pygame.K_d] and keys_pressed[pygame.K_w]:
character.XChange = (character.Speed / 1.5)
character.YChange = (-character.Speed / 1.5)
# Event handling #
for event in pygame.event.get():
if event.type == pygame.KEYUP:
if event.key != pygame.K_a or event.key != pygame.K_d:
character.XChange = 0
if event.key != pygame.K_w or event.key != pygame.K_s:
character.YChange = 0
# Mouse Handling #
if event.type == pygame.MOUSEBUTTONDOWN:
if userMouse.CharacterSelected:
userMouse.CharacterSelected = False
if event.button == 1:
userMouse.MouseLeftClickDown = True
userMouse.MouseInitXY = pygame.mouse.get_pos()
if event.button == 2:
userMouse.MouseRightClickDown = True
userMouse.CharacterMoveTo = pygame.mouse.get_pos()
if event.type == pygame.MOUSEMOTION:
userMouse.MouseDrag = True
if event.type == pygame.MOUSEBUTTONUP:
if userMouse.MouseLeftClickDown:
userMouse.MouseLeftClickDown = False
userMouse.MouseDrag = False
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Mouse Tools #
if userMouse.MouseLeftClickDown and userMouse.MouseDrag:
userMouse.MouseFinalXY = pygame.mouse.get_pos()
# Check if user's character is inside selection tool #
if userMouse.selection(screen, character.X, character.Y):
character.render_Selected()
else:
character.render_Unselected()
else:
character.render_Unselected()
# Update Display and next frame variables #
character.X += character.XChange
character.Y += character.YChange
pygame.display.update()
fpsClock.tick(144)
game_Loop()
pygame.quit()
quit()
Thanks for your time everyone. Much appreciated.
I believe the problem can be found in core.py. Try changing :
userMouse = pyWMouse.MouseTools
to the following:
userMouse = pyWMouse.MouseTools()
Adding the missing parentheses should do the trick.
I'm trying to make piano tiles in python using pygame. So, I've started with making an intro window but I'm unable to upload a background image1 in my into window. I actually want to display the name 'Piano tiles' and the background image whenever the player starts the game. Here's my code:
import pygame,os,random,time
from pygame.locals import *
wix=800
wiy=800
pygame.init()
white=(255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)
clock = pygame.time.Clock()
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 100)
gameDisplay=pygame.display.set_mode((wix,wiy))
bg = pygame.image.load("background.jpg")
pygame.display.set_caption("Piano Tiles")
def game_intro():
screen=pygame.display.set_mode((wix,wiy))
intro =True
while intro:
bg = pygame.image.load("background.jpg")
screen.blit(bg,(0,0))
gameDisplay.fill(white)
message_to_screen("PIANO TILES",black,-100,"large")
pygame.display.update()
clock.tick(8)
def text_objects(text,color,size):
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def message_to_screen(msg,color, y_displace=0, size = "small"):
textSurf, textRect = text_objects(msg,color, size)
textRect.center = (wix/ 2), (wiy / 2)+y_displace
gameDisplay.blit(textSurf, textRect)
game_intro()
pygame.time.wait(4000)
pygame.quit()
quit()
You have to use fill(white) before you blit anything because it clear screen.
It could look like this
import pygame
# --- constants --- (UPPER_CASE names)
WIX = 800
WIY = 800
WHITE = (255,255,255)
BLACK = ( 0, 0, 0)
RED = (255, 0, 0)
GREEN = ( 0,155, 0)
FPS = 8
# --- functions --- (lower_case names)
def text_objects(text, color, size):
if size == "small":
text_font = small_font
elif size == "medium":
font = med_font
elif size == "large":
font = large_font
#fonts = {"small": small_font, "medium": med_font, "large": large_font}
#font = fonts[size]
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
return text_surface, text_rect
def message_to_screen(screen, msg, color, y_displace=0, size="small"):
text_surface, text_rect = text_objects(msg, color, size)
text_rect.center = screen.get_rect().center
text_rect.y += y_displace
screen.blit(text_surface, text_rect)
def game_intro(screen, text):
#bg = pygame.image.load("background.jpg")
screen.fill(WHITE) # use if background is smaller then screen
screen.blit(bg, (0,0))
message_to_screen(screen, text, BLACK, -100, "large")
message_to_screen(screen, text, BLACK, 0, "large")
message_to_screen(screen, text, BLACK, 100, "large")
pygame.display.update()
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False # exit program
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return True # go to next stage
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
return True # go to next stage
clock.tick(FPS)
# --- main --- (lower_case names)
# - init -
pygame.init()
screen = pygame.display.set_mode((WIX, WIY))
#screen_rect = screen.get_rect()
pygame.display.set_caption("Piano Tiles")
# - resources -
bg = pygame.image.load("Obrazy/test.png")#"background.jpg")
small_font = pygame.font.SysFont("comicsansms", 25)
med_font = pygame.font.SysFont("comicsansms", 50)
large_font = pygame.font.SysFont("comicsansms", 100)
#fonts = {"small": small_font, "medium": med_font, "large": large_font}
# - stages -
go_next = game_intro(screen, "HELLO WORLD")
if go_next:
go_next = game_intro(screen, "PIANO TILES")
if go_next:
go_next = game_intro(screen, "BYE, BYE")
# - exit -
pygame.quit()
I'm a student and this game is one of my task. when the player win or loose, pressanykeytostart() doesn't work. however in the beginning it works. Also I get this error massage (Pygame Error: Video System not Initialized) every time I play.
How can I add a Pause function in my game?
###########################Set up the screen, background image and sound
import random,pygame,sys,math
pygame.init()
from pygame.locals import*
WIDTH = 600
HEIGHT = 600
TEXTCOLOR = (255, 255, 255)
Yellow = (255, 255, 0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Pacman')
pygame.mouse.set_visible(False)
background_image = pygame.image.load('leaves.jpg')
backgroundmusic = pygame.mixer.Sound('lost.wav')
backgroundmusic.play()
##################################################Set up the score font
font_name = pygame.font.match_font('arial')
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, Yellow)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
###################################################SET UP the images and Sound
pacman = pygame.sprite.Sprite()
ghost = pygame.sprite.Sprite()
eatingsound = pygame.mixer.Sound('pacman_eatfruit.wav')
pacman.image = pygame.image.load('pacman1.png')
pacman.rect = pacman.image.get_rect()
pacman_group = pygame.sprite.GroupSingle(pacman)
over_image = pygame.image.load('game.jpg')
deathsound = pygame.mixer.Sound('pacman_death.wav')
##################################################press a key to start
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
return
def drawText(text, font, surface, x, y):
screen.blit(background_image, (0,0))
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
screen.blit(textobj, textrect)
font = pygame.font.SysFont(None, 48)
drawText('Pacman Game', font, screen, (WIDTH / 3), (HEIGHT / 3))
drawText('Press a key to start.', font, screen, (WIDTH / 3) - 30, (HEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
######################################Adding Ghost in different position with different speed
class Ghost(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('ghost.png')
self.rect = self.image.get_rect()
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
all_sprites = pygame.sprite.Group()
ghosts = pygame.sprite.Group()
for i in range(2):
g = Ghost()
all_sprites.add(g)
ghosts.add(g)
#################################################### Adding the Coins
TILE_SIZE = pacman.rect.width
NUM_TILES_WIDTH = WIDTH / TILE_SIZE
NUM_TILES_HEIGHT = HEIGHT / TILE_SIZE
candies = pygame.sprite.OrderedUpdates()
for i in range(50):
candy = pygame.sprite.Sprite()
candy.image = pygame.image.load('coin.png')
candy.rect = candy.image.get_rect()
candy.rect.left = random.uniform(0, NUM_TILES_WIDTH - 1) * TILE_SIZE
candy.rect.top = random.uniform(0, NUM_TILES_HEIGHT - 1) * TILE_SIZE
candies.add(candy)
###########################################Game Loop
score = 0
pause = False
gameOver = False
running = True
win = False
while running :
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
if event.type == pygame.QUIT:
running = False
###########################################Move the pacman
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
pacman.rect.top -= TILE_SIZE
elif event.key == pygame.K_DOWN:
pacman.rect.top += TILE_SIZE
elif event.key == pygame.K_RIGHT:
pacman.rect.right += TILE_SIZE
elif event.key == pygame.K_LEFT:
pacman.rect.right -= TILE_SIZE
##############################################Keep the pacman on the screen
if pacman.rect.left < 0:
pacman.rect.left = 0
elif pacman.rect.right > 600:
pacman.rect.right = 600
elif pacman.rect.top <= 0:
pacman.rect.top = 0
elif pacman.rect.bottom >= 600:
pacman.rect.bottom = 600
###############################################Able to use mouse
if event.type == MOUSEMOTION:
pacman.rect.move_ip(event.pos[0] - pacman.rect.centerx, event.pos[1] - pacman.rect.centery)
###############################################Adding coins randomly
if event.type == pygame.USEREVENT:
if win == False:
candy = pygame.sprite.Sprite()
candy.image = pygame.image.load('coin.png')
candy.rect = candy.image.get_rect()
candy.rect.left = random.uniform(0, NUM_TILES_WIDTH - 1) * TILE_SIZE
candy.rect.top = random.uniform(0, NUM_TILES_HEIGHT - 1) * TILE_SIZE
candies.add(candy)
################################################Collecting the coins and set the score
collides = pygame.sprite.groupcollide(pacman_group, candies, False, True)
if len(collides) > 0:
eatingsound.play()
score += 1
if len(candies) == 0:
win = True
screen.blit(background_image, (0,0))
#################################################Wining the game
if win:
drawText('You Win!', font, screen, (WIDTH / 3) - 30, (HEIGHT / 3) + 50)
pygame.display.update()
winingsound = pygame.mixer.Sound('applause3.wav')
winingsound.play()
backgroundmusic.stop()
waitForPlayerToPressKey()
##################################################################### Game Over screen
candies.draw(screen)
pacman_group.draw(screen)
all_sprites.draw(screen)
draw_text(screen, str(score), 18, WIDTH / 2, 10)
pygame.display.flip()
all_sprites.update()
hits = pygame.sprite.spritecollide(pacman, ghosts, False)
if hits:
gameOver = True
if gameOver == True:
drawText('Game Over!', font, screen, (WIDTH / 3) - 30, (HEIGHT / 3) + 50)
drawText('Press a key to start again.', font, screen, (WIDTH / 3) - 30, (HEIGHT / 3) + 50)
pygame.display.update()
deathsound.play()
backgroundmusic.stop()
waitForPlayerToPressKey()
#############################################Drwing everything on the screen
pygame.quit()
Try with pygame.time.wait(time)
Or Pygame.event.wait (). The first wait the amount of time in brakets, and the second wait until a new event received.