Related
when ever I try to display to render this text 1 by 1 it seems to slow my game down and make everything run slow and for some reason it starts the text as well I want it to end when its finished typing the text VIDEO< as you can see in the video the text keeps playing the game keeps lagging for some reason when ever each of the text is rendered on the screen
def show_text(string):
WHITE = (255, 255, 255)
text = ''
font = pygame.font.Font("Alice.ttf", 30)
for i in range(len(string)):
text += string[i]
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.center = (700/2, 800/2)
window.blit(text_surface, text_rect)
pygame.display.update()
pygame.time.wait(100)
display_text_animation('Hello World!')
heres the full code there all rects execept the Alice.tff < text style
import pygame, sys
from pygame.locals import *
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
pygame.init()
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
class player:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
def draw(self):
self.rect.topleft = (self.x,self.y)
pygame.draw.rect(DISPLAYSURF,self.color,self.rect)
white = (120,120,120)
player1 = player(150,150,50,50,white)
def display_text_animation(string):
text = ''
for i in range(len(string)):
text += string[i]
font = pygame.font.Font("Alice.ttf", 30)
text_surface = font.render(text, True, white)
text_rect = text_surface.get_rect()
DISPLAYSURF.blit(text_surface, text_rect)
pygame.display.update()
pygame.time.wait(100)
def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
player1.x += 5
if keys[pygame.K_a]:
player1.x -= 5
DISPLAYSURF.fill((0,0,0))
player1.draw()
display_text_animation('Hello World!')
main()
Do not create the pygame.font.Font object in every frame. Creating a font object is very time consuming. Every time the Font object is created, the font file ("Alice.ttf") must be read and interpreted. Create the Fontobject before the application loop during initialization.
Furthermore do not animate the text in a loop use the application loop. Use pygame.time.get_ticks() to measure the time. Calculate the number of letters to be displayed as a function of time:
font = pygame.font.Font("Alice.ttf", 30)
def display_text_animation(string, start_time):
current_time = pygame.time.get_ticks()
letters = (current_time - start_time) // 100
text = string[:letters]
WHITE = (255, 255, 255)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.center = (700/2, 800/2)
DISPLAYSURF.blit(text_surface, text_rect)
def main():
text = 'Hello World!'
start_time = pygame.time.get_ticks()
clock = pygame.time.Clock()
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
player1.x += 5
if keys[pygame.K_a]:
player1.x -= 5
DISPLAYSURF.fill((0,0,0))
player1.draw()
display_text_animation(text, start_time)
pygame.display.update()
When ever you want to animate a new text you just have to set text and start_time. e.g:
text = "New text"
start_time = pygame.time.get_ticks()
Minimal typewriter effect example:
import pygame
pygame.init()
window = pygame.display.set_mode((500, 150))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (32, 32, 32), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
text = 'Hello World'
text_len = 0
typewriter_event = pygame.USEREVENT+1
pygame.time.set_timer(typewriter_event, 100)
text_surf = None
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == typewriter_event:
text_len += 1
if text_len > len(text):
text_len = 0
text_surf = None if text_len == 0 else font.render(text[:text_len], True, (255, 255, 128))
window.blit(background, (0, 0))
if text_surf:
window.blit(text_surf, text_surf.get_rect(midleft = window.get_rect().midleft).move(40, 0))
pygame.display.flip()
pygame.quit()
exit()
I have been working on a game for a school project and I have these blocks come down the screen and you need to dodge them. I need to turn the blank drawn rectangles coming down the screen into a picture of a car I have.
This is my code so far:
import pygame
import time
import random
pygame.init()
skate_sound = pygame.mixer.Sound("skateboard.wav")
pygame.mixer.music.load("menu_audio.wav")
ouch = pygame.mixer.Sound("ouch.wav")
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
cyan = (71, 148, 192)
green = (0, 255, 0)
dark_red = (200, 0 ,0)
dark_green = (0, 180 ,0)
grass_green = (39, 131, 51)
man_width = 35
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Skate or Die')
clock = pygame.time.Clock()
manImg = pygame.image.load('skater1.png')
def objects_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, black)
gameDisplay.blit(text, (0,0))
def objects(objectx, objecty, objectw, objecth, color):
pygame.draw.rect(gameDisplay, color, [objectx, objecty, objectw, objecth])
#^^NEED TO CHANGE TO AN IMAGE CALLED TAXI.PNG CAN SOMEONE PLEASE FIX FOR ME
def man(x,y):
gameDisplay.blit(manImg,(x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
pygame.mixer.Sound.play(ouch)
pygame.mixer.Sound.stop(skate_sound)
message_display("You Died!")
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ic,(x,y,w,h))
if click[0] == 1 and action != None:
if action == "play":
game_loop()
elif action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def game_intro():
pygame.mixer.music.play(-1)
intro = True
while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Skate or Die!", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start",150,450,100,50,dark_green,green,"play")
button("Quit",550,450,100,50,dark_red,red,"quit")
#pygame.draw.rect(gameDisplay, red,(550,450,100,50))
pygame.display.update()
clock.tick(3)
def game_loop():
pygame.mixer.Sound.stop(ouch)
pygame.mixer.music.stop()
pygame.mixer.Sound.play(skate_sound)
x = (display_width * 0.45)
y = (display_height * 0.75)
x_change = 0
object_startx = random.randrange(0, display_width)
object_starty = -600
object_speed = 8
object_width = 100
object_height = 80
dodged = 0
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
#gameDisplay.fill(white)
bg = pygame.image.load("bg.png")
gameDisplay.blit(bg, (0, 0))
man(x,y)
# objects(objectx, objecty, objectw, objecth, color)
objects(object_startx, object_starty, object_width, object_height, cyan)
object_starty += object_speed
man(x,y)
objects_dodged(dodged)
if x > display_width - man_width or x < 0:
crash()
if object_starty > display_height:
object_starty = 0 - object_height
object_startx = random.randrange(0, display_width)
dodged += 1
object_speed += 0.7
object_width += (dodged * 1)
if y < object_starty+object_height:
print('y crossover')
if x > object_startx and x < object_startx + object_width or x+man_width > object_startx and x + man_width < object_startx+object_width:
print('x crossover')
crash()
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
If someone could fix it so it displays taxi.png instead of the rectangles as objects it would be greatly appreciated.
To draw the picture of the car instead of a rectangle, just do the same thing that you are doing with the man.
Under the line that is manImg = pygame.image.load('skater1.png'), put this line: carImg= pygame.image.load('taxi.png') This will load the picture of the car and it will be called carImg.
Now, you need to draw that picture onto the screen. Replace your objects function:
def objects(objectx, objecty, objectw, objecth, color):
pygame.draw.rect(gameDisplay, color, [objectx, objecty, objectw, objecth])
with a function to draw a car.
def drawCar(x,y):
pygameDisplay.blit(carImg,(x,y))
Notice how it is very similar to the man function, the only difference is the image that is drawn.
The last thing you need to do is actually call that drawCar function. Replace this line
objects(object_startx, object_starty, object_width, object_height, cyan)
with this one: drawCar(object_startx,object_starty)
I would recommend doing these changes yourself, it will help you learn. But if you're in a hurry, the final code, with all of these changes made, should be:
import pygame
import time
import random
pygame.init()
skate_sound = pygame.mixer.Sound("skateboard.wav")
pygame.mixer.music.load("menu_audio.wav")
ouch = pygame.mixer.Sound("ouch.wav")
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
cyan = (71, 148, 192)
green = (0, 255, 0)
dark_red = (200, 0 ,0)
dark_green = (0, 180 ,0)
grass_green = (39, 131, 51)
man_width = 35
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Skate or Die')
clock = pygame.time.Clock()
manImg = pygame.image.load('skater1.png')
carImg= pygame.image.load('taxi.png')
def objects_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, black)
gameDisplay.blit(text, (0,0))
def drawCar(x,y):
pygameDisplay.blit(carImg,(x,y))
def man(x,y):
gameDisplay.blit(manImg,(x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
pygame.mixer.Sound.play(ouch)
pygame.mixer.Sound.stop(skate_sound)
message_display("You Died!")
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ic,(x,y,w,h))
if click[0] == 1 and action != None:
if action == "play":
game_loop()
elif action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def game_intro():
pygame.mixer.music.play(-1)
intro = True
while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Skate or Die!", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start",150,450,100,50,dark_green,green,"play")
button("Quit",550,450,100,50,dark_red,red,"quit")
#pygame.draw.rect(gameDisplay, red,(550,450,100,50))
pygame.display.update()
clock.tick(3)
def game_loop():
pygame.mixer.Sound.stop(ouch)
pygame.mixer.music.stop()
pygame.mixer.Sound.play(skate_sound)
x = (display_width * 0.45)
y = (display_height * 0.75)
x_change = 0
object_startx = random.randrange(0, display_width)
object_starty = -600
object_speed = 8
object_width = 100
object_height = 80
dodged = 0
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
#gameDisplay.fill(white)
bg = pygame.image.load("bg.png")
gameDisplay.blit(bg, (0, 0))
man(x,y)
# objects(objectx, objecty, objectw, objecth, color)
drawCar(object_startx,object_starty)
object_starty += object_speed
man(x,y)
objects_dodged(dodged)
When you follow tutorials online, don't just copy and paste the code. Make sure that you understand what is happening so that in the future, you can do it yourself.
I have my flask file and a seperate file which contains a pygame. Both work seperately, How would i combine the flask so that when i press my link on my webpage it starts running the external file, how would I call it?
from flask import Flask, render_template
import going
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/my-link/')
def my_link():
return going.main()
if __name__ == '__main__':
app.run(debug=True)
At the moment I am trying to run the main() method to initialize the program.
import pygame
##1100 * 800
size = [1100, 800]
score1 = 0
score2 = 0
blue = (100, 149, 237)
black = (0, 0, 0)
brown = (165,42,42)
white = (255, 255, 255)
green =(0,100,0)
red = (255,0,0)
dark_red = (200,0,0)
grey = (100,100,100)
other_grey = (0,0,100)
background = 'Mahogany.jpg'
pass_count = 0
player = 1
clock = pygame.time.Clock()
class Player(object):
def ___init__(self,id):
self.id = 1
def quitGame(self):
pygame.quit()
quit()
def pass_turn(self):
global pass_count
pass_count += 1
if pass_count == 2:
quitGame()
def score(player_text, score):
return player_text + str(score)
class Stone(object):
def __init__(self,board,position,color):
self.board = board
self.position = position
self.color = color
self.placeStone()
def placeStone(self):
coords = (self.position[0] * 50, self.position[1] * 50)
pygame.draw.circle(self.board,self.color,coords,20,0)
pygame.display.update()
class Board(object):
def draw_board(self):
for i in range(12):
for j in range(12):
rect = pygame.Rect(55 + (50 * i), 100 + (50 * j), 50, 50)
pygame.draw.rect(background, blue, rect, 1)
screen.blit(background, (0,0))
pygame.display.update()
def text_objects(self,text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def button(self,msg,x,y,w,h,ic,ac,action = None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(screen, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(screen, ic,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = self.text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
screen.blit(textSurf, textRect)
def game_intro(self):
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(background, (0,0))
largeText = pygame.font.SysFont("comicsansms",60)
TextSurf, TextRect = self.text_objects("GONLINE", largeText)
TextRect.center = ((1100/2),(800/2))
screen.blit(TextSurf, TextRect)
self.button("Play!",200,500,100,100,grey,other_grey,self.play_game)
self.button("Quit!",700,500,100,100,red,dark_red,Player.quitGame)
pygame.display.update()
clock.tick(15)
def play_game(self):
width = 20
height = 20
space_between = 5
global player
finish = False
self.draw_board()
while not finish:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finish = True
elif event.type == pygame.MOUSEBUTTONDOWN and player == 1:
position = pygame.mouse.get_pos()
if (event.button == 1) and (position[0] > 55 and position[0] < 710) and (position[1] > 100 and position[1] < 750):
x = int(round(((position[0]) / 50.0), 0))
y = int(round(((position[1]) / 50.0), 0))
Stone(screen,(x,y),white)
player = 2
elif event.type == pygame.MOUSEBUTTONDOWN and player == 2:
position = pygame.mouse.get_pos()
if (event.button == 1) and(position[0] > 55 and position[0] < 710) and (position[1] > 100 and position[1] < 750):
x = int(round(((position[0]) / 50.0), 0))
y = int(round(((position[1] ) / 50.0), 0))
Stone(screen,(x,y),black)
player = 1
clock.tick(60)
self.button("Pass!",750,200,100,100,grey,other_grey,Player.pass_turn)
self.button("Quit!",950,200,100,100,red,dark_red,Player.quitGame)
self.button(score("Player 1: ", score1),750,400,300,110,white,white)
self.button(score("Player 2: ",score2),750,600,300,110,white, white)
pygame.display.update()
pygame.quit()
def main():
player = Player()
board = Board()
board.game_intro()
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption("Go_Online")
background = pygame.image.load(background).convert()
main()
Here is the main game file
It seems that the two ways you try to call your game are slightly different.
The successful way, which seems to be something like
$ python going.py
runs this code
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption("Go_Online")
background = pygame.image.load(background).convert()
main()
The flask route, when triggered runs this
return going.main()
You're missing some setup. My guess is that the bottom of your going.py should look like this.
def main():
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption("Go_Online")
background = pygame.image.load(background).convert()
player = Player()
board = Board()
board.game_intro()
if __name__ == '__main__':
main()
I've been learning Python the easy (for me) way: simple video game example tutorials from sentdex on youtube. The concepts which I had not already known are made much clearer in the context of something for which I see value like a simple game. Anyway, I have come to an issue; for some reason, I cannot get a menu page to blit. I originally followed the tutorial very closely, with an eye for punctuation, capitalization and proper indentation as I see that seems to be the n00bs most consistent pitfall. However, the tutorial did not work for that section, and the program goes right into the game loop, even when game over. I have tried other methods prescribed throughout here, google, and youtube, but nothing seems to be working! I get a non-descriptive "syntax error", but as far as I can tell, the vital bits are wired up right. I'm sure I'm just being a blind noob, but some simple analysis would be much appreciated on this code!
NOTE: I know I have some danglers like how I imported Pickle but haven't used it yet, those are all just reminders for the next steps, soon to be fleshed out as soon as this menu problem is resolved.
Running python (with pygame) 2.7, since I cant get pygame to work on python 3.
I have both Eric5 and pycharm, I am running Debian Jessie with a backported Cinnamon (And I believe the kernel to, but I might be wrong)
#!/urs/bin/python2.7
import random
import pygame
import time
##import pickle
pygame.init()
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Zoomin' Zigs")
#Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
#asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
menuactive = True
#FUNCTIONS
##def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
##def leftclick():
##
## if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
## mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades (smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
time.sleep(3)
menuscreen()
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
pygame.Rect(gamedisplay (x, y, w, h))
def text_objects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2), (display_height/2))
gamedisplay.blit(TextSurf, TextRect)
def button(x, y, w, h,):
if x+w > mousecoords[0] > x and y+h > mousecoords[1] >y:
pygame.quit()
quit()
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, blue)
gamedisplay.blit(text, (30,100))
################################MENU###################################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
else:
time.sleep(3)
game_loop()
gamedisplay.blit(menuimage (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP###############################################
def game_loop():
#CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
#SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
while not menuactive:
for event in pygame.event.get():
# GAME QUIT EVENT
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(event)
x += x_change
gamedisplay.blit(background, (0, 0))
smbarricades (smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
#OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
#DODGE COUNT
dodged += 1
#CRASHESloop
if y <= smbar_starty+smbar_height and y >= smbar_starty+smbar_height and x <= smbar_startx+car_width and x >= smbar_startx-car_width:
crash()
menuactive = True
pygame.display.update()
clock.tick(60)
########################################################################################
menuscreen()
game_loop()
pygame.quit()
quit()
Hey I saw your code and did necessary changes And Its Working now next time kindly provide us the whole details.
#!/urs/bin/python2.7
import random
import pygame
import time
# import pickle
menuactive = True
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Zoomin' Zigs")
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
# asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
# FUNCTIONS
# def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
# def leftclick():
##
# if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades(smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
# menuscreen()
# def button(x, y, w, h,):
# mousecoords = pygame.mouse.get_pos()
# if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
# pygame.Rect(gamedisplay (x, y, w, h))
def text_objects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gamedisplay.blit(TextSurf, TextRect)
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x + w > mousecoords[0] > x and y + h > mousecoords[1] > y:
# pygame.quit()
# quit()
global menuactive
menuactive = False
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: " + str(count), True, blue)
gamedisplay.blit(text, (30, 100))
################################MENU######################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
global menuactive
while menuactive:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
menuactive = False
else:
# time.sleep(3)
game_loop()
gamedisplay.blit(menuimage, (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP#################################
def game_loop():
# CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
# SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
global menuactive
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# pygame.quit()
menuactive = False
# CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
print(event)
x += x_change
gamedisplay.blit(background, (0, 0))
smbarricades(smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
# OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
# DODGE COUNT
dodged += 1
# CRASHESloop
if y <= smbar_starty + smbar_height and y >= smbar_starty + smbar_height and x <= smbar_startx + car_width and x >= smbar_startx - car_width:
crash()
menuactive = False
pygame.display.update()
clock.tick(60)
##########################################################################
if __name__ == '__main__':
pygame.init()
menuscreen()
# game_loop()
pygame.quit()
quit()
I am wondering why it is that my "GO" button will not toggle the
def game_start()
permanently, it toggles it while holding the button, but when you let go of the button its goes back to the main menu?
I am also curious to if there is a way of making the text and buttons vanish when
you press the go button as the game has start?
I am quite new to python so an explanation would be great with any code I have made a mistake on and or need to add/change.
import sys
import pygame
from pygame.locals import *
pygame.init()
size = width, height = 720, 480
speed = [2, 2]
#Colours
black = (0,0,0)
blue = (0,0,255)
green = (0,200,0)
red = (200,0,0)
green_bright = (0,255,0)
red_bright = (255,0,0)
screen = pygame.display.set_mode(size)
#Pictures
road = pygame.image.load(r"C:\Users\John\Desktop\Michael\V'Room External\1.png")
BackgroundPNG = pygame.image.load(r"C:\Users\John\Desktop\Michael\V'Room External\BackgroundPNG.png")
carImg = pygame.image.load(r"C:\Users\John\Desktop\Michael\V'Room External\Sp1.png").convert_alpha()
pygame.display.set_caption("Broom! || BETA::00.0.3")
clock = pygame.time.Clock()
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
print(mouse)
print(click)
screen.fill(blue)
screen.blit(BackgroundPNG,(0,0))
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("V'Room!", largeText)
TextRect.center = ((width/2),(height/2))
screen.blit(TextSurf, TextRect)
#Button
if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, green_bright,(75,400,100,50))
if click != None and click[0] == 1:
print("GO == 1 ! == None")
x = 350
y = 370
game_start()
else:
pygame.draw.rect(screen, green,(75,400,100,50))
smallText = pygame.font.Font("freesansbold.ttf",20)
TextSurf, TextRect = text_objects("GO", smallText)
TextRect.center = ((75+(100/2)),(400+(50/2)))
screen.blit(TextSurf, TextRect)
if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, red_bright,(550,400,100,50))
if click != None and click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(screen, red,(550,400,100,50))
TextSurf, TextRect = text_objects("Exit", smallText)
TextRect.center = ((550+(100/2)),(400+(50/2)))
screen.blit(TextSurf, TextRect)
pygame.display.flip()
pygame.display.update()
clock.tick(15)
def game_start():
print("Car Loaded Sucessfully")
screen.blit(road, (0,0))
screen.blit(carImg, (350,370))
game_intro()
One of solution is to use game_started variable instead of function game_start() and use it to decide what to draw - title or car and road, GO or STOP button, etc.
I use rectangles in place of bitmaps to make full working example.
import pygame
# --- constants ----
size = width, height = 720, 480
speed = [2, 2]
#Colours
black = (0,0,0)
blue = (0,0,255)
green = (0,200,0)
red = (200,0,0)
green_bright = (0,255,0)
red_bright = (255,0,0)
# --- functions ---
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_intro():
largeText = pygame.font.Font('freesansbold.ttf',115)
smallText = pygame.font.Font("freesansbold.ttf",20)
text_vroom, text_vroom_rect = text_objects("V'Room!", largeText)
text_vroom_rect.center = ((width/2),(height/2))
text_go, text_go_rect = text_objects("GO", smallText)
text_go_rect.center = ((75+(100/2)),(400+(50/2)))
text_stop, text_stop_rect = text_objects("STOP", smallText)
text_stop_rect.center = ((75+(100/2)),(400+(50/2)))
text_exit, text_exit_rect = text_objects("Exit", smallText)
text_exit_rect.center = ((550+(100/2)),(400+(50/2)))
game_started = False
intro = True
while intro:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
screen.fill(blue)
#screen.blit(BackgroundPNG,(0,0))
# road and car - or title
if game_started:
screen.blit(road, (0,0))
screen.blit(carImg, (350,370))
else:
screen.blit(text_vroom, text_vroom_rect)
# Button GO/STOP
if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, green_bright,(75,400,100,50))
if click != None and click[0] == 1:
# toggle True/False
game_started = not game_started
else:
pygame.draw.rect(screen, green,(75,400,100,50))
# draw GO or STOP
if not game_started:
screen.blit(text_go, text_go_rect)
else:
screen.blit(text_stop, text_stop_rect)
# Button EXIT
if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, red_bright,(550,400,100,50))
if click != None and click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(screen, red,(550,400,100,50))
screen.blit(text_exit, text_exit_rect)
pygame.display.flip()
clock.tick(15)
# --- main ---
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Broom! || BETA::00.0.3")
#Pictures
road = pygame.surface.Surface( size )
road.fill(black)
carImg = pygame.surface.Surface( (10,10) )
road.fill(green)
clock = pygame.time.Clock()
game_intro()
EDIT: second solution is to create function (game_running) with own while loop, own buttons, etc.
I had to use pygame.time.wait() because pygame.mouse.get_pressed() is not good function for single click on button. Computer (and while loop) is too fast (for human click) and pygame.mouse.get_pressed() toggle button many times. Better to use pygame.event.get() for single click.
import pygame
# --- constants ----
size = width, height = 720, 480
speed = [2, 2]
#Colours
black = (0,0,0)
blue = (0,0,255)
green = (0,200,0)
red = (200,0,0)
green_bright = (0,255,0)
red_bright = (255,0,0)
# --- functions ---
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_intro():
text_vroom, text_vroom_rect = text_objects("V'Room!", largeText)
text_vroom_rect.center = ((width/2),(height/2))
text_go, text_go_rect = text_objects("GO", smallText)
text_go_rect.center = ((75+(100/2)),(400+(50/2)))
text_exit, text_exit_rect = text_objects("Exit", smallText)
text_exit_rect.center = ((550+(100/2)),(400+(50/2)))
running = True
while running:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
screen.fill(blue)
screen.blit(text_vroom, text_vroom_rect)
# Button GO
if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, green_bright,(75,400,100,50))
if click != None and click[0] == 1:
# wait because `pygame.mouse.get_pressed()` is too fast for human clik
pygame.time.wait(100)
# run game
game_running()
else:
pygame.draw.rect(screen, green,(75,400,100,50))
screen.blit(text_go, text_go_rect)
# Button EXIT
if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, red_bright,(550,400,100,50))
if click != None and click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(screen, red,(550,400,100,50))
screen.blit(text_exit, text_exit_rect)
pygame.display.flip()
clock.tick(15)
def game_running():
text_stop, text_stop_rect = text_objects("STOP", smallText)
text_stop_rect.center = ((75+(100/2)),(400+(50/2)))
text_exit, text_exit_rect = text_objects("Exit", smallText)
text_exit_rect.center = ((550+(100/2)),(400+(50/2)))
running = True
while running:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
screen.fill(blue)
#screen.blit(BackgroundPNG,(0,0))
# road and car - or title
screen.blit(road, (0,0))
screen.blit(carImg, (350,370))
# Button STOP
if 75+100 > mouse[0] > 75 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, green_bright,(75,400,100,50))
if click != None and click[0] == 1:
# return to menu
return
else:
pygame.draw.rect(screen, green,(75,400,100,50))
# draw STOP
screen.blit(text_stop, text_stop_rect)
# Button EXIT
if 550+100 > mouse[0] > 550 and 400+50 > mouse[1] > 400:
pygame.draw.rect(screen, red_bright,(550,400,100,50))
if click != None and click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(screen, red,(550,400,100,50))
screen.blit(text_exit, text_exit_rect)
pygame.display.flip()
clock.tick(15)
# --- main ---
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Broom! || BETA::00.0.3")
# pictures
road = pygame.surface.Surface( size )
road.fill(black)
carImg = pygame.surface.Surface( (10,10) )
road.fill(green)
# fonts
largeText = pygame.font.Font('freesansbold.ttf',115)
smallText = pygame.font.Font("freesansbold.ttf",20)
# others
clock = pygame.time.Clock()
game_intro()