I'm trying to do a small school project it's very simple and basically, all you do is click on randomly appearing donuts on the screen each click gives a point and everything is ok up until there, I tried to do a timer that will reset when you click on a donut each time so basically, you have around 1.5 seconds between each click and if you run out of time you lose a life but I can't figure out how to implement a timer that will run between clicks on the donut and reset each time you click, I searched all across the internet and found nothing can someone please help.
donut_width, donut_height = 110, 95
score = 0
lives = 4
class Donut:
def __init__(self, x, y):
self.donut_original = pygame.image.load(os.path.join('icon.png'))
self.donutImg = pygame.transform.scale(self.donut_original, (donut_width, donut_height))
self.donut = self.donutImg.get_rect()
self.donut.x = x
self.donut.y = y
def draw(self):
screen.blit(self.donutImg, self.donut)
def collision(donut1, mouse):
return donut1.collidepoint(mouse)
donut = Donut(width//2, height//2)
def graphics():
screen.fill(uwred)
donut.draw()
text_score = pygame.font.SysFont('comicsans', 80).render('SCORE: ' + str(score), True, white)
screen.blit(text_score, (0, 0))
run = True
out_of_time = False
while run:
mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if collision(donut.donut, mouse_pos) and event.type == pygame.MOUSEBUTTONDOWN:
donut.donut.x = random.randint(donut_width * 2, width - donut_width * 2)
donut.donut.y = random.randint(donut_height * 2, height - donut_height * 2)
score += 1
graphics()
pygame.display.update()
pygame.quit()
You can try using the time.time() method:
import pygame
from time import time
pygame.init()
wn = pygame.display.set_mode((600, 600))
class Button:
def __init__(self):
self.rect = pygame.Rect(250, 250, 100, 100)
self.color = (255, 0, 0)
def clicked(self, pos):
return self.rect.collidepoint(pos)
def draw(self):
pygame.draw.rect(wn, self.color, self.rect)
button = Button()
score = 0
t = time()
while True:
if time() - t > 1.5:
score -= 1
t = time()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if button.clicked(event.pos):
score += 1
t = time()
wn.fill((255, 255, 255))
button.draw()
pygame.display.update()
print(score)
Explanation:
Import the necessary modules and function:
import pygame
from time import time
Initialize the pygame module and create a pygame window:
pygame.init()
wn = pygame.display.set_mode((600, 600))
Define the most basic Button class as an example for the object to click:
class Button:
def __init__(self):
self.rect = pygame.Rect(250, 250, 100, 100)
self.color = (255, 0, 0)
def clicked(self, pos):
return self.rect.collidepoint(pos)
def draw(self):
pygame.draw.rect(wn, self.color, self.rect)
Create a Button from the class defined above:
button = Button()
Define a variable, t, to be the score, and a variable, score, to be the current time in seconds:
score = 0
t = time()
In the while loop, check if the current time during that iteration of the while loop is more than 1.5 seconds greater than the t variable defined. If so, decrement 1 from the score variable and reset the t variable to be the current time:
while True:
if time() - t > 1.5:
score -= 1
t = time()
Use a for loop to loop over the pygame events to check for an exit event:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
If the button is clicked, increment the score variable by 1 and reset the t variable to be the current time:
elif event.type == pygame.MOUSEBUTTONDOWN:
if button.clicked(event.pos):
score += 1
t = time()
Finally, draw the button, and print the score to see it working:
wn.fill((255, 255, 255))
button.draw()
pygame.display.update()
print(score)
Use pygame.time.get_ticks to get the number of milliseconds since pygame.init() was called.
Set the start time when a new donut appears. Calculate the difference between the current time and the start time. Decrease the number of lives if the difference exceeds the limit:
lives = 4
start_time = pygame.time.get_ticks()
run = True
while run:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN and collision(donut.donut, event.pos) and :
donut.donut.x = random.randint(donut_width * 2, width - donut_width * 2)
donut.donut.y = random.randint(donut_height * 2, height - donut_height * 2)
score += 1
start_time = current_time
delta_time = current_time - start_time
if delta_time > 1500: # 1.5 sceonds
lives -= 1
start_time = current_time
print("lives:", lives)
graphics()
pygame.display.update()
Related
I've been trying to make a Chrome Dino Game, however, I'm struggling with this problem:
On every frame, it should draw a new one at the new position and delete the previous one to make it look as if it's moving. HOWEVER, it remains at its previous position and a new image appears on its next position. I did write the pygame.display.update() code at the end of my maintop.
In the last time I ran into a similar problem, I managed to make it work by drawing a background image, but this time, it doesn't work.
following are my codes:
import pygame
import os
from random import randint
import schedule
pygame.init()
assets = os.path.join(os.path.dirname(__file__), "Assets")
screen_size = (screen_width, screen_height) = (1280, 720)
screen = pygame.display.set_mode(screen_size)
clock = pygame.time.Clock()
fps = 120
bg = pygame.image.load(os.path.join(assets, "IMG_15.png"))
ground = 700
running = True
spacebaridx = 0
gamestart = False
tick_on_start = 0
obs1 = pygame.image.load(os.path.join(assets, "colourmat/light_green.png"))
pygame.transform.scale(obs1, (100, 200))
obs2 = pygame.image.load(os.path.join(assets, "colourmat/light_green.png"))
pygame.transform.scale(obs2, (120, 200))
obs3 = pygame.image.load(os.path.join(assets, "colourmat/light_green.png"))
pygame.transform.scale(obs3, (150, 200))
ls_obs = []
def create_obs():
k = randint(1, 3)
if k == 1:
info = {"type":1, "img":obs1, "x":screen_width, "y":ground - 200, "tox":2}
ls_obs.append(info)
if k == 2:
info = {"type":2, "img":obs2, "x":screen_width, "y":ground - 200, "tox":2}
ls_obs.append(info)
else:
info = {"type":3, "img":obs3, "x":screen_width, "y":ground - 200, "tox":2}
ls_obs.append(info)
schedule.every(3).seconds.do(create_obs)
while running:
dt = clock.tick(fps)
if gamestart == True:
game_ticks = pygame.time.get_ticks() - tick_on_start
schedule.run_pending()
else:
game_ticks = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if spacebaridx == 0: # Press space to start / to tell whether it's the first press
spacebaridx += 1
gamestart = True
tick_on_start = pygame.time.get_ticks()
else:
pass # Jump
for o in ls_obs:
o["x"] += o["tox"] * -1
screen.blit(bg, (0, 0))
for o in ls_obs:
screen.blit(o["img"], (o["x"], o["y"]))
pygame.display.update()
pygame.quit()
This issue is occurring because you aren't clearing the display within each frame. In pygame, in order to clear the display, we need to use the fill method. So in your code, at the top of your game loop before the event loop, add screen.fill((0, 0, 0)). This will fill your screen in the color black. Don't worry, the black won't be shown if you draw the background on top of it. Now, when you add a new image, the previous images won’t be displayed.
Modified Game Loop
while running:
screen.fill((0, 0, 0))
dt = clock.tick(fps)
if gamestart == True:
game_ticks = pygame.time.get_ticks() - tick_on_start
schedule.run_pending()
else:
game_ticks = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if spacebaridx == 0: # Press space to start / to tell whether it's the first press
spacebaridx += 1
gamestart = True
tick_on_start = pygame.time.get_ticks()
else:
pass # Jump
for o in ls_obs:
o["x"] += o["tox"] * -1
screen.blit(bg, (0, 0))
for o in ls_obs:
screen.blit(o["img"], (o["x"], o["y"]))
pygame.display.update()
pygame.quit()
I'm currently making a Python clicking game using Pygame. Right now, there is a coin in the center of the screen that you can click. What I want to add now, it a little green "+$10" icon that appears somewhere next to the coin whenever someone clicks it. This is what I want the game to look like whenever someone clicks the coin:
Here is the code of my coin functions:
def button_collide_mouse(element_x, element_y, x_to_remove, y_to_remove):
mouse_x, mouse_y = pygame.mouse.get_pos()
if mouse_x > element_x > mouse_x - x_to_remove and \
mouse_y > element_y > mouse_y - y_to_remove:
return True
def check_events(coin, settings):
for event in pygame.event.get():
# Change button color if mouse is touching it
if button_collide_mouse(coin.image_x, coin.image_y, 125, 125):
coin.image = pygame.image.load('pyfiles/images/click_button.png')
if event.type == pygame.MOUSEBUTTONUP:
settings.money += settings.income
else:
coin.image = pygame.image.load('pyfiles/images/click_button_grey.png')
Using my current code, how can I add that kind of effect?
See How to make image stay on screen in pygame?.
Use pygame.time.get_ticks() to return the number of milliseconds since pygame.init() was called. When the coin is clicked, calculate the point in time after that the text image has to be removed. Add random coordinates and the time to the head of a list:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
# [...]
if event.type == pygame.MOUSEBUTTONDOWN:
if coin_rect.collidepoint(event.pos):
pos = ... # random position
end_time = current_time + 1000 # 1000 milliseconds == 1 scond
text_pos_and_time.insert(0, (pos, end_time))
Draw the text(s) in the main application loop. Remove the text when the time has expired from the tail of the list:
for i in range(len(text_pos_and_time)):
pos, text_end_time = text_pos_and_time[i]
if text_end_time > current_time:
window.blit(text, text.get_rect(center = pos))
else:
del text_pos_and_time[i:]
break
Minimal example:
import pygame
import random
pygame.init()
window = pygame.display.set_mode((400, 400))
font = pygame.font.SysFont(None, 40)
clock = pygame.time.Clock()
coin = pygame.Surface((160, 160), pygame.SRCALPHA)
pygame.draw.circle(coin, (255, 255, 0), (80, 80), 80, 10)
pygame.draw.circle(coin, (128, 128, 0), (80, 80), 75)
cointext = pygame.font.SysFont(None, 80).render("10", True, (255, 255, 0))
coin.blit(cointext, cointext.get_rect(center = coin.get_rect().center))
coin_rect = coin.get_rect(center = window.get_rect().center)
text = font.render("+10", True, (0, 255, 0))
text_pos_and_time = []
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if coin_rect.collidepoint(event.pos):
pos = pygame.math.Vector2(coin_rect.center) + pygame.math.Vector2(105, 0).rotate(random.randrange(360))
text_pos_and_time.insert(0, ((round(pos.x), round(pos.y)), current_time + 1000))
window.fill(0)
window.blit(coin, coin_rect)
for i in range(len(text_pos_and_time)):
pos, text_end_time = text_pos_and_time[i]
if text_end_time > current_time:
window.blit(text, text.get_rect(center = pos))
else:
del text_pos_and_time[i:]
break
pygame.display.flip()
pygame.quit()
exit()
Uhh sorry for the super vague title, I have no idea whats wrong with my code either.
if event.type == pygame.K_SPACE:
run= True
There appears to be a problem when running this line, like the code is shaded a different colour on my screen, and it doesn't change run to True
This problem seems to be fixed if i delete:
def mainmenu()
and just use a while loop, however, I think it gets pretty messy and am quite hesitant to delete that.
Furthermore, when I run the mainmenu() function, it takes quite a long time to load up, a problem which I haven't had thus far and I am unsure why or how to fix it.
import pygame
import time
import random
pygame.init()
window = pygame.display.set_mode((1000,700))
White=(255,255,255)
font = pygame.font.SysFont("comicsansms", 25)
#for easier counting of lives, score here starts from 1, just simply subtract 1 from whats displayed later
score = 1
clicks = 1
lives = 3
run=False
intro=True
def mainmenu():
while intro:
window.fill((0, 0, 0))
text = font.render("Press space to start!" , True, White)
window.blit(text, (500, 350))
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro = False
pygame.quit()
quit()
if event.type == pygame.K_SPACE:
run= True
class Circle():
def __init__(self, color, x, y, radius, width):
self.color = color
self.x = x
self.y = y
self.radius = radius
self.width = width
def draw(self, win, outline=None):
pygame.draw.circle(win, self.color, (self.x, self.y), self.radius, self.width)
def isOver(self, mouse):
dx, dy = mouse[0] - self.x, mouse[1] - self.y
return (dx * dx + dy * dy) <= self.radius * self.radius
circles = []
def redrawWindow():
window.fill((0, 0, 0))
for c in circles:
c.draw(window)
text = font.render("Score:" + str(score-1), True, White)
window.blit(text, (0,0))
text = font.render("Lives:" + str(lives), True, White)
window.blit(text, (900, 0))
clock = pygame.time.Clock()
FPS = 60
x = str(pygame.time.get_ticks())
current_time = 0
next_circle_time = 0
while run:
delta_ms = clock.tick()
current_time += delta_ms
if current_time > next_circle_time:
next_circle_time = current_time + 1000 # 1000 milliseconds (1 second)
r = 20
new_circle = Circle((255, 255, 255), random.randint(r, 800-r), random.randint(r, 600-r), r, r)
circles.append(new_circle)
print()
redrawWindow()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN:
clicks += 1
mouse = pygame.mouse.get_pos()
for circle in circles:
if circle.isOver(mouse):
score += 1
circles.pop(circles.index(circle))
lives= 3-(clicks-score)
pygame.display.update()
run is a variable in global namespace. If you want to write a variable in global namespace within a function, then you have to use the global statement, which means that the listed identifiers are to be interpreted as globals:
run=False
intro=True
def mainmenu():
global run, intro
while intro:
window.fill((0, 0, 0))
text = font.render("Press space to start!" , True, White)
window.blit(text, (500, 350))
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro = False
pygame.quit()
quit()
if event.type == pygame.K_SPACE:
run = True
My original Solution was from this Comment on a similar question. However, if I do that and implement this
into different parts of my code, it stops counting up the in-game Counter of CASH.
CASH = 0
DPS = 5
HPofMonster = 10
starttime=time.time()
def handle_monster():
global HPofMonster, CASH
if pygame.mouse.get_focused():
event = pygame.event.poll()
mouse_x, mouse_y = pygame.mouse.get_pos()
if GEN1.collidepoint(mouse_x, mouse_y) and event.type == MOUSEBUTTONDOWN and event.button == 1:
HPofMonster -= 1
print('click')
pass
else:
print('Not Pushed OR not on Monster')
pass
else:
print('Mouse not focused')
pass
if HPofMonster < 0:
CASH += 5
HPofMonster = 10
print('reset')
def handle_dps():
global HPofMonster
HPofMonster -= DPS
print("tick")
time.sleep(1.0 - ((time.time() - starttime) % 1.0))
def game_loop():
while True:
handle_dps()
handle_monster()
update_text()
handle_events()
def main():
pygame.display.set_caption('Clicker')
game_loop()
main()
When I don´t move my Mouse, my console looks like this:
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
reset
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
reset
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
reset
Mouse not focused
Process finished with exit code 0
Here is the entire code:
import pygame, threading, time
from threading import Event, Thread
from pygame.locals import *
pygame.init()
WIDTH = 800
HEIGHT = 600
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
CASH = 0
DPS = 5
HPofMonster = 10
BACKGROUND_COLOR = (0, 0, 0)
BUTTON_COLOR = (0, 255, 0)
starttime=time.time()
FONT = pygame.font.SysFont('monospace', 15)
# Main Screen for drawing buttons
DRAW_SCREEN = pygame.Surface((WIDTH, HEIGHT))
DRAW_SCREEN.fill(BACKGROUND_COLOR)
# Buttons
GEN1 = pygame.draw.rect(DRAW_SCREEN, BUTTON_COLOR, pygame.Rect(200, 200, 200, 200), 1)
GEN1_LABEL = FONT.render('Defeat the Monster', 1, (255, 255, 0))
def handle_monster():
global HPofMonster, CASH
if pygame.mouse.get_focused():
event = pygame.event.poll()
mouse_x, mouse_y = pygame.mouse.get_pos()
if GEN1.collidepoint(mouse_x, mouse_y) and event.type == MOUSEBUTTONDOWN and event.button == 1:
HPofMonster -= 1
print('click')
pass
else:
print('Not Pushed OR not on Monster')
pass
else:
print('Mouse not focused')
pass
if HPofMonster < 0:
CASH += 5
HPofMonster = 10
print('reset')
def handle_events():
event_dict = {
pygame.QUIT: exit,
}
for event in pygame.event.get():
if event.type in event_dict:
event_dict[event.type]()
def update_text():
global CASH_LABEL, DPS_LABEL, GEN1_LABEL, DPS, CASH
WINDOW.blit(DRAW_SCREEN, (0, 0))
WINDOW.blit(GEN1_LABEL, (10, 108))
CASH_LABEL = FONT.render('Total Cash: ${}'.format(CASH), 1, (255, 255, 0))
DPS_LABEL = FONT.render('Total DPS: ${}'.format(DPS), 1, (255, 65, 0))
WINDOW.blit(CASH_LABEL, (0, 0))
WINDOW.blit(DPS_LABEL, (0, 20))
pygame.display.flip()
def handle_dps():
global HPofMonster
HPofMonster -= DPS
print("tick")
def game_loop():
while True:
handle_dps()
handle_monster()
update_text()
handle_events()
def main():
pygame.display.set_caption('Clicker')
game_loop()
main()
Do not use time.sleep() in a event-driven program. It blocks the event-loop, and on some systems the window manager or outlying operating system will consider the program to have stopped and/or crashed. The program must continually process incoming events.
An easy way to do this in pygame is to use the real-time system clock function pygame.time.get_ticks() which returns the number of milliseconds since the program started, and it keeps increasing forever. If you want something to trigger in the future, set a timestamp like:
future_timestamp = pygame.time.get_ticks() + 15000 # 15 seconds from now
...
# somewhere else in the code, maybe in the main loop
time_now = pygame.time.get_ticks()
if ( future_timestamp < time_now ):
# do the thing that had to happen
do_that_thing()
# re-set the timer for next time
future_timestamp = time_now + 15000
Another simple way to implement something that happens periodically is to setup a pygame timer:
pygame.time.set_timer( pygame.USEREVENT + 1, 3500 ) # Cash every 3500 milliseconds
# Main Loop
while not exiting:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.USEREVENT + 1 ):
CASH += 1
# reset the event-timer
pygame.time.set_timer( pygame.USEREVENT + 1, 3500 )
Instead of time.sleep use pygame.time.delay()or pygame.time.wait().
Here is the link of official pygame time events: https://www.pygame.org/docs/ref/time.html
I've have this dodging aliens game and it's not working. I can get the front begin screen to open but then when I hit enter to start it crashes and freezes. I've tried running it from python.exe instead of just IDLE but in that case it just pops up then closes right down. A few errors popped up the first few times I tried to run it but now there are no errors indicating what might be wrong. It just stops responding. What am I doing wrong here?
import pygame, random, sys
from pygame.locals import *
def startGame():
if event.type == K_ENTER:
if event.key == K_ESCAPE:
sys.exit()
return
def playerCollision():
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False
pygame.init()
screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')
font = pygame.font.SysFont(None, 55)
playerImage = pygame.image.load('')
playerRect = playerImage.get_rect()
alienImage = pygame.image.load('')
drawText('Dodge the Aliens!', font, screen, (750 / 3), (750 / 3))
drawText('Press ENTER to start.', font, screen, (750 / 3) - 45, (750 / 3) + 65)
pygame.display.update()
topScore = 0
while True:
aliens = []
score = 0
playerRect.topleft = (750 /2, 750 - 50)
alienAdd = 0
while True:
score += 1
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]: x -=3
if pressed[pygame.K_RIGHT]: x += 3
if pressed[pygame.K_ESCAPE]: sys.exit()
alienAdd += 1
if alienAdd == addedaliens:
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a)
screen.fill(0,0,0)
drawText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.update()
if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break
clock.tick(60)
drawText('Game Over!', font, screen, (750 / 3), ( 750 / 3))
drawText('Press ENTER To Play Again.', font, screen, ( 750 / 3) - 80, (750 / 3) + 50)
pygame.display.update()
startGame()
Here's my new code after modifying it some
import pygame, random, sys
from pygame.locals import*
alienimg = pygame.image.load('C:\Python27\alien.png')
playerimg = pygame.image.load('C:\Python27\spaceship.png')
def playerCollision(): # a function for when the player hits an alien
for a in aliens:
if playerRect.colliderect(b['rect']):
return True
return False
def screenText(text, font, screen, x, y): #text display function
textobj = font.render(text, 1, (255, 255, 255))
textrect = textobj.get_rect()
textrect.topleft = (x,y)
screen.blit(textobj, textrect)
def main(): #this is the main function that starts the game
pygame.init()
screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')
font = pygame.font.SysFont("monospace", 55)
pressed = pygame.key.get_pressed()
aliens = []
score = 0
alienAdd = 0
addedaliens = 0
while True: #our while loop that actually runs the game
for event in pygame.event.get(): #key controls
if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
sys.exit()
elif event.type == KEYDOWN and event.key == pygame.K_LEFT:
playerRect.x -= 3
elif event.type == KEYDOWN and event.key == pygame.K_RIGHT:
playerRect.x += 3
playerImage = pygame.image.load('C:\\Python27\\spaceship.png').convert() # the player images
playerRect = playerImage.get_rect()
playerRect.topleft = (750 /2, 750 - 50)
alienImage = pygame.image.load('C:\\Python27\\alien.png').convert() #alien images
alienAdd += 1
pygame.display.update()
if alienAdd == addedaliens: # randomly adding aliens of different sizes and speeds
aliendAdd = 0
alienSize = random.randint(10, 40)
newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
aliens.append(newAlien)
for a in aliens[:]:
if a['rect'].top > 750:
aliens.remove(a) #removes the aliens when they get to the bottom of the screen
screen.blit(screen, (0,0))
screenText('Score %s' % (score), font, screen, 10, 0)
screen.blit(playerImage, playerRect)
for a in aliens:
screen.blit(b['surface'], b['rect'])
pygame.display.flip()
if playerCollision(playerRect, aliens):
if score > topScore:
topScore = score
break
clock.tick(60)
screenText('Game Over!', font, screen, (750 / 6), ( 750 / 6))
screenText('Press ENTER To Play Again.', font, screen, ( 750 / 6) - 80, (750 / 6) + 50)
pygame.display.update()
main()
I still see several issues with your code and I think you're trying to do too much at once for the very beginning. Try to keep it as simple as possible. Try creating a display and draw some image:
import pygame
pygame.init()
display = pygame.display.set_mode((750, 750))
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
display.blit(img, (0, 0))
pygame.display.flip()
You'll have to adjust the img path of course. Running this you should either get an explicit Error (which you should then post in another thread) or see your img on the screen. BUT the program will not respond as there's no event handling and no main loop at all.
To avoid this, you could introduce a main loop like:
import sys
import pygame
pygame.init()
RESOLUTION = (750, 750)
FPS = 60
display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
while True: # <--- game loop
# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)
This should result in a program that displays the same img over and over, and it can be quit properly using the mouse. But still it's like a script, and if someone imported this, it would execute immediately, which is not what we want. So let's fix that as well and wrap it all up in a main function like this:
import sys
import pygame
#defining some constants
RESOLUTION = (750, 750)
FPS = 60
def main(): # <--- program starts here
# setting things up
pygame.init()
display = pygame.display.set_mode(RESOLUTION)
clock = pygame.time.Clock()
img = pygame.image.load("""C:\\Game Dev\\alien.png""")
while True: # <--- game loop
# check quit program
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# clear the screen
display.fill((0, 0, 0))
# draw the image
display.blit(img, (0, 0))
# update the screen
pygame.display.flip()
# tick the clock
clock.tick(FPS)
if __name__ == "__main__":
main()
The 'if name == "main":' ensures that the program does not execute when it's imported.
I hope this helps. And remember: Don't try too much all at once. Take small steps, one after another, and try to keep the control over your program. If needed, you can even put a print statement after every single line of code to exactly let you know what your program does and in what order.