I'm trying to make it so when the game over screen shows the user can press space to get back into the game. Currently, when a game over happens, it displays the game over screen but accepts no input or at least doesn't do anything with the input. For some context, the game is basically about moving left and right to avoid obstacles. Currently, I only have one obstacle, but I just have not gotten to that yet. Thanks!
import pygame
import random
import math
pygame.init()
screenWidth = 700
screenHeight = 800
x = screenWidth / 2
y = (screenHeight / 4) * 3
width = 50
height = 50
win = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption("Test Game")
bg = pygame.image.load("background.png").convert()
gameover = pygame.image.load("gameover.png").convert()
bgx = (screenWidth / 6) * 2
bgy = 0
clock = pygame.time.Clock()
class enemy():
def __init__(self,c,y,width,height):
self.c = c
self.y = y
self.width = width
self.height = height
self.vel = 5
def draw(self, win):
if self.c == 1:
self.x = 250
#250
elif self.c == 2:
self.x = 350
#350
else:
self.x = 450
#450
self.y += self.vel
pygame.draw.rect(win, (0,0,255), (self.x,self.y,self.width,self.height))
evil = enemy(random.randint(1,3),0,50,50)
#def redrawGameWindow():
# evil.draw(win)
# pygame.display.update()
running = True
gameOver = False
while running:
clock.tick(60)
while gameOver:
win.blit(gameover, (0,0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if pygame.event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
gameOver = True
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
x+=100
if event.key == pygame.K_LEFT:
x-=100
win.fill((0,0,0))
win.blit(bg, (bgx, bgy))
evil.draw(win)
dist = math.hypot(evil.x - x, evil.y - y)
if dist <= 50:
print("Game Over!")
running = False
gameOver = True
pygame.draw.rect(win, (255,0,0), (x,y,width,height))
pygame.display.update()
#redrawGameWindow()
while gameOver:
win.blit(gameover, (0,0))
pygame.display.update()
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
gameOver = False
pygame.quit()
The main problem is that your game over scene is the loop behind the main while running: loop and there's no way to go back to the first loop when you reach it. When you touch the evil object, you set running = False, leave the main and enter the while gameOver: loop.
In this loop you also need to call pygame.event.pump(), otherwise the pygame.key.get_pressed() function doesn't work correctly and the window freezes after a while because the events are not handled. If you want to restart the game, you should rather use only the nested while gameOver loop. Actually, I would recommend that you restructure the scenes even more and use a finite state machine instead (here's an answer in which I use functions as scenes but check out the link in the comment below as well).
Here's a working version of your code. I've changed a few things and added comments to explain the changes.
while running:
# -----The game over scene.-----
while gameOver:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# pygame.quit only uninitializes the pygame modules and
# doesn't quit the program.
pygame.quit()
# This will quit the whole program. You need to import sys.
sys.exit()
elif event.type == pygame.KEYUP: # event.type not pygame.event.type
if event.key == pygame.K_SPACE:
# Change it to False to break out of the loop.
gameOver = False
# Reset the game. You could reset the position of the
# `evil` object or instantiate a new one.
evil.x = 350
evil.y = 0
win.blit(gameover, (0,0))
pygame.display.update()
clock.tick(60) # You need to call tick in this loop as well.
# ------------------------------
# -----The main scene.-----
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
x += 100
elif event.key == pygame.K_LEFT:
x -= 100
win.fill((0,0,0))
win.blit(bg, (bgx, bgy))
evil.draw(win)
dist = math.hypot(evil.x - x, evil.y - y)
if dist <= 50:
print("Game Over!")
# running = False # This would stop the main loop.
gameOver = True
pygame.draw.rect(win, (255,0,0), (x,y,width,height))
pygame.display.update()
clock.tick(60)
# The other while loop was removed.
pygame.quit()
Related
This question already has answers here:
Why is my pygame application loop not working properly?
(1 answer)
Pygame window freezes when it opens
(1 answer)
How to detect when a rectangular object, image or sprite is clicked
(1 answer)
Closed 2 years ago.
For my coursework for computer science I have to make a program but I've ran into issues that I can't find answers to.
Firstly in the section of code highlighted with *** I am trying to make the sprite character1 move which doesn't do anything when I press the arrow keys and don't know why
Secondly is the picture I am using as a button doesn't do anything when i click on it - highlighted with ###
I know my code isn't the most efficient but I'm trying to do what makes sense to me
import pygame
import random
import time
WIDTH = 1080
HEIGHT =720
FPS = 30
x1 = WIDTH/2.25
y1 = HEIGHT/2.5
x2 = WIDTH/20
y2 = HEIGHT/2.5
xbut = 800
ybut = 275
gameTitle = 'Hungry Ghosts'
xChange1 = 0
yChange1 = 0
xChange2 = 0
yChange2 = 0
#define colours
WHITE = (255,255,255)
BLACK = (0,0,0)
MEGAN = (123,57,202)
MOLLIE = (244,11,12)
KATIE = (164,12,69)
#initialise pygame and window
pygame.init()
pygame.mixer.init()
pygame.font.init()
screen =pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Hungry Ghosts')
clock = pygame.time.Clock()
#load immages
background_image = pygame.image.load(('purplesky.jpg'))
player1_image = pygame.image.load(('player 1.png')).convert_alpha()
player2_image = pygame.image.load(('player 2.png')).convert_alpha()
position = (0,0)
screen.blit(background_image, position)
startBut = pygame.image.load('button.jpg').convert()
#define functions
def textObjects(gameTitle, font):
textSurface = font.render(gameTitle,True, WHITE)
pygame.display.update()
return textSurface, textSurface.get_rect()
def titleText(gameTitle):
textForTitle = pygame.font.Font('VCR_OSD_MONO_1.001.ttf',115)
TextSurf, TextRect = textObjects(gameTitle, textForTitle)
TextRect.center = ((WIDTH/2),(HEIGHT/6))
screen.blit(TextSurf,TextRect)
pygame.display.update()
########################################
def titleButton(xbut,ybut):
screen.blit(startBut,(xbut,ybut))
pygame.display.update()
########################################
***************************************
def character1(x1,y1):
screen.blit(player1_image,(x1,y1))
pygame.display.update()
***************************************
def character2(x,y):
screen.blit(player2_image,(x,y))
pygame.display.update()
def homeScreen():
running = True
gameplay = False
instructions = False
home = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
################################################################
if event.type == pygame.MOUSEBUTTONDOWN:
xbut,ybut = event.pos
if startBut.get_rect().collidepoint(xbut,ybut):
print('clicked on button')
################################################################
def gameLoop():
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
*************************************************************************
#movement
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xChange1 = -5
elif event.key == pygame.K_RIGHT:
xChange1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xChange1 = 0
x1 += xChange1
*************************************************************************
#calling functions
titleText(gameTitle)
character1(x1,y1)
character2(x2,y2)
titleButton(xbut,ybut)
homeScreen()
pygame.quit()
You have to do the movement and the drawing of the scene in the game loop.
an application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
running = True
def homeScreen():
global running
start = False
home = True
while running and not start:
clock.tick(FPS)
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if startBut.get_rect(topleft = (xbut, ybut)).collidepoint(event.pos):
print('clicked on button')
start = True
# draw background
screen.blit(background_image, (0, 0))
# draw scene
titleText(gameTitle)
titleButton(xbut,ybut)
# update display
pygame.display.flip()
homeScreen()
def gameLoop():
global running
global x1, y2, x2, y2, xChange1, yChange1, xChange2, yChange2
while running:
clock.tick(FPS)
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xChange1 = -5
elif event.key == pygame.K_RIGHT:
xChange1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xChange1 = 0
# update position of objects
x1 += xChange1
# draw background
screen.blit(background_image, (0, 0))
# draw scene
character1(x1,y1)
character2(x2,y2)
# update display
pygame.display.flip()
gameLoop()
pygame.quit()
Okay so I started a project today where I created Space Invaders. The only I'm personally having issues with is the pause and unpause button. I'm using Python 3.7.4 and Pygame 1.9.6.
paused = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p: # Pausing
paused = True
if event.key == pygame.K_u: # Unpausing
paused = False
if not paused:
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bullet_Sound = mixer.Sound('laser.wav')
bullet_Sound.play()
# Get the current x coordinate of the spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
So I don't know if I should have the pause button first or not.
I've tried:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p: # Pausing
paused = True
if event.key == pygame.K_u: # Unpausing
paused = False
if not paused:
while running:
'''The rest of the code'''
Where the # Pausing is:
I've tried:
if event.key == pygame.K_p:
paused = not paused # for pause and unpausing
No 'u' key.
So I'm just lost on where I should put it at. So it would be nice with the help. I looked at question: pausing/ Unpausing in Pygame for help. So anything else let me know.
Here's a minimal, complete example of a ball moving. You can pause and unpause its movement by pressing P. You can change its speed using ←↑→↓. Pressing Spacebar will reset the speed.
import pygame
WIDTH = 640
HEIGHT = 480
FPS = 30
class Ball(pygame.sprite.Sprite):
"""Moving ball sprite"""
def __init__(self, color="white", size=20, speedx=-5, speedy=-5):
pygame.sprite.Sprite.__init__(self)
self.color = pygame.color.Color(color)
# instead of loading an image from file, draw a circle.
self.image = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, self.color, (size, size), size)
self.rect = self.image.get_rect()
# start ball in the middle of the screen
self.rect.x = WIDTH / 2 - self.rect.width / 2
self.rect.y = HEIGHT / 2 - self.rect.height / 2
self.speedx = speedx
self.speedy = speedy
self.size = size
def update(self):
# reverse direction if out of bounds
if not (0 < self.rect.x < WIDTH - self.size*2):
self.speedx *= -1
if not (0 < self.rect.y < HEIGHT - self.size*2):
self.speedy *= -1
# update position
self.rect.x += self.speedx
self.rect.y += self.speedy
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
ball = Ball()
balls = pygame.sprite.Group()
balls.add(ball)
paused = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_p:
paused = not paused
elif event.key == pygame.K_UP:
ball.speedy += 5
elif event.key == pygame.K_DOWN:
ball.speedy -= 5
if event.key == pygame.K_RIGHT:
ball.speedx += 5
elif event.key == pygame.K_LEFT:
ball.speedx -= 5
elif event.key == pygame.K_SPACE:
# reset speed
ball.speedx = 2
ball.speedy = 0
# update game elements
if not paused:
pygame.display.set_caption('Running')
ball.update()
else:
pygame.display.set_caption('Paused')
# draw surface - fill background
window.fill(pygame.color.Color("grey"))
## draw sprites
balls.draw(window)
# show surface
pygame.display.update()
# limit frames
clock.tick(FPS)
pygame.quit()
Note that whilst paused, events are still being handled, so you can still adjust the speed. To change this behaviour, you'd need to discard specific events when paused is True.
So right now I am learning pygame and I'm using sentdex's tutorials. On I believe his 6th pygame tutorial he showed us how to generate more than just one block. I added the code, but it didin't work. I don't understand why it didn't work? Could you please tell me what I'm doing wrong and how to fix it?
Here's the code:
import pygame
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
window_width = 800
window_height = 600
gameDisplay = pygame.display.set_mode((window_width,window_height))
pygame.display.set_caption('MyFirstGame')
carImg = pygame.image.load("racecar.png")
clock = pygame.time.Clock()
def blocks(block_x, block_y, block_width, block_height, color):
pygame.draw.rect(gameDisplay, color, [block_x, block_y, block_width, block_height])
def crash():
print("YOUR GARBAGE! Press C to play again or Q to quit.")
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit
quit()
gameExit = True
if event.key == pygame.K_c:
gameLoop()
print("User has decided to play again")
def gameLoop():
# Defining variables to draw and move car
car_x = 350
car_y = 400
car_x_change = 0
car_w = 100
car_h = 100
# Defining variables to draw blocks
block_x = random.randrange(0, window_width)
block_y = -600
block_speed = 7
block_width = 100
block_height = 100
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
car_x_change += -5
if event.key == pygame.K_RIGHT:
car_x_change += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
if event.key == pygame.K_RIGHT:
x_change = 0
car_x += car_x_change
gameDisplay.fill(white)
# blocks((block_x,block_y,[block_width,block_height,black))
blocks(block_x, block_y, block_width, block_height, black)
block_y += block_speed
gameDisplay.blit(carImg, (car_x,car_y))
if car_x >= window_width:
gameExit = True
crash()
if car_x <= 0:
gameExit = True
crash()
if car_y > window_height:
block_y = 0 - block_height
block_x = random.randrange(0,window_width-block_width)
pygame.display.update()
clock.tick(30)
gameLoop()
pygame.quit
quit()
One pair block_x, block_y can't be use to draw many blocks.
You have to create list with pairs (x,y) for all blocks which you want to draw. You have to use for loops to create blocks (pairs (x,y)), to move them, and to draw them.
BTW: running gameloop() inside crash() create recursion which is not prefered method.
My version with more information in comments # changed
import pygame
import random
# changed: better organized code
# --- constants --- (UPPERCASE_NAMES)
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# --- functions --- (lowercase_names)
def blocks(points, width, height, color):
# changed: use `for` to draw all blocks
for x, y in points:
pygame.draw.rect(display, color, [x, y, width, height])
def crash():
print("YOUR GARBAGE! Press C to play again or Q to quit.")
# changed: return `True/False` insted of executing gameloop()
# because it was not good idea
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
return True # True = quit
if event.key == pygame.K_c:
print("User has decided to play again")
return False # false = continue
def gameloop():
# --- objects ---
car_image = pygame.image.load("racecar.png")
# Defining variables to draw and move car
car_x = 350
car_y = 400
car_x_change = 0
car_w = 100
car_h = 100
# BTW: you could use `pygame.Rect` to keep position and size
# car_rect = car_image.get_rect(x=350, y=450)
# Defining variables to draw blocks
block_speed = 7
block_width = 100
block_height = 100
# changed: create list with points x,y
pairs = []
for _ in range(10):
x = random.randrange(0, WINDOW_WIDTH)
y = -block_height
pairs.append( (x, y) )
# --- mainloop ---
clock = pygame.time.Clock()
gameExit = False
while not gameExit:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
car_x_change -= 5
elif event.key == pygame.K_RIGHT:
car_x_change += 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
car_x_change += 5 # changed: wrong variable, use +=
elif event.key == pygame.K_RIGHT:
car_x_change -= 5 # changed: wrong variable, use -=
# --- updates ---
# changed: all moves before draws
# move car
car_x += car_x_change
# changed: one `if` for both crashes (`car_x`)
if car_x < 0 or car_x >= WINDOW_WIDTH:
# changed: use value from crash to set gameExit
# and to move car to start position
gameExit = crash()
if not gameExit:
car_x = 350
car_y = 400
# changed: use `for` to move all points
# and to check if they need new random place
# move blocks
moved_pairs = []
for x, y in pairs:
y += block_speed
if y > WINDOW_HEIGHT:
y = -block_height
x = random.randrange(0, WINDOW_WIDTH - block_width)
moved_pairs.append( (x, y) )
pairs = moved_pairs
# --- draws ---
# changed: all draws after moves
display.fill(WHITE)
blocks(pairs, block_width, block_height, BLACK)
display.blit(car_image, (car_x, car_y))
pygame.display.update()
# --- FPS ---
clock.tick(30)
# --- main ---
pygame.init()
display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('MyFirstGame')
gameloop()
pygame.quit() # changed: forgot ()
First of all, sorry for my noob question.
So I'm trying to learn pygame, and to do so I created a """game""' that is supposed to quit whenever someone clicks the close button ("x" button") in the top corner of the window, but instead the whole game restarts itself.
I use "Game = False" to point that the game needs to close, since everything that the game does is located in a loop that only starts with "Game = True", and at the end of the script (after the loop ends) there is a "pygame.quit()" and a "sys.exit()". This was was working fine, but recenlty I added the following lines:
if x < 0 or x > display_width - spacecore_width:
game_over()
Those are supposed to call a "game_over" function, that resets the game by calling the another function that covers the whole game (the loop is located inside of this function). But this is not supposed to happen when someone clicks the "x" button to quit the game, and I have no idea of why this also happens when such thing is done (besides working as intended, by only repeating the game if "x < 0 or x > display_width - spacecore_width".
I already know how to avoid it (I just need to replace "Game = False" with those quit commands) but I would like to know why the problem happens in the first place.
Here's the full code:
import pygame, sys, time
pygame.init()
display_width = 800
display_height = 600
DISPLAY = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Não enconste nas bordas da tela")
WHITE = (255,255,255)
RED = (255,0,0)
SPACECORE = pygame.image.load("spacecore.png")
spacecore_width = 100
clock = pygame.time.Clock()
def text_and_rect(text,font):
text_surface = font.render(text,True,RED)
return text_surface, text_surface.get_rect()
def message_display(text):
font = pygame.font.Font("freesansbold.ttf",50)
text_surf, text_rect = text_and_rect(text,font)
text_rect.center = ((display_width/2),(display_height/2))
DISPLAY.blit(text_surf,text_rect)
pygame.display.update()
time.sleep(2)
def game_over():
message_display("Você morreu de morte morrida")
game_loop()
def player(x,y):
DISPLAY.blit(SPACECORE,(x,y))
def game_loop():
Game = True
x = display_width * 0.5
y = display_height * 0.8
mod_x = mod_y = 0
while Game == True:
pygame.display.update()
DISPLAY.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
Game = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
mod_x = -5
if event.key == pygame.K_RIGHT:
mod_x = 5
if event.key == pygame.K_UP:
mod_y = -5
if event.key == pygame.K_DOWN:
mod_y = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
mod_x = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
mod_y = 0
x += mod_x
y += mod_y
clock.tick(60)
player(x,y)
if x < 0 or x > display_width - spacecore_width:
game_over()
game_loop()
pygame.quit()
sys.exit()
Make sure you're breaking out of the loop and then calling the loop function again:
while Game == True:
# some here code
if x < 0 or x > display_width - spacecore_width:
break # leave while loop
# proceed elsewhere
game_over()
Or alternatively cut the flow back to game_loop in game_over:
def game_over():
message_display("Você morreu de morte morrida")
# game_loop() # removed
Currently you're never breaking out of loops when game is over - you're just calling other functions (which in turn active another loop) in a mutually-recursive manner, effectively this never ends any game.
Also, if you receive a quit event you may want to break out of the for loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Game = False
break
I am attempting to make a game where the 'player' (who spawns as the moon furthest to the right) can move around using the 'WASD' keys and enemies fall from the top of the screen in order to hit the player and end the game. I am currently doing this for an assignment and i have set up a test to see whether it is possible for me to do this and so far i have been able to create a 'player' object that is controllable by the 'WASD' keys and make a screen which requires players to press 'SPACE' to play the game. I am having trouble though with being able to have the enemies fall on the 'Y' axis down the screen smoothly. The picture moves down the screen only when the user presses or releases a key, this creates a jagged movement or when the user moves the mouse over the pygame screen, creating a very smooth movement.
#import necessary modules and pygame.
import pygame, sys, random
from pygame.locals import *
#set global variables
pygame.init()
WINDOWWIDTH = 800
WINDOWHEIGHT = 800
BACKGROUNDCOLOUR = (255,255,255)
TEXTCOLOUR = (0,0,0)
FPS = 30
ENEMYMINSIZE = 10
BOMBSAWAY = -1
ENEMYMAXSIZE = 40
ENEMYMINSPEED = 1
ENEMYMAXSPEED = 10
ADDNEWENEMYRATE = 5
PLAYERMOVERATE = 5
FSIZE = 48
BLUE = (0,0,255)
global PLAY
PLAY = False
global fpsClock
fpsClock = pygame.time.Clock()
# set up pygame and GUI
MainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
windowSurface.fill(BACKGROUNDCOLOUR)
pygame.display.set_caption('Bubble Dash')
enemy = pygame.image.load('player.jpg')
char = pygame.image.load('player.jpg')
# set up fonts
basicFont = pygame.font.SysFont(None, 48)
# set up the text
text = basicFont.render('Press any key to play!', True, (255,255,0))
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
# draw the text onto the surface
# set up x and y coordinates
# music
windowSurface.blit(text, textRect)
def playgame(PLAY):
x,y = 0,0
movex,movey = 0,0
charx=300
chary=200
direction = 'down'
enemyx= 10
enemyy=10
while PLAY:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == ord('m'):
pygame.mixer.music.stop()
if event.key == ord('n'):
pygame.mixer.music.play()
if event.key == ord('a'):
movex = -0.5
if event.key == ord('d'):
movex = 0.5
if event.key == ord('w'):
movey = -0.5
if event.key == ord('s'):
movey = 0.5
if event.type ==KEYUP:
if event.key == ord('a'):
movex = 0
if event.key == ord('d'):
movex = 0
if event.key == ord('w'):
movey = 0
if event.key == ord('s'):
movey = 0
if direction == 'down':
enemyy += 7
windowSurface.fill(BLUE)
windowSurface.blit(char, (charx, chary))
windowSurface.blit(enemy, (enemyx, enemyy))
pygame.display.update()
charx+=movex
chary+=movey
def playertopresskey(PLAY):
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_SPACE:
PLAY = True
if PLAY == True:
playgame(PLAY)
pygame.display.update()
playertopresskey(PLAY)
I would like for the 'enemy' object to be able to fall from the top without the user either needing to keypress or to key up or to have to move the mouse on the screen, rather the 'enemy' would just fall from the top as soon as the subroutine is called.
You may need to tweak it a bit because it is set up for me at the moment but i deleted a few things that would give you bother. Hopefully someone can help me. Thanks.
The below is link to a picture similar to mine which you can download and replace in the code for both the 'char' and the 'enemy' variables to view this yourself for i cannot access the courses at the present time.
http://www.roleplaygateway.com/roleplay/the-five-elements/characters/miss-joy/image
I found your error, you would have caught it yourself if you would have divided your code into some functions. Here is the problem:
for event in pygame.event.get():
if event.type == QUIT:
...
if event.type == KEYDOWN:
...
if event.type == KEYUP:
...
if direction == 'down':
enemyy += 7
your code moving the enemy is called only when an event is waiting in the queue. Move it out of the loop, and you will be good to go.
You have to change indention for:
if direction == 'down':
enemyy += 7
Now it is inside for event in pygame.event.get():