Keyboard Event - Pygame - events

Does anyone know how I can make it so my code only fires a bullet if the space bar is pressed? Right now any key makes my character shoot a bullet but I want to change it if possible, heres my code so far:
import pygame, sys, random
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode([screen_width, screen_height])
all_sprites_list = pygame.sprite.Group()
block_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
background = pygame.image.load('space.jpg')
pygame.display.set_caption("Alien Invasion!")
explosion = pygame.mixer.Sound('explosion.wav')
score = 0
class Block(pygame.sprite.Sprite):
def __init__(self, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("spaceship.png")
self.rect = self.image.get_rect()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.x=0
self.y=0
self.image = pygame.image.load("alien.png")
self.rect = self.image.get_rect()
def update(self):
pos = pygame.mouse.get_pos()
self.rect.x = pos[0]
def render(self):
if (self.currentImage==0):
screen.blit(self.image, (self.x, self.y))
class Bullet(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("bullet.png")
self.rect = self.image.get_rect()
def update(self):
self.rect.y -= 3
for i in range(30):
block = Block(BLACK)
block.rect.x = random.randrange(screen_width)
block.rect.y = random.randrange(330)
block_list.add(block)
all_sprites_list.add(block)
player = Player()
all_sprites_list.add(player)
done = False
clock = pygame.time.Clock()
player.rect.y = 480
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
bullet = Bullet()
bullet.rect.x = player.rect.x
bullet.rect.y = player.rect.y
all_sprites_list.add(bullet)
bullet_list.add(bullet)
all_sprites_list.update()
for bullet in bullet_list:
block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
for block in block_hit_list:
explosion.play()
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
score += 10
if bullet.rect.y < -10:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, WHITE)
textpos = text.get_rect(centerx=screen.get_width()/12)
screen.blit(background, (0,0))
screen.blit(text, textpos)
all_sprites_list.draw(screen)
pygame.display.update()
clock.tick(80)
pygame.quit()
Also, if possible, I want to make it so that once the escape key is pressed, the game exits. For this I have this code:
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
However it doesnt seem to work properly for some reason :( Im new to python so any help would be appreciated!

Right! So first things first!
To fire bullets by pressing the space bar you would need to add this:
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
bullet = Bullet()
bullet.rect.x = player.rect.x
bullet.rect.y = player.rect.y
all_sprites_list.add(bullet)
bullet_list.add(bullet)
The above solution will spawn bullets by pressing the space key
If you would like to fire a single bullet by pressing the space key then you would need
to create a k_space variable that would be set to True on the above event and would be set to False at the end of the loop.
So to do the above you would have to change some stuff :)
k_space = False #---- Initialize the boolean for the space key here
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
k_space = True #----- Set it to true here
if k_space: #---- create a bullet when the k_space variable is set to True
bullet = Bullet()
bullet.rect.x = player.rect.x
bullet.rect.y = player.rect.y
all_sprites_list.add(bullet)
bullet_list.add(bullet)
k_space = False #------ Reset it here
all_sprites_list.update()
for bullet in bullet_list:
block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)
for block in block_hit_list:
explosion.play()
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
score += 10
if bullet.rect.y < -10:
bullet_list.remove(bullet)
all_sprites_list.remove(bullet)
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, WHITE)
textpos = text.get_rect(centerx=screen.get_width()/12)
screen.blit(background, (0,0))
screen.blit(text, textpos)
all_sprites_list.draw(screen)
pygame.display.update()
clock.tick(80)
Changing the above code would make only one bullet spawn per space bar press!
If you would like multiple bullets to spawn by pressing the space bar just stick to the first change I proposed :)
Finally if you want the program to close by pressing the escape key then you would just have to change the first event in your loop:
Instead of that:
if event.type == pygame.QUIT:
done = True
You could just change it to:
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
done = True
And that should exit your program safely:)
Hope that helped!
Cheers,
Alex
(EDIT)
Allright! just split the two quit events and it should work smoothly :)
#code above
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
#code below
Lastly :) if you want the bullets to spawn exactly from the middle of the spaceship,
just add this code in the k_space check:
if k_space:
bullet = Bullet()
bullet.rect.x = player.rect.center[0] - bullet.rect.width/2
bullet.rect.y = player.rect.center[1] - bullet.rect.height/2
all_sprites_list.add(bullet)
bullet_list.add(bullet)
Phew! Hope that helped mate:)
Cheers!

Related

one click animations with lua in LOVE

I have recently been familiar with lua in LOVE 2D and watched some tutorials and now am trying to make a simple game. The game will feature a character who can run and when pressed 'space', attack(strike with his sword). When pressed 'space', it should go through all the frames/sprites of attacking animation. But the character is not going through all the frames and the interval between them seems really fast even though I kept it minimum.
This is the code I am using to account for the key pressing.
self.animations = {
['idle'] = Animation{
frames = {
self.frames[1]
},
interval = 1
},
['attack'] = Animation{
frames = {
self.frames[1], self.frames[2], self.frames[3], self.frames[4], self.frames[5], self.frames[6], self.frames[3]
},
interval = 0.25
}
}
self.animation = self.animations['idle']
self.currentFrame = self.animation:getCurrentFrame()
self.behaviors = {
['idle'] = function(dt)
if love.keyboard.wasPressed('space') then
self.dy = 0
self.state = 'attack'
self.animation = self.animations['attack']
elseif love.keyboard.wasPressed('up') then
self.dy = -MOVE_DIST
elseif love.keyboard.wasPressed('down') then
self.dy = MOVE_DIST
else
self.dy = 0
end
end,
['attack'] = function(dt)
self.animation = self.animations['attack']
if love.keyboard.wasPressed('up') then
self.dy = -MOVE_DIST
elseif love.keyboard.wasPressed('down') then
self.dy = MOVE_DIST
else
self.dy = 0
self.state = 'idle'
self.animation = self.animations['idle']
end
end
This is my animation class that's responsible for transition effects
Animation = Class{}
function Animation:init(params)
--self.texture = params.texture
self.frames = params.frames
self.interval = params.interval or 0.05
self.timer = 0
self.currentFrame = 1
end
function Animation:getCurrentFrame()
return self.frames[self.currentFrame]
end
function Animation:restart()
self.timer = 0
self.currentFrame = 1
end
function Animation:update(dt)
self.timer = self.timer + dt
if #self.frames == 1 then
return self.currentFrame
else
while self.timer > self.interval do
self.timer = self.timer - self.interval
self.currentFrame = (self.currentFrame + 1) % (#self.frames + 1)
if self.currentFrame == 0 then
self.currentFrame = 1
end
end
end
end
Please help. I hope I asked the question correctly. Thanks in advance.
Don't really know how you deal with the state in the key pressing code but this could be part of the issue too.
Anyway, your Animation:update looks very weird to me and I really think this is the center of the problem. There is a simple function that you could use instead and it should work perfectly (if you have any question about it feel free to ask).
If your not really comfortable with a debugger you could use love.graphics.print to print some value to the screen (like self.currentFrame or self.timer in that case) to see what's going on with those value in real time.
function Animation:update(dt)
self.timer = self.timer + dt/self.interval
if self.timer >= #self.frames then
self.timer = 0
end
self.currentFrame = Math.floor(self.timer)+1
end
Also note that "Math.floor(self.timer)+1" cannot be replaced by "Math.ceil(self.timer)" because it will return 0 if self.timer == 0 (and lua's array starts at one)
Edit:
It could probably come from here:
['attack'] = function(dt)
self.animation = self.animations['attack']
if love.keyboard.wasPressed('up') then
self.dy = -MOVE_DIST
elseif love.keyboard.wasPressed('down') then
self.dy = MOVE_DIST
else
self.dy = 0
self.state = 'idle'
self.animation = self.animations['idle']
end
end
I don't know how you deal with your inputs since 'love.keyboard.wasPressed' if not a love function but if 'up' and 'down' where not pressed the last frame, the state will go back to 'idle' and the animation to animations['idle']
Without more code I cannot do much more for you.

wxPython: onPaint event not called on panel update

The following code is supposed to create a window consisting of a "calibrate" button and a canvas. When the "calibrate" button is clicked, the red dot is supposed to be re-drawn on a random location on the canvas.
Instead, I see the OnPaint event is called once, in the beginning, and not afterwards. Any idea what's going on?
import wx
import datetime
import threading
import random
class frmMain ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 839,553 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.pos = (300,100)
self.initGUI()
def initGUI(self):
self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize )
topSizer = wx.BoxSizer( wx.HORIZONTAL )
buttonsSizer = wx.BoxSizer( wx.VERTICAL )
self.btnCalibrate = wx.Button( self, wx.ID_ANY, u"Calibrate", wx.DefaultPosition, wx.DefaultSize, 0 )
buttonsSizer.Add( self.btnCalibrate, 0, wx.ALL, 5 )
topSizer.Add( buttonsSizer, 0, wx.LEFT, 5 )
sizeCanvas = wx.BoxSizer( wx.VERTICAL )
sizeCanvas.SetMinSize( wx.Size( 600,600 ) )
self.panel=wx.Panel(self, size=(600,600))
self.panel.SetBackgroundColour('white')
self.firstpoint=wx.Point(300,300)
self.secondpoint=wx.Point(400,400)
self.panel.Bind(wx.EVT_PAINT, self.onPaint)
sizeCanvas.Add(self.panel, 0, wx.ALIGN_LEFT, 5)
topSizer.Add( sizeCanvas, 1, wx.ALIGN_RIGHT, 5 )
self.SetSizer( topSizer )
self.Layout()
self.Centre( wx.BOTH )
# Connect Events
self.btnCalibrate.Bind( wx.EVT_BUTTON, self.StartCalibrate )
self.Show(True)
def onPaint(self,event):
print "lalal"
dc = wx.WindowDC(self.panel)
color = wx.Colour(255,0,0)
b = wx.Brush(color)
dc.SetBrush(b)
dc.DrawCircle(self.pos[0], self.pos[1], 10)
def __del__( self ):
pass
def StartCalibrate( self, event ):
size = self.GetSize()
self.pos = (random.randrange(0, size[0] - 1, 1), random.randrange(0, size[1] - 1, 1))
print "fixation at %d, %d" % (self.pos[0], self.pos[1])
self.panel.Update()
event.Skip()
if __name__ == "__main__":
app = wx.App()
frmMain(None)
app.MainLoop()
Use Refresh instead of Update. Update causes any pending paint events to be processed immediately, but if there are no pending paint events then nothing will be done. On the other hand, Refresh causes a paint event to be sent to the widget.

Don't see images on my buttons if I create them with a loop

I'm trying to make a program in Python 3.3.0 to train with Tkinter, but when I try to put images on buttons which are created in a loop, I obtain a few buttons that don't work (I can't click on them and they don't have images), and the last one is working and with the image on it. Here there's the code:
elenco = [immagine1, immagine2, immagine3, immagine 4]
class secondWindow:
def __init__(self):
self.secondWindow = Tk()
self.secondWindow.geometry ('500x650+400+30')
class mainWindow:
def __init__(self):
self.mainWindow = Tk()
self.mainWindow.geometry ('1100x650+100+10')
self.mainWindow.title('MainWindow')
def Buttons(self, stringa):
i = 0
for _ in elenco:
if stringa in _.lower():
j = int(i/10)
self.IM = PIL.Image.open (_ + ".jpg")
self.II = PIL.ImageTk.PhotoImage (self.IM)
self.button = Button(text = _, compound = 'top', image = self.II, command = secondWindow).grid(row = j, column = i-j*10)
i += 1
def mainEnter (self):
testoEntry = StringVar()
self.mainEntry = Entry(self.mainWindow, textvariable = testoEntry).place (x = 900, y = 20)
def search ():
testoEntry2 = testoEntry.get()
if testoEntry2 == "":
pass
else:
testoEntry2 = testoEntry2.lower()
mainWindow.Buttons(self, testoEntry2)
self.button4Entry = Button (self.mainWindow, text = 'search', command = search).place (x = 1050, y = 17)
MW = mainWindow()
MW.mainEnter()
mainloop()
If I try to create buttons in a loop without images, they work:
def Buttons(self, stringa):
i = 0
for _ in elenco:
if stringa in _.lower():
j = int(i/10)
self.button = Button(text = _, command = secondWindow).grid(row = j, column = i-j*10)
i += 1
And if I try to create a button with an image but not in a loop, it works too:
im = PIL.Image.open("immagine1.jpg")
ge = PIL.ImageTk.PhotoImage (im)
butt = Button(text = 'immagine', compound = 'top', image = ge, command = secondWindow).grid(row = 0, column = 0)
Let's say you have images named "image-i.png", i=0,..,9.
When I execute the following code (with python 3.5) I obtain ten working buttons with image and text:
from tkinter import Tk, Button, PhotoImage
root = Tk()
images = []
buttons = []
for i in range(10):
im = PhotoImage(master=root, file="image-%i.png" % i)
b = Button(root, text="Button %i" % i, image=im, compound="left",
command=lambda x=i: print(x))
b.grid(row=i)
images.append(im)
buttons.append(b)
root.mainloop()

I cannot animating the sprite, what am I doing wrong?

Anyone can help me. I create some sprite images for a jump animate. But it cannot animated as I want, it only showing the first frame ( I set it for 7 jump frame). Here is my corona code.
function playerJump( event )
if event.phase == "ended" then
if doubleJump == false then
player:setLinearVelocity( 0, 0 )
player:applyForce(0,-30, player.x, player.y)
player:setSequence("jump")
jumpChannel = audio.play(jumpSound)
end
if singleJump == false then singleJump = true
else doubleJump = true end
end
return true
end
Then below that function, I generate the sprite
local options =
{
width = 60, height = 100,
numFrames = 33,
sheetContentWidth = 1980,
sheetContentHeight = 100
}
playerSheet = graphics.newImageSheet( "images/playerSprite.png", options)
playerSprite = {
{name="run", frames = {1,3,5,7,9,11,13,15,17,19,21,23,25}, time = 700, loopCount = 0 },
{name="jump", frames = {27,28,29,30,31,32,33}, time = 1000, loopCount = 1 },
}
--Add the jump listener
Runtime:addEventListener("touch", playerJump)
Thankyou very much
Regards
function playerJump( event )
if event.phase == "ended" then
if doubleJump == false then
player:setLinearVelocity( 0, 0 )
player:applyForce(0,-30, player.x, player.y)
player:setSequence("jump")
player:play() --- You have forgot to add this line.
jumpChannel = audio.play(jumpSound)
end
if singleJump == false then singleJump = true
else doubleJump = true end
end
return true
end

Python compiled code crashes

I made this game in python 2.7 and it worked in .py format but when I compiled it with py2exe it suddenly broke. It gave me this error:
"Microsoft Visuak C++ Runtime Library
Runtime Error!
Program C:\Python27\Helmetdodger\Stuffz\main.exe
This application has requested the Runtime to terminate it in an unusual way.
Please contact the program's support team."
The code:
import pygame
import random, sys, os
from pygame.locals import *
WINDOWWIDTH = 1200
WINDOWHEIGHT = 900
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 1
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
def terminate():
pygame.quit()
os.exit(1)
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Helmetdodger')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
# set up images
playerImage1 = pygame.image.load('player1.png')
powerImage = pygame.image.load('power.png')
playerRect = playerImage1.get_rect()
baddieImage1 = pygame.image.load('baddie.png')
baddieImage2 = pygame.image.load('baddie1.png')
baddieImage3 = pygame.image.load('baddie2.png')
baddieImage4 = pygame.image.load('baddie3.png')
baddieImage5 = pygame.image.load('baddie4.png')
baddieImage6 = pygame.image.load('baddie5.png')
baddieImage7 = pygame.image.load('baddie6.png')
baddieImage8 = pygame.image.load('baddie7.png')
baddieImage9 = pygame.image.load('baddie8.png')
baddieImage10 = pygame.image.load('baddie9.png')
baddieImage11 = pygame.image.load('baddie10.png')
baddieImage12 = pygame.image.load('baddie11.png')
baddieImage13 = pygame.image.load('baddie12.png')
baddieImage14 = pygame.image.load('baddie13.png')
baddieImage15 = pygame.image.load('baddie14.png')
baddieImage16 = pygame.image.load('baddie15.png')
baddieImage17 = pygame.image.load('baddie16.png')
baddieImage18 = pygame.image.load('baddie17.png')
baddieImage19 = pygame.image.load('baddie18.png')
baddieImage20 = pygame.image.load('baddie19.png')
baddieImage21 = pygame.image.load('baddie20.png')
baddieImage22 = pygame.image.load('baddie21.png')
baddieImage23 = pygame.image.load('baddie22.png')
baddieImage24 = pygame.image.load('baddie23.png')
baddieImage25 = pygame.image.load('baddie24.png')
baddieImage26 = pygame.image.load('baddie25.png')
baddieImage27 = pygame.image.load('baddie26.png')
baddieImage28 = pygame.image.load('baddie27.png')
baddieImage29 = pygame.image.load('baddie28.png')
baddieImage30 = pygame.image.load('baddie29.png')
baddieImages = [baddieImage1, baddieImage2, baddieImage3, baddieImage4, baddieImage5, baddieImage6, baddieImage7, baddieImage8, baddieImage9, baddieImage10, baddieImage11, baddieImage12, baddieImage13, baddieImage14, baddieImage15, baddieImage16, baddieImage17, baddieImage18, baddieImage19, baddieImage20, baddieImage21, baddieImage22, baddieImage23, baddieImage24, baddieImage25, baddieImage26, baddieImage27, baddieImage28, baddieImage29, baddieImage20]
# show the "Start" screen
drawText('Helmetdodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
#Get highscore
topScore = 0
try:
file = open('hs.txt', "r")
topScore = file.read()
topScore = int(topScore)
file.close()
except:
topScore = 0
while True:
# set up the start of the game
baddies = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
powerCount = 0
while True: # the game loop runs while the game part is playing
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.type == MOUSEMOTION:
# If the mouse moves, move the player where the cursor is.
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieCount = random.randrange(len(baddieImages))
baddieAddCounter = 0
baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(baddieImages[baddieCount], (baddieSize, baddieSize)),
}
baddies.append(newBaddie)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
# Move the mouse cursor to match the player.
pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
# Move the baddies down.
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
# Delete baddies that have fallen past the bottom.
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
# Draw the player's rectangle
windowSurface.blit(playerImage1, playerRect)
# Draw each baddie
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
topScore = score # set new top score
file = open("hs.txt", "w")
score = str(score)
file.write(score)
file.close()
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
My buildscript was incorrect, I found a better buildscript online to use instead
try:
from distutils.core import setup
import py2exe, pygame
from modulefinder import Module
import glob, fnmatch
import sys, os, shutil
import operator
except ImportError, message:
raise SystemExit, "Unable to load module. %s" % message
#hack which fixes the pygame mixer and pygame font
origIsSystemDLL = py2exe.build_exe.isSystemDLL # save the orginal before we edit it
def isSystemDLL(pathname):
# checks if the freetype and ogg dll files are being included
if os.path.basename(pathname).lower() in ("libfreetype-6.dll", "libogg-0.dll","sdl_ttf.dll"): # "sdl_ttf.dll" added by arit.
return 0
return origIsSystemDLL(pathname) # return the orginal function
py2exe.build_exe.isSystemDLL = isSystemDLL # override the default function with this one
class pygame2exe(py2exe.build_exe.py2exe): #This hack make sure that pygame default font is copied: no need to modify code for specifying default font
def copy_extensions(self, extensions):
#Get pygame default font
pygamedir = os.path.split(pygame.base.__file__)[0]
pygame_default_font = os.path.join(pygamedir, pygame.font.get_default_font())
#Add font to list of extension to be copied
extensions.append(Module("pygame.font", pygame_default_font))
py2exe.build_exe.py2exe.copy_extensions(self, extensions)
class BuildExe:
def __init__(self):
#Name of starting + .py
self.script = "raw.py"
#Name of program
self.project_name = "main"
#Project url
self.project_url = "about:none"
#Version of program
self.project_version = "0.0"
#License of the program
self.license = "MyApps License"
#Auhor of program
self.author_name = "Me"
self.author_email = "example#example.com"
self.copyright = "Copyright (c) 2009 Me."
#Description
self.project_description = "MyApps Description"
#Icon file (None will use pygame default icon)
self.icon_file = None
#Extra files/dirs copied to game
self.extra_datas = []
#Extra/excludes python modules
self.extra_modules = []
self.exclude_modules = []
#DLL Excludes
self.exclude_dll = ['']
#python scripts (strings) to be included, seperated by a comma
self.extra_scripts = []
#Zip file name (None will bundle files in exe instead of zip file)
self.zipfile_name = None
#Dist directory
self.dist_dir ='C:\Python27\dist'
## Code from DistUtils tutorial at http://wiki.python.org/moin/Distutils/Tutorial
## Originally borrowed from wxPython's setup and config files
def opj(self, *args):
path = os.path.join(*args)
return os.path.normpath(path)
def find_data_files(self, srcdir, *wildcards, **kw):
# get a list of all files under the srcdir matching wildcards,
# returned in a format to be used for install_data
def walk_helper(arg, dirname, files):
if '.svn' in dirname:
return
names = []
lst, wildcards = arg
for wc in wildcards:
wc_name = self.opj(dirname, wc)
for f in files:
filename = self.opj(dirname, f)
if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):
names.append(filename)
if names:
lst.append( (dirname, names ) )
file_list = []
recursive = kw.get('recursive', True)
if recursive:
os.path.walk(srcdir, walk_helper, (file_list, wildcards))
else:
walk_helper((file_list, wildcards),
srcdir,
[os.path.basename(f) for f in glob.glob(self.opj(srcdir, '*'))])
return file_list
def run(self):
if os.path.isdir(self.dist_dir): #Erase previous destination dir
shutil.rmtree(self.dist_dir)
#Use the default pygame icon, if none given
if self.icon_file == None:
path = os.path.split(pygame.__file__)[0]
self.icon_file = os.path.join(path, 'pygame.ico')
#List all data files to add
extra_datas = []
for data in self.extra_datas:
if os.path.isdir(data):
extra_datas.extend(self.find_data_files(data, '*'))
else:
extra_datas.append(('.', [data]))
setup(
cmdclass = {'py2exe': pygame2exe},
version = self.project_version,
description = self.project_description,
name = self.project_name,
url = self.project_url,
author = self.author_name,
author_email = self.author_email,
license = self.license,
# targets to build
windows = [{
'script': self.script,
'icon_resources': [(0, self.icon_file)],
'copyright': self.copyright
}],
options = {'py2exe': {'optimize': 2, 'bundle_files': 2, 'compressed': True, \
'excludes': self.exclude_modules, 'packages': self.extra_modules, \
'dll_excludes': self.exclude_dll,
'includes': self.extra_scripts} },
zipfile = self.zipfile_name,
data_files = extra_datas,
dist_dir = self.dist_dir
)
if os.path.isdir('build'): #Clean up build dir
shutil.rmtree('build')
if __name__ == '__main__':
if operator.lt(len(sys.argv), 2):
sys.argv.append('py2exe')
BuildExe().run() #Run generation
raw_input("Press any key to continue") #Pause to let user see that things ends

Resources