Related
This question already has answers here:
How do I rotate an image around its center using Pygame?
(6 answers)
Closed 1 year ago.
I'm trying to rotate a sprite 90 degrees whenever the player presses the A and D keys, and I've got that working, but the sprite is always sent to the top left corner of the screen whenever this happens. Can someone shed some light on this? As well as that, I've tried to get a shooting system working with shooting asteroids, by creating an asteroid and appending it to a list, but it seems to become a tuple instead of a pygame rectangle when I try to change the y of it, can someone help with that as well?
import pygame, sys, random
from pygame.locals import *
#Imports pygame, system and random as modules to use later in the code.
#Also imports extra stuff from pygame that contains useful variables.
pygame.init()
mainClock = pygame.time.Clock()
FONT = pygame.font.SysFont(None, 48)
#Initialises pygame, sets up the clock to stop the program running too fast
#And also makes the font (must happen after pygame initialises)
WINDOWWIDTH = 1000
WINDOWHEIGHT = 1000
BACKGROUNDCOLOUR = (255, 255, 255)
TEXTCOLOUR = (0, 0, 0)
FPS = 60
PLAYERSPEED = 5
PLAYERIMAGE = pygame.image.load("images/P1.png")
PLAYERRECT = PLAYERIMAGE.get_rect()
ASTEROIDIMAGE = pygame.image.load("images/asteroid.png")
ASTEROIDRECT = ASTEROIDIMAGE.get_rect()
ASTEROIDMINSIZE = 3
ASTEROIDMAXSIZE = 5
ASTEROIDSPEED = 5
ASTEROIDS = []
#Defining Variables and setting up player sprite
def terminate():
pygame.quit()
sys.exit()
def pendingKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOUR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
#Defining functions, to quit pygame and the system.
#And to wait for the escape key to be pressed to start the terminate function.
#And to wait for the quit event (such as at the end of the game).
#And a function to create text on the screen, such as for the title.
WINDOWSURFACE = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Space Penguin Remastered')
pygame.mouse.set_visible(False)
#Creates the games window, sets the name of the window, and makes the mouse invisible
WINDOWSURFACE.fill(BACKGROUNDCOLOUR)
drawText('Space Penguin Remastered', FONT, WINDOWSURFACE, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start!', FONT, WINDOWSURFACE, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
pendingKey()
#Sets the colour of the background and draws the title and some basic instructions
#And updates the display and activates the terminate function
while True:
LEFT = RIGHT = UP = DOWN = SHOOT = LEFTROTATE = RIGHTROTATE = False
#Sets the players start position to half through the screen, and 50 pixels down
#And sets the movement variables to false
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
#Checks for events, first event being the game quitting
if event.type == KEYDOWN:
if event.key == K_LEFT:
RIGHT = False
LEFT = True
if event.key == K_RIGHT:
LEFT = False
RIGHT = True
if event.key == K_UP:
DOWN = False
UP = True
if event.key == K_DOWN:
UP = False
DOWN = True
if event.key == K_SPACE:
SHOOT = True
if event.key == K_a:
RIGHTROTATE = False
LEFTROTATE = True
if event.key == K_d:
LEFTROTATE = False
RIGHTROTATE = True
#Checks for keys being pressed, corresponding to movement.
if event.key == K_ESCAPE:
terminate()
#Checks for escape being pressed, which quits the game.
if event.type == KEYUP:
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT:
LEFT = False
if event.key == K_RIGHT:
RIGHT = False
if event.key == K_UP:
UP = False
if event.key == K_DOWN:
DOWN = False
if event.key == K_SPACE:
SHOOT = False
if event.key == K_a:
RIGHTROTATE = False
LEFTROTATE = False
if event.key == K_d:
LEFTROTATE = False
RIGHTROTATE = False
#Checks whether keys have been let go of.
if LEFT and PLAYERRECT.left > 0:
PLAYERRECT.move_ip(-1 * PLAYERSPEED, 0)
if RIGHT and PLAYERRECT.right < WINDOWWIDTH:
PLAYERRECT.move_ip(PLAYERSPEED, 0)
if UP and PLAYERRECT.top > 0:
PLAYERRECT.move_ip(0, -1 * PLAYERSPEED)
if DOWN and PLAYERRECT.bottom < WINDOWHEIGHT:
PLAYERRECT.move_ip(0, PLAYERSPEED)
if SHOOT:
ASTEROIDS.append(ASTEROIDIMAGE.get_rect(center=PLAYERRECT.midtop))
if LEFTROTATE:
PLAYERIMAGE = pygame.transform.rotate(PLAYERIMAGE, 90)
PLAYERRECT = PLAYERIMAGE.get_rect()
if RIGHTROTATE:
PLAYERIMAGE = pygame.transform.rotate(PLAYERIMAGE, -90)
PLAYERRECT = PLAYERIMAGE.get_rect()
for asteroid in ASTEROIDS:
asteroid.y -= 4
for asteroid in ASTEROIDS:
WINDOWSURFACE.blit(ASTEROIDIMAGE, asteroid)
#Moves the player a certain number of pixels in a direction and shoots asteroids
WINDOWSURFACE.fill(BACKGROUNDCOLOUR)
WINDOWSURFACE.blit(PLAYERIMAGE, PLAYERRECT)
pygame.display.update()
mainClock.tick(FPS)
#Fills the background, draws the players image on the rectangle
#And updates the screen and selects how many frames per second the game should tick by
Thanks in advance
Note that you should only call pygame.event.get() once in your application.
When you rotate, you set your player rect as such:
PLAYERRECT = PLAYERIMAGE.get_rect()
You have never specified the value of PLAYERIMAGE.get_rect() and it is (0, 0) by default, so if the player is transported to the top left of the screen. To fix that, simply remove it, it serves no purpose.
Also, your movement code can be simplified.
keys = pygame.key.get_pressed()
PLAYERRECT.move_ip
(
(keys[K_RIGHT] - keys[K_LEFT]) * PLAYERSPEED,
(keys[K_DOWN] - keys[K_UP]) * PLAYERSPEED
)
Thats it.
Code to handle rotation can be simplified as well. Make a function that gets the players rotation angle:
def getPlayerRotation(keys):
if keys[K_a]: return 90
elif keys[K_d]: return -90
return 0
Then use that to rotate your image and draw it.
#https://stackoverflow.com/questions/4183208/how-do-i-rotate-an-image-around-its-center-using-pygame
rotated_image = pygame.transform.rotate(PLAYERIMAGE, getPlayerRotation(keys))
new_rect = rotated_image.get_rect(center = PLAYERIMAGE.get_rect(topleft = PLAYERRECT.topleft).center)
WINDOWSURFACE.blit(rotated_image, new_rect)
Your asteroid isn't drawing because you are trying to draw it before you clear the screen, which draws over the asteroids.
Also you cannot do
ASTEROIDS.append(ASTEROIDIMAGE.get_rect(center=PLAYERRECT.midtop))
because there is only one asteroid.rect object, so what you are appending is a reference to the same object over and over. You need to create a new rect if your want to use a rect, but I got around the problem by using a list.
ASTEROIDS.append(list(PLAYERRECT.center))
and then later:
for asteroid in ASTEROIDS:
asteroid[1] -= 4
Lastly I changed pending key function:
def pendingKey(events):
for event in events:
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
It takes events as argument to avoid calling pygame.event.get() in the function. I also removed the return statement at the end of it since it was causing the function to exit before it got to to through all the events.
Here is the new code:
import pygame, sys, random
from pygame.locals import *
WINDOWWIDTH = 1000
WINDOWHEIGHT = 1000
pygame.init()
mainClock = pygame.time.Clock()
FONT = pygame.font.SysFont(None, 48)
BACKGROUNDCOLOUR = (255, 255, 255)
TEXTCOLOUR = (0, 0, 0)
FPS = 60
PLAYERSPEED = 5
PLAYERIMAGE = pygame.image.load("images/P1.png")
PLAYERRECT = PLAYERIMAGE.get_rect()
ASTEROIDIMAGE = pygame.image.load("images/asteroid.png")
ASTEROIDRECT = ASTEROIDIMAGE.get_rect()
ASTEROIDMINSIZE = 3
ASTEROIDMAXSIZE = 5
ASTEROIDSPEED = 5
ASTEROIDS = []
#Defining Variables and setting up player sprite
def terminate():
pygame.quit()
sys.exit()
def pendingKey(events):
for event in events:
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOUR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
WINDOWSURFACE = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Space Penguin Remastered')
pygame.mouse.set_visible(False)
WINDOWSURFACE.fill(BACKGROUNDCOLOUR)
drawText('Space Penguin Remastered', FONT, WINDOWSURFACE, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start!', FONT, WINDOWSURFACE, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
def getPlayerRotation(keys):
if keys[K_a]: return 90
elif keys[K_d]: return -90
return 0
while True:
events = pygame.event.get()
pendingKey(events)
keys = pygame.key.get_pressed()
PLAYERRECT.move_ip((keys[K_RIGHT] - keys[K_LEFT]) * PLAYERSPEED, (keys[K_DOWN] - keys[K_UP]) * PLAYERSPEED)
#https://stackoverflow.com/questions/4183208/how-do-i-rotate-an-image-around-its-center-using-pygame
rotated_image = pygame.transform.rotate(PLAYERIMAGE, getPlayerRotation(keys))
new_rect = rotated_image.get_rect(center = PLAYERIMAGE.get_rect(topleft = PLAYERRECT.topleft).center)
for event in events:
if event.type == KEYDOWN and event.key == K_SPACE:
ASTEROIDS.append(list(PLAYERRECT.center))
for asteroid in ASTEROIDS:
asteroid[1] -= 4
WINDOWSURFACE.fill(BACKGROUNDCOLOUR)
WINDOWSURFACE.blit(rotated_image, new_rect)
for asteroid in ASTEROIDS:
WINDOWSURFACE.blit(ASTEROIDIMAGE, asteroid)
pygame.display.update()
mainClock.tick(FPS)
When we run our pygame's code, our target scope image will NOT move, but our do robots generate. We are trying to use our arrow keys to move them and I included all of our code.
Commented out under our newest trial code for moving are two other things we tried.
import pygame, sys
from graphics import *
import time
import random
pygame.init()
level=1
bg = pygame.image.load('bg.png')
bg_width = 800
pygame.display.set_caption('Robot Apocalypse')
surfacew = 1054
surfacel = 562
surface = pygame.display.set_mode((surfacew,surfacel))
black = (0, 0, 0)
score = 0
#player_health = 99
alive=True
targetImg = pygame.image.load('target.png')
targetImg = pygame.transform.scale(targetImg, (40, 40))
targetxy = targetImg.get_rect()
targetx = targetxy[0]
targety = targetxy[1]
def move_target(targetImg):
pygame.event.clear()
while alive == True:
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT]:
targetx -= 5
if keys_pressed[pygame.K_RIGHT]:
targetx += 5
if keys_pressed[pygame.K_UP]:
targety -= 5
if keys_pressed[pygame.K_DOWN]:
targety += 5
pygame.display.update()
# pygame.event.clear()
# for event in pygame.event.get():
# if event.type ==KEYDOWN:
# if event.key == K_LEFT:
# direction = MOVE_LEFT
# elif event.key == K_RIGHT:
# direction = MOVE_RIGHT
# elif event.type == KEYUP:
# if event.key == K_LEFT:
# direction = 0
# elif event.key == K_RIGHT:
# direction = 0
# if(direction == MOVE_LEFT):
# targetx-=10
# elif(direction == MOVE_RIGHT):
# targetx+=10
# for event in pygame.event.get():
# print(event)
# if event.type==QUIT:
# pygame.quit()
# sys.exit()
# if event.type == KEYDOWN:
# if event.key == K_LEFT:
# targetx-=5
# elif event.key == K_RIGHT:
# targetx+=5
# elif event.key == K_UP:
# targety-=5
# elif event.key == K_DOWN:
# targety+=5
# pygame.display.update()
def shoot():
#while True:
shot = False
pos = (targetx, targety)
t = screen.blit(robot, (64,64))
if t.collidepoint(pos):
shot = True
return shot
def generate_robot(x,y):
#while displayrobot == True
robot=pygame.draw.rect(surface, (255,0,0), (x,y,64,64), 0)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
shoot()
if shot == True:
displayrobot = False
cover = surface.blit(bg, (x,y))
pygame.display.update()
return x, y
#if shot == True:
def die():
message("YOU DIED")
pygame.display.update()
def win(level):
level+=1
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message(text):
largeText = pygame.font.Font('freesansbold.ttf',60)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((surfacew/6),(surfacel/2))
surface.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
def main(alive):
#displayrobot = True:
robot=0
score=0
surface.fill(black)
surface.blit(bg, (0,0))
message("Level "+ str(level))
mouse = pygame.mouse.get_pos()
target = surface.blit(targetImg, (mouse))
while alive==True:
# robot = enemy(64, 64)
x=random.randint(40,760)
y=random.randint(40,560)
generate_robot(x,y)
pygame.display.update()
robot+=1
time.sleep(8/level)
if robot>50 and robot>score:
alive=False
# if pygame.mouse.get_pressed()==True:
# shoot() #maybe??
if shot==True:
score+=1
robot-=1
if robot==10/(level/2): #if 10- robots on screen then...
die()
if score>25*(level/2):
win()
move_target(targetImg)
main(alive)
pygame.quit()
quit()
.
There are no error messages, but it won't move. We've tried a ton of different things (that aren't included) and looked up a lot of websites so please help us. Thanks
To move object you have to not only change x,y and update screen (send buffer to video card which will display it) but also clean buffer, draw image in new place in buffer (blit()).
This code shows only working move_target. I skiped rest of code.
I keep position in target_rect which is pygame.Rect. You can use it to blit(img,rect) but later you can also use to check collision rect.colliderect(other_rect)
import pygame
# --- constants --- (UPPER_CASE_NAMES)
BLACK = (0, 0, 0)
SURFACE_WIDTH = 1054
SURFACE_HEIGHT = 562
# --- functions --- (lower_case_names)
def move_target(target_img, target_rect):
alive = True
clock = pygame.time.Clock()
while alive:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
alive = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
alive = False
# --- updates/changes ---
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT]:
target_rect.x -= 5
if keys_pressed[pygame.K_RIGHT]:
target_rect.x += 5
if keys_pressed[pygame.K_UP]:
target_rect.y -= 5
if keys_pressed[pygame.K_DOWN]:
target_rect.y += 5
# --- draws ---
surface.fill(BLACK)
surface.blit(target_img, target_rect)
pygame.display.update()
# the same game's speed on all computers = 60 FPS
clock.tick(60)
# --- main --- (lower_case_names)
pygame.init()
pygame.display.set_caption('Robot Apocalypse')
surface = pygame.display.set_mode((SURFACE_WIDTH, SURFACE_HEIGHT))
target_img = pygame.image.load('target.png')
target_img = pygame.transform.scale(target_img, (40, 40))
target_rect = target_img.get_rect()
move_target(target_img, target_rect)
pygame.quit()
It looks like my original functional comment is still "in force": your code doesn't move any game object.
targetxy = targetImg.get_rect()
targetx = targetxy[0]
targety = targetxy[1]
At this point, targetxy is a reference to the bounding rectangle for your game object.
targetx and targety are copies of the values of the rect position.
def move_target(targetImg):
pygame.event.clear()
while alive == True:
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT]:
targetx -= 5
...
You've change the local copy of the x-coordinate. This does not affect the position of targetImg. You need to change the object's attributes, such as
targetxy.x -= 5
After this, you need to update the game screen.
I am new to pygame and python, and I am just making a simple "Dodger" game. I have created a main menu with some buttons.
My main menu:
# show the start screen
done=False
while not done:
screen.fill(black)
text_width,text_height=font.size("Dodger")
#a function for drawing text
drawText('Dodger', font, screen, (screen_width / 2-(text_width/2)), (screen_height / 2-200))
font = pygame.font.SysFont(None, 45)
start_button=button(screen_width/2-125,175,250,50,white,black,'Start')
start_button.draw()
instructions_button=button(screen_width/2-125,250,250,50,white,black,'Instructions')
instructions_button.draw()
back_button=button(screen_width/2-125,325,250,50,white,black,'Back')
back_button.draw()
pygame.display.flip()
I also have a button class:
class button(object):
def __init__(self,x,y,width,height,text_color,background_color,text):
self.rect=pygame.Rect(x,y,width,height)
self.image=pygame.draw.rect(screen, background_color,(self.rect),)
self.x=x
self.y=y
self.width=width
self.height=height
self.text=text
self.text_color=text_color
def check(self):
return self.rect.collidepoint(pygame.mouse.get_pos())
def draw(self):
drawText(self.text,font,screen,self.x+self.width/2,self.y+self.height/2,self.text_color)
pygame.draw.rect(screen,self.text_color,self.rect,3)
Two buttons work, but the third one is not responding.
My code looks like this:
#show start screen
done=False
while not done:
screen.fill(black)
text_width,text_height=font.size("Dodger")
drawText('Dodger', font, screen, (screen_width / 2-(text_width/2)), (screen_height / 2-200))
font = pygame.font.SysFont(None, 45)
#the start button starts the game
start_button=button(screen_width/2-125,175,250,50,white,black,'Start')
start_button.draw()
#my button that is not working
instructions_button=button(screen_width/2-125,250,250,50,white,black,'Instructions')
instructions_button.draw()
#go back to game selection
back_button=button(screen_width/2-125,325,250,50,white,black,'Back')
back_button.draw()
pygame.display.flip()
while not done:
for event in pygame.event.get():
if event.type==QUIT:
terminate()
elif event.type == pygame.MOUSEBUTTONDOWN:
if start_button.check()==True:
#main game code
if instructions_button.check()==True:
#show instructions
if back_button.check()==True:
#go back to game selection
However, my "instructions" button is not working, though the other two work.
Code:
elif instructions_button.check()==True:
screen.fill(black)
drawText('some instructions',font,screen,screen_width/2-127.5, 185)
back_button.draw()
done=False
while not done:
for event in pygame.event.get():
if event.type==QUIT:
terminate()
elif back_button.check()==True:
done=True
The problem is that when I click the button, the screen doesn't fill(screen.fill(black) or draw my text (drawText('some instructions',font,screen,screen_width/2-127.5, 185)).
In my attempts to debug it, I placed various print('hello') to see why it wasn't working:
elif instructions_button.check()==True:
print('hello')
screen.fill(black)
print('hello')
drawText('some instructions',font,screen,screen_width/2-127.5, 185)
back_button.draw()
done=False
while not done:
for event in pygame.event.get():
if event.type==QUIT:
terminate()
elif back_button.check()==True:
done=True
It printed but didn't fill the screen with black.
All help is appreciated!
Complete code:
import pygame,sys,os,random
from pygame.locals import *
from cPickle import load
from asyncore import write
#initalize pygame
pygame.init()
#define colors
black=(0,0,0)
white=(255,255,255)
def terminate():
pygame.quit()
sys.exit()
def drawText(text,font,screen,x,y,color):
textobj=font.render(text,True,color)
textrect=textobj.get_rect(center=(x,y))
screen.blit(textobj,textrect)
class button(object):
def __init__(self,x,y,width,height,text_color,background_color,text):
self.rect=pygame.Rect(x,y,width,height)
self.image=pygame.draw.rect(screen, background_color,(self.rect),)
self.x=x
self.y=y
self.width=width
self.height=height
self.text=text
self.text_color=text_color
def check(self):
return self.rect.collidepoint(pygame.mouse.get_pos())
def draw(self):
drawText(self.text,font,screen,self.x+self.width/2,self.y+self.height/2,self.text_color)
pygame.draw.rect(screen,self.text_color,self.rect,3)
def dodger(screen,clock):
global button
#define variables
white=(255,255,255)
black=(0,0,0)
fps=40
baddieminsize=10
baddiemaxsize=40
baddieminspeed=1
baddiemaxspeed=8
addnewbaddierate=6
player_speed=5
def terminate():
pygame.quit()
sys.exit()
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, white)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
def load_hs():
try:
f = open("dodger_hs.txt","rb")
hs = int(f.read())
f.close()
return hs
except:
return 0
def write_hs(hs):
f = open("dodger_hs.txt","wb")
f.write(str(hs).encode())
f.close()
# set up fonts
font = pygame.font.SysFont(None, 90)
# set up images
playerImage = pygame.image.load('player.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('baddie.png')
# show the start screen
done=False
while not done:
screen.fill(black)
text_width,text_height=font.size("Dodger")
drawText('Dodger', font, screen, (screen_width / 2-(text_width/2)), (screen_height / 2-200))
font = pygame.font.SysFont(None, 45)
start_button=button(screen_width/2-125,175,250,50,white,black,'Start')
start_button.draw()
instructions_button=button(screen_width/2-125,250,250,50,white,black,'Instructions')
instructions_button.draw()
back_button=button(screen_width/2-125,325,250,50,white,black,'Back')
back_button.draw()
pygame.display.flip()
while not done:
for event in pygame.event.get():
if event.type==QUIT:
terminate()
elif event.type == pygame.MOUSEBUTTONDOWN:
if start_button.check()==True:
while not done:
# set up the start of the game
baddies = []
score = 0
playerRect.topleft = (screen_width / 2, screen_height- 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
high_score=load_hs()
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
if event.key == ord('x'):
slowCheat = False
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
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == addnewbaddierate:
baddieAddCounter = 0
baddieSize = random.randint(baddieminsize, baddiemaxsize)
newBaddie = {'rect': pygame.Rect(random.randint(0, screen_width-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
'speed': random.randint(baddieminspeed, baddiemaxspeed),
'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)),
}
baddies.append(newBaddie)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * player_speed, 0)
if moveRight and playerRect.right < screen_width:
playerRect.move_ip(player_speed, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * player_speed)
if moveDown and playerRect.bottom < screen_height:
playerRect.move_ip(0, player_speed)
# 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 > screen_height:
baddies.remove(b)
if score>=high_score:
high_score=score
# Draw the game world on the window.
screen.fill(black)
# Draw the player's rectangle
screen.blit(playerImage, playerRect)
# Draw each baddie
for b in baddies:
screen.blit(b['surface'], b['rect'])
# Draw the score
drawText('Score: %s' % (score), font, screen, 10, 0)
drawText('High Score: %s' % (high_score), font, screen, 10, 30)
pygame.display.update()
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, baddies):
break
clock.tick(fps)
write_hs(high_score)
screen.fill(black)
if score<100:
drawText('Your Score: %s' % (score), font,screen,screen_width/2-107.5, 185)
if score<1000 and score>99:
drawText('Your Score: %s' % (score), font,screen,screen_width/2-117.5, 185)
if score<10000 and score>999:
drawText('Your Score: %s' % (score), font,screen,screen_width/2-127.5, 185)
if score<100000 and score>9999:
drawText('Your Score: %s' % (score), font,screen,screen_width/2-127.5, 185)
font = pygame.font.SysFont(None, 90)
text_width,text_height=font.size("Game Over")
drawText('Game Over', font, screen, (screen_width / 2-(text_width/2)), (screen_height / 2-200))
font = pygame.font.SysFont(None, 45)
retry_button=button(screen_width/2-125,250,250,50,white,black,'Retry')
retry_button.draw()
back_button.draw()
pygame.display.flip()
back=False
while not back:
for event in pygame.event.get():
if event.type==QUIT:
terminate()
elif event.type == pygame.MOUSEBUTTONDOWN:
if retry_button.check()==True:
back=True
if back_button.check()==True:
back=True
done=True
elif instructions_button.check()==True:
screen.fill(black)
drawText('Your Score:', font,screen,screen_width/2-127.5, 185)
back_button.draw()
done=False
while not done:
for event in pygame.event.get():
if event.type==QUIT:
terminate()
elif back_button.check()==True:
done=True
elif back_button.check()==True:
done=True
#define other varibles
clock=pygame.time.Clock()
font=pygame.font.SysFont(None,40)
done=False
#set up screen
screen_width=600
screen_height=600
screen=pygame.display.set_mode([screen_width,screen_height])
pygame.display.set_caption('The Arcade')
#set up buttons
dodger_button=button(25,75,125,50,white,black,'Dodger')
#main loop
while not done:
for event in pygame.event.get():
if event.type==QUIT:
terminate()
elif event.type == pygame.MOUSEBUTTONDOWN:
if dodger_button.check():
dodger(screen, clock)
#fill screen with background
screen.fill(black)
#draw buttons
dodger_button.draw()
#draw text
drawText('The Arcade', font, screen, screen_width/2, 25, white)
#change display
pygame.display.flip()
clock.tick(15)
terminate()
Problem is because you didn't use pygame.display.update()
All functions draw in buffer in RAM memory and update()/flip() sends data from buffer in memory to buffer in video card which displays it on screen. It is called "Double Buffering" and it is used as soluton for image flickering/tearing.
BTW: you also forgot MOUSEBUTTONDOWN so button Back is "clicked" when mouse touch button without using mouse button.
Other problem - you use done variable to exit from "instruction" but the same variable control external while loop so it exits from game. You have to use different variable. If you would use this inside function then it wouldn't make problem and code would be better organzied.
You don't have to use ==True to check it.
But you could use spaces around == and after , to make code more readable.
See: PEP 8 -- Style Guide for Python Code
elif instructions_button.check():
screen.fill(black)
drawText('Your Score:', font, screen, screen_width/2-127.5, 185)
back_button.draw()
pygame.display.update() # <-- send to video card
doneX = False # <-- use different variable
while not doneX:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == pygame.MOUSEBUTTONDOWN: # <-- check mouse click
if back_button.check():
doneX = True
You don't have to create two functions drawText() and terminate().
I am trying to make my sprite go to the bottom check to see if it is on a bottom and if it is on the bottom go to the top and check to see if it is on the top then go down and do that in a endless loop. This is the code that i am trying but it does not work, it goes to the bottom and stops.:
if baddieRect.bottom > WINDOWHEIGHT:
baddieRect.move_ip(0, -5)
if baddieRect.bottom < WINDOWHEIGHT:
baddieRect.move_ip(0, 5)
My whole code:
import pygame, random, sys
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BGC = (0, 0, 0)
FPS = 80
PLAYERMOVERATE = 5
countBy = 1
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def playerHasHitShoot(playerRect, shootRect):
if playerRect.colliderect(shootRect):
return True
return False
def baddieHasHitShoot(baddieRect, shootRect):
if baddieRect.colliderect(shootRect):
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)
def fire(shoot):
shootRect.topleft = ((playerRect / 2), 101)
shootRect.move_ip(5, 1)
pygame.init()
pygame.font.init()
font = pygame.font.SysFont(None,48)
mainClock = pygame.time.Clock()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Mothers Day')
pygame.mouse.set_visible(True)
pygame.display.set_icon(pygame.image.load('gameicon.gif'))
icon = pygame.image.load('icon.bmp').convert_alpha()
pygame.display.set_icon(icon)
gameStartSound = pygame.mixer.Sound('gamestart.wav')
gameOverSound = pygame.mixer.Sound('gamestart.wav')
pygame.mixer.music.load('background.wav')
playerImage = pygame.image.load('starship.bmp')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('enemy.bmp')
baddieRect = baddieImage.get_rect()
shootImage = pygame.image.load('shoot.bmp')
shootRect = shootImage.get_rect()
def main():
UPDOWN # if true go up, else go down
while True:
#update the position
if UPDOWN:
baddieRect.move_ip(0, -5)
elif not UPDOWN:
baddieRect.move_ip(0, 5)
# where your code is not quite right
if baddieRect.bottom > WINDOWHEIGHT: #correct
UPDOWN = True
#yours baddieRect.bottom < WINDOWHEIGHT
#mine elif baddieRect.top < 0
elif baddieRect.top < 0: # tests if the 'baddie' hits the top
UPDOWN = False
drawText('Star Trek', font, screen, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, screen, (WINDOWWIDTH / 3.75) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
score = 10000
playerRect.topleft = (0, 100)
baddieRect.topright = (600, 100)
moveUp = moveDown = False
pygame.mixer.music.play(-1, 0.0)
while True:
score -= countBy
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_UP:
moveDown = False
moveUp = True
if event.key == ord(' '):
fire
if event.key == K_DOWN:
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord(' '):
fire
if event.key == K_ESCAPE:
terminate()
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 moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
sb = pygame.image.load('sb.png')
screen.blit(sb, (600, 600))
screen.fill(BGC)
main()
drawText('Score: %s' % (score), font, screen, 10, 0)
drawText('Top Score: %s' % (topScore), font, screen, 10, 40)
screen.blit(playerImage, playerRect)
screen.blit(shootImage, shootRect)
screen.blit(baddieImage, baddieRect)
pygame.display.update()
if playerHasHitShoot(playerRect, shootRect):
score = 0
break
if baddieHasHitShoot(baddieRect, shootRect):
if score > topScore:
score = topscore
break
mainClock.tick(FPS)
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, screen, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
Yeah OK. So the reasoning for this is that you test if it's greater than the bottom, and then you say if it's the bottom to go back up 5. They offset each other, and if you change it to an if else statement you will get this really annoying jittering motion.
In order to fix this you should define a variable called something along the lines of UPDOWN (if Boolean) or DIRECTION (if integer based).
So I'm going to use the Boolean, now you haven't shown much of your code, which is both good and bad, good because you narrowed it down to the exact problem, but bad because I'm not sure exactly where to put it in your code, so I'm going to make my own loop to sort of show how you would use it.
def main():
UPDOWN = False # if true go up, else go down
while True:
#update the position
if UPDOWN:
baddieRect.move_ip(0, -5)
elif not UPDOWN:
baddieRect.move_ip(0, 5)
# where your code is not quite right
if baddieRect.bottom > WINDOWHEIGHT: #correct
UPDOWN = True
#yours baddieRect.bottom < WINDOWHEIGHT
#mine elif baddieRect.top < 0
elif baddieRect.top < 0: # tests if the 'baddie' hits the top
UPDOWN = False
Now why does this work, it tests if your sprite hits the bottom, and if it does it goes, but if it hits the top it goes down. I hope you can see how you went a bit wrong in your if statement. nothing too big, just a minor mistake that I can see how you missed.
Cheers!
------------------EDIT---------------------
So you responded saying that you don't know where to put main The truth of the matter is that main is just a place holder. I just wanted to get the point across that it was in your mainloop. Well I found your main loop and put it in accordingly I have put comments on my edits
import pygame, random, sys
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BGC = (0, 0, 0)
FPS = 80
PLAYERMOVERATE = 5
countBy = 1
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def playerHasHitShoot(playerRect, shootRect):
if playerRect.colliderect(shootRect):
return True
return False
def baddieHasHitShoot(baddieRect, shootRect):
if baddieRect.colliderect(shootRect):
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)
def fire(shoot):
shootRect.topleft = ((playerRect / 2), 101)
shootRect.move_ip(5, 1)
pygame.init()
pygame.font.init()
font = pygame.font.SysFont(None,48)
mainClock = pygame.time.Clock()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Mothers Day')
pygame.mouse.set_visible(True)
pygame.display.set_icon(pygame.image.load('gameicon.gif'))
icon = pygame.image.load('icon.bmp').convert_alpha()
pygame.display.set_icon(icon)
gameStartSound = pygame.mixer.Sound('gamestart.wav')
gameOverSound = pygame.mixer.Sound('gamestart.wav')
pygame.mixer.music.load('background.wav')
playerImage = pygame.image.load('starship.bmp')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('enemy.bmp')
baddieRect = baddieImage.get_rect()
shootImage = pygame.image.load('shoot.bmp')
shootRect = shootImage.get_rect()
drawText('Star Trek', font, screen, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, screen, (WINDOWWIDTH / 3.75) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
score = 10000
playerRect.topleft = (0, 100)
baddieRect.topright = (600, 100)
moveUp = moveDown = False
pygame.mixer.music.play(-1, 0.0)
UPDOWN = False# if true go up, else go down DEFINE UPDOWN
while True:
#I ADDED IN THE BELOW lines. They were just not positioned correctly in your code
#update the position
print ("got here #1")
if UPDOWN:
baddieRect.move_ip(0, -5)
elif not UPDOWN:
baddieRect.move_ip(0, 5)
print ("got here #2")
# where your code is not quite right
if baddieRect.bottom > WINDOWHEIGHT: #correct
UPDOWN = True
#yours baddieRect.bottom < WINDOWHEIGHT
#mine elif baddieRect.top < 0
elif baddieRect.top < 0: # tests if the 'baddie' hits the top
UPDOWN = False
score -= countBy
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_UP:
moveDown = False
moveUp = True
if event.key == ord(' '):
fire
if event.key == K_DOWN:
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord(' '):
fire
if event.key == K_ESCAPE:
terminate()
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 moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
sb = pygame.image.load('sb.png')
screen.blit(sb, (600, 600))
screen.fill(BGC)
#got rid of the next line which is why I commented it out. as main is no longer a function
#main()
drawText('Score: %s' % (score), font, screen, 10, 0)
drawText('Top Score: %s' % (topScore), font, screen, 10, 40)
screen.blit(playerImage, playerRect)
screen.blit(shootImage, shootRect)
screen.blit(baddieImage, baddieRect)
pygame.display.update()
if playerHasHitShoot(playerRect, shootRect):
score = 0
break
if baddieHasHitShoot(baddieRect, shootRect):
if score > topScore:
score = topscore
break
mainClock.tick(FPS)
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, screen, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am new to Python and I have modified dodger (here's the link http://inventwithpython.com/dodger.py) to add ''goodies'', sprites similar to the baddies, but that give you score when you touch them; instead of killing you as the baddies do.
(I have made a change at the start with easygui too, but it works fine).
I am really confused as this code works (I mean this code starts) but the goodies don't appear, like if I didn't put them in at all. I have tried to figure out by myself what the problem is but I haven't found it. The source code is long but there are some comments to make it more readable. I think that the multimedia files are right because it doesn't give me error messages.
Here you have the not working program:
import pygame, random, sys
from pygame.locals import *
import easygui
#Message to make the user decide the hardness of the game
msg = 'Inserisci un numero da 1 a 20\n per la difficoltà: \n1 = Semplice\n 20 = Impossibile'
title = 'Difficoltà'
#Message to make the user decide the colour of the background of the game
Difficoltà = easygui.enterbox(msg,title)
msg = "Quale colore preferisci fra questi come sfondo?"
choices = ["Nero","Blu","Verde"]
COLORESCELTODALLUTENTE = easygui.buttonbox(msg,choices=choices)
#Unused Values as it runs in fullscreen mode
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
#The text is white
TEXTCOLOR = (255, 255, 255)
#Changes the colour of the background according to the choice of the user
if COLORESCELTODALLUTENTE == 'Nero':
BACKGROUNDCOLOR = (0, 0, 0)
elif COLORESCELTODALLUTENTE == 'Blu':
BACKGROUNDCOLOR = (36, 68, 212)
elif COLORESCELTODALLUTENTE == 'Verde':
BACKGROUNDCOLOR = (36, 237, 52)
#Frames per second the game will run at
FPS = 40
#Description of the baddies
baddie_type_1MINSIZE = 20
baddie_type_1MAXSIZE = 40
baddie_type_1MINSPEED = 4
baddie_type_1MAXSPEED = 5
ADDNEWbaddie_type_1RATE = 21 - int(Difficoltà)
#Description of the goddies
goddie_type_1MINSIZE = 20
goddie_type_1MAXSIZE = 40
goddie_type_1MINSPEED = 4
goddie_type_1MAXSPEED = 5
ADDNEWgoddie_type_1RATE = 10
#How fast you move with the arrows
PLAYERMOVERATE = 5
def terminate():
pygame.quit()
sys.exit()
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_type_1(playerRect, baddies_type_1):
for b in baddies_type_1:
if playerRect.colliderect(b['rect_b']):
return True
return False
def playerHasHitgoddie_type_1(playerRect, goddies_type_1):
for g in goddies_type_1:
if playerRect.colliderect(g['rect_g']):
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()
#This down here is windowed mode
#windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
#This down here is fullscreen mode
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), pygame.FULLSCREEN)
pygame.display.set_caption('Dodger')
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.mp3')
# set up images
playerImage = pygame.image.load('Player.png')
playerRect = playerImage.get_rect()
baddie_type_1Image = pygame.image.load('Baddie_type_1.png')
goddie_type_1Image = pygame.image.load('Goddie_type_1.png')
# show the "Start" screen
drawText('Dodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
# set up the start of the game
baddies_type_1 = []
goddies_type_1 = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddie_type_1AddCounter = 0
goddie_type_1AddCounter = 0
pygame.mixer.music.play(-1, 0.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)
# ize is for size
# Add new baddies_type_1 at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
baddie_type_1AddCounter += 1
if baddie_type_1AddCounter == ADDNEWbaddie_type_1RATE:
baddie_type_1AddCounter = 0
baddies_type_1ize = random.randint(baddie_type_1MINSIZE, baddie_type_1MAXSIZE)
newbaddie_type_1 = {'rect_b': pygame.Rect(random.randint(0, WINDOWWIDTH-baddies_type_1ize), 0 - baddies_type_1ize, baddies_type_1ize, baddies_type_1ize),
'speed_b': random.randint(baddie_type_1MINSPEED, baddie_type_1MAXSPEED),
'surface_b':pygame.transform.scale(baddie_type_1Image, (baddies_type_1ize, baddies_type_1ize)),
}
baddies_type_1.append(newbaddie_type_1)
# ize is for size
# Add new goddies_type_1 at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
goddie_type_1AddCounter += 1
if goddie_type_1AddCounter == ADDNEWgoddie_type_1RATE:
goddie_type_1AddCounter = 0
goddies_type_1ize = random.randint(goddie_type_1MINSIZE, goddie_type_1MAXSIZE)
newgoddie_type_1 = {'rect_g': pygame.Rect(random.randint(0, WINDOWWIDTH-goddies_type_1ize), 0 - goddies_type_1ize, goddies_type_1ize, goddies_type_1ize),
'speed_g': random.randint(goddie_type_1MINSPEED, goddie_type_1MAXSPEED),
'surface_g':pygame.transform.scale(goddie_type_1Image, (goddies_type_1ize, goddies_type_1ize)),
}
# 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_type_1 down.
for b in baddies_type_1:
if not reverseCheat and not slowCheat:
b['rect_b'].move_ip(0, b['speed_b'])
elif reverseCheat:
b['rect_b'].move_ip(0, -5)
elif slowCheat:
b['rect_b'].move_ip(0, 1)
# Move the goddies_type_1 down.
for g in goddies_type_1:
if not reverseCheat and not slowCheat:
g['rect_g'].move_ip(0, g['speed_g'])
elif reverseCheat:
g['rect_g'].move_ip(0, -5)
elif slowCheat:
g['rect_g'].move_ip(0, 1)
# Delete baddies_type_1 that have fallen past the bottom.
for b in baddies_type_1[:]:
if b['rect_b'].top > WINDOWHEIGHT:
baddies_type_1.remove(b)
# Delete goddies_type_1 that have fallen past the bottom.
for g in goddies_type_1[:]:
if g['rect_g'].top > WINDOWHEIGHT:
goddies_type_1.remove(g)
# 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(playerImage, playerRect)
# Draw each baddie_type_1
for b in baddies_type_1:
windowSurface.blit(b['surface_b'], b['rect_b'])
# Draw each goddie_type_1
for g in goddies_type_1:
windowSurface.blit(g['surface_g'], g['rect_g'])
pygame.display.update()
# Check if any of the baddies_type_1 have hit the player.
if playerHasHitbaddie_type_1(playerRect, baddies_type_1):
if score > topScore:
topScore = score # set new top score
break
# Check if any of the goddies_type_1 have hit the player.
if playerHasHitgoddie_type_1(playerRect, goddies_type_1):
score = score + 200
#Frapes of the game
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()
After your # Add new baddies_type_1 at the top of the screen, if needed. code, it looks like you actually add the baddie with this line:
baddies_type_1.append(newbaddie_type_1)
You don't appear to be doing that with your goodies code. Try adding:
goddies_type_1.append(newgoddie_type_1)
after your # Add new goddies_type_1 at the top of the screen, if needed. if statements.
Also, you spelled goodies as goddies throughout your code.