How would I get my game over screen stay on the screen - python

import pygame, random, time
from time import sleep
from pygame import*
pygame.init()
myname=input('What is your name')
#set the window size
window= pygame.display.set_mode((800,600) ,0,24)
pygame.display.set_caption("Fruit Catch")
gameover=pygame.image.load('fifa.jpg')
#game variables
myscore=0
mylives=3
mouth_x=300
fruit_x=250
fruit_y=75
fruitlist=['broccoli.gif','chicken.gif']
#prepare for screen
myfont=pygame.font.SysFont("Britannic Bold", 55)
label1=myfont.render(myname, 1, (240, 0, 0))
label3=myfont.render(str(mylives), 1, (20, 255, 0))
#grapchics
fruit=pygame.image.load('data/chicken.png')
mouth=pygame.image.load('data/v.gif')
backGr=pygame.image.load('data/kfc.jpg')
#endless loop
running=True
while running:
if fruit_y>=460:#check if at bottom, if so prepare new fruit
fruit_x=random.randrange(50,530,1)
fruit_y=75
fruit=pygame.image.load('data/'+fruitlist[random.randrange(0,2,1)])
caught= fruit_x>=mouth_x and fruit_x<=mouth_x+300
else:fruit_y+=5
#check collision
if fruit_y>=456:
mylives-=1
if fruit_y>=440:
if fruit_x>=mouth_x and fruit_x<=mouth_x+300 :
myscore+=1
fruit_y=600#move it off screen
pygame.mixer.music.load('data/eating.wav')
if mylives==0:
window.blit(backg,(0,0))
pygame.time.delay(10)
window.blit(gameover,(0,0))
pygame.display.update()
#detect key events
for event in pygame.event.get():
if (event.type==pygame.KEYDOWN):
if (event.key==pygame.K_LEFT):
mouth_x-=55
if (event.key==pygame.K_RIGHT):
mouth_x+=55
label3=myfont.render(str(mylives), 1, (20, 255, 0))
label2=myfont.render(str(myscore), 1, (20, 255, 0))
window.blit(backGr,(0,0))
window.blit(mouth, (mouth_x,440))
window.blit(fruit,(fruit_x, fruit_y))
window.blit(label1, (174, 537))
window.blit(label2, (700, 157))
window.blit(label3, (700, 400))
pygame.display.update()
When my lives hit 0 the game over screen comes up but it flickers between that and the normal background.
How would I get it to stay on the screen?
I thinks its something to with the updates, but if I take either out it doesn't work

If line is 0 then you run some blits and update twice
First inside if mylives==0: (and it stay for awhile becaus you use delay(10) )
Second time at the end of loop.
Use:
if mylives==0:
#blit and update game over
else:
#blit and update normal game

Related

"Hello from the pygame community"

When I executed the following code, instead of an error it said "Hello from the pygame community. https://www.pygame.org/contribute.html". It would be easier for me if it just included the error so I could fix it myself without posting the code in stackoverflow (for privacy reasons).
Here's the code:
# import the pygame module, so you can use it
import pygame
# define a main function
def main():
# initialize the pygame module
pygame.init()
# load and set the logo
logo = pygame.image.load("logo32x32.png")
pygame.display.set_icon(logo)
pygame.display.set_caption("minimal program")
# create a surface on screen that has the size of 240 x 180
screen = pygame.display.set_mode((240, 180))
# define a variable to control the main loop
running = True
# main loop
while running:
# event handling, gets all event from the eventqueue
for event in pygame.event.get():
# only do something if the event is of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
running = False
# draw a green line from (0,0) to (100,100)
pygame.draw.line(screen, (0,255,0), (0,0), (100,100))
# draw a green line from (0,100) to (100,0)
pygame.draw.line(screen, (0,255,0), (0,100), (100,0))
# draw a rectangle outline
pygame.draw.rect(screen, (0,255,0), (60,60,100,50), 1)
# draw a filled in rectangle
pygame.draw.rect(screen, (0,255,0), (60,120,100,50))
# draw a circle
pygame.draw.circle(screen, (0,255,0), (120,60), 20, 0)
# draw a circle outline
pygame.draw.circle(screen, (0,255,0), (120,60), 20, 1)
# draw a polygon
pygame.draw.polygon(screen, (0,255,0), ((140,60),(160,80),(160,100),(140,120),(120,100),(120,80)), 0)
# draw a filled in poly
pygame.draw.polygon(screen, (0,255,0), ((140,60),(160,80),(160,100),(140,120),(120,100),(120,80)), 1)
# draw a text
font = pygame.font.Font(None, 36)
text = font.render("Hello There", 1, (10, 10, 10))
textpos = text.get_rect()
textpos.centerx = screen.get_rect().centerx
screen.blit(text, textpos)
# update the screen
pygame.display.flip()
# quit pygame properly to clean up resources
pygame.quit()
# end of the code
That isn't an error. That line is printed when you import pygame. None of your code is producing an error because none of it is being called. After you define the main function, make sure to call main().

TypeError: 'int' object has no attribute '__getitem__' error

I have a list to store the X and Y of bullets in my game, and when spacebar is pushed, it adds an x and y to the list, and then it should call both values and draw them. i know i need to delete them after they leave the screen, but atm when i hit space this error pops up
TypeError:'int' object has no attribute '__getitem__'
here's my code:
#start system
import pygame, sys, random
from pygame.locals import*
pygame.init()
fps=50
Clock=pygame.time.Clock()#use fps as system time
#set up a list of STUFF
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 100, 0)
RED = ( 100, 0, 0)
YELLOW= (255,255,0)
ORANGE= (255,165,0)
screensizex=800
screensizey=600
bullets=[]
screenarea=pygame.display.set_mode((screensizex,screensizey))
pygame.display.set_caption("space invaders")
player_x=250
# end of variable init, begin main loop!
while 1==1:
#key roster
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_d and player_x<screensizex-25:
player_x+=25
if event.key==K_a:
player_x-=25
if event.key==K_SPACE:
bullets.insert(player_x,665)
#drawing to screen
screenarea.fill(WHITE)
for bullet in bullets:
pygame.draw.rect(screenarea,ORANGE,Rect(bullet[0],bullet[1],5,10))
pygame.draw.rect(screenarea,GREEN,(0,screensizey-100,screensizex,100))
pygame.draw.rect(screenarea,RED,(player_x,screensizey-125,25,25))
pygame.display.update()
Clock.tick(fps)
can you help me out? how do i call both values?
It looks like you meant to put tuples into your list, so this:
bullets.insert(player_x,665)
Should be:
bullets.append((player_x,665))

Pygame: Drawing a circle after input

this seemed like a really simple code, this is why I'm even more confused that it won't work. I'm creating a game that draws different lines of a picture and, after each shape, asks the user what it could be. My problem is that it won't even draw the first circle once I have the input()-part included, but without the input, it works perfectly fine.
import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1000, 600))
pygame.display.set_caption('PyDoodle')
clock= pygame.time.Clock()
clock.tick(30)
#importing background pictures:
backPimg = pygame.image.load('Wood.jpg')
backPimg = pygame.image.load('Paper.jpg')
backWx = 0
backWy = 0
backPx = 250
backPy = 0
screen.blit(backWimg, (backWx, backWy))
screen.blit(backPimg, (backPx, backPy))
#colors
black = (0, 0, 0)
#solutions
snowman = ('snowman'.capitalize(), 'snow man'.upper(), 'snowman', 'snow man')
#MAIN GAME
while True:
for event in pygame.event.get()
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
#DRAWING #1: SNOWMAN
#circle 1 - the part that's getting on my nerves
pygame.draw.circle(screen, black, (500,400), 70, 2)
guess1 = raw_input('Your guess:\n')
It'd be really nice if you could have a look at it, maybe you have some suggestions.
The problem is, that pygame does not receive any events while raw_input is waiting for input. (You are not in the event-loop at that point.) As a result you never execute pygame.display.update().
Add pygame.display.update() after pygame.draw.circle(screen, black, (500,400), 70, 2). However then if a redraw of the window is necessary it will not be executed until the input is finished still.
Probably you should use input mechanisms provided by pygame instead.

How to display text in pygame? [duplicate]

This question already has answers here:
pygame - How to display text with font & color?
(7 answers)
Closed 2 years ago.
I can't figure out to display text in pygame.
I know I can't use print like in regular Python IDLE but I don't know how.
import pygame, sys
from pygame.locals import *
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = ( 255, 0, 0)
pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('P.Earth')
while 1: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.display.update()
import time
direction = ''
print('Welcome to Earth')
pygame.draw.rect(screen, RED, [55,500,10,5], 0)
time.sleep(1)
This is only the beginning part of the whole program.
If there is a format that will allow me to show the text I type in the pygame window that'd be great. So instead of using print I would use something else. But I don't know what that something else is.
When I run my program in pygame it doesn't show anything.
I want the program to run in the pygame window instead of it just running in idle.
You can create a surface with text on it. For this take a look at this short example:
pygame.font.init() # you have to call this at the start,
# if you want to use this module.
my_font = pygame.font.SysFont('Comic Sans MS', 30)
This creates a new object on which you can call the render method.
text_surface = my_font.render('Some Text', False, (0, 0, 0))
This creates a new surface with text already drawn onto it.
At the end you can just blit the text surface onto your main screen.
screen.blit(text_surface, (0,0))
Bear in mind, that every time the text changes, you have to recreate the surface again, to see the new text.
There's also the pygame.freetype module which is more modern, works with more fonts and offers additional functionality.
Create a font object with pygame.freetype.SysFont() or pygame.freetype.Font if the font is inside of your game directory.
You can render the text either with the render method similarly to the old pygame.font.Font.render or directly onto the target surface with render_to.
import pygame
import pygame.freetype # Import the freetype module.
pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255,255,255))
# You can use `render` and then blit the text surface ...
text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
screen.blit(text_surface, (40, 250))
# or just `render_to` the target surface.
GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))
pygame.display.flip()
pygame.quit()
When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:
import pygame
def text_to_screen(screen, text, x, y, size = 50,
color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
try:
text = str(text)
font = pygame.font.Font(font_type, size)
text = font.render(text, True, color)
screen.blit(text, (x, y))
except Exception, e:
print 'Font Error, saw it coming'
raise e
Then when that has been imported when I want to display text taht updates E.G score I do:
Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)
If it is just normal text that isn't being updated:
Funk.text_to_screen(screen, 'Text', xpos, ypos)
You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)
This is slighly more OS independent way:
# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)
# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))

Update display all at one time PyGame

Using PyGame, I get flickering things. Boxes, circles, text, it all flickers. I can reduce this by increasing the wait between my loop, but I though maybe I could eliminate it by drawing everything to screen at once, instead of doing everything individually. Here's a simple example of what happens to me:
import pygame, time
pygame.init()
screen = pygame.display.set_mode((400, 300))
loop = "yes"
while loop=="yes":
screen.fill((0, 0, 0), (0, 0, 400, 300))
font = pygame.font.SysFont("calibri",40)
text = font.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
pygame.display.update()
font = pygame.font.SysFont("calibri",20)
text = font.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
pygame.display.update()
time.sleep(0.1)
The "Begin" button flickers for me. It could just be my slower computer, but is there a way to reduce or eliminate the flickers? In more complex things I'm working on, it gets really bad. Thanks!
I think part of the problem is you're calling 'pygame.display.update()' more then once. Try calling it only once during the mainloop.
Some other optimizations:
You could take the font creation code out of the main loop to speed things up
Do loop = True rather then loop = "yes"
To have a more consistent fps, you could use Pygame's clock class
So...
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
loop = True
# No need to re-make these again each loop.
font1 = pygame.font.SysFont("calibri",40)
font2 = pygame.font.SysFont("calibri",20)
fps = 30
clock = pygame.time.Clock()
while loop:
screen.fill((0, 0, 0), (0, 0, 400, 300))
text = font1.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
text = font2.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
pygame.display.update() # Call this only once per loop
clock.tick(fps) # forces the program to run at 30 fps.
You're updating your screen 2 times in a loop, one for drawing first text(TextA) and one for second text(Begin).
After your first update, only first text appears, so you can't see begin text between first update and second update. This causes flickering.
Update your screen after drawing everything. In your case, remove first pygame.display.update().
You're redrawing the content of your entire screen every 0.1 seconds. It's much more common and faster to keep track of the changes you actual make and only update the rects that actually contain changed content. So draw everything outside of your loop and have your events modify the screen and keep track of the rectangles that actually are changed.
So something like this:
import pygame, time
pygame.init()
screen = pygame.display.set_mode((400, 300))
screen.fill((0, 0, 0), (0, 0, 400, 300))
font = pygame.font.SysFont("calibri",40)
text = font.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
font = pygame.font.SysFont("calibri",20)
text = font.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
loop = "yes"
counter = 0
dirty_rects = []
while loop=="yes":
pygame.display.update()
time.sleep(0.1)
# Handle events, checks for changes, etc. Call appropriate functions like:
counter += 1
if counter == 50:
font = pygame.font.SysFont("calibri",20)
text = font.render("We hit 50!", True,(255,255,255))
screen.blit(text,(50,100))
dirty_rects.append(Rect((50,100),text.get_size()))
Pygame has a Buffer system to avoid flickering, so you should draw them as you are doing, but update only once at the end:
...
while loop=="yes":
screen.fill((0, 0, 0), (0, 0, 400, 300))
font = pygame.font.SysFont("calibri",40)
text = font.render("TextA", True,(255,255,255))
screen.blit(text,(0,0))
font = pygame.font.SysFont("calibri",20)
text = font.render("Begin", True,(255,255,255))
screen.blit(text,(50,50))
pygame.display.update() # only one update
time.sleep(0.1)
And Pygame has a Clock Class that is better than time.sleep(0.1) if you wan't to keep a framerate.

Categories