我正在尝试创建涂鸦跳跃风格的游戏。该代码仅包括平台和开始屏幕。我需要游戏循环才能在开始屏幕上完成按钮功能。
如何在我的代码中进行游戏循环/定义游戏循环?我不断收到语法错误,说我的游戏循环未定义。
我的代码:
import pygame as pg
import sys,time,random
pg.init()
res_x,res_y=800,600
screen = pg.display.set_mode((res_x,res_y))
screen.fill((0,0,0))
pg.display.update()
clock=pg.time.Clock()
#COLOURS
light_green=(124,252,0)
green=(50,205,50)
light_red=(255,99,71)
red=(128,0,0)
yellow=(255,215,0)
black=(0,0,0)
white=(255,255,255)
light_grey=(119,136,153)
dark_pink=(220,20,60)
light_pink=(255,108,180)
sky_blue=(0,255,255)
#start screen
def text_object(text, font,):
textsurface=font.render(text,True,(255,255,255))
return textsurface, textsurface.get_rect()
def button(msg1,x1,y1,l1,h1,ic1,ac1,action=None):
mouse=pg.mouse.get_pos()
click=pg.mouse.get_pressed()
if x1+l1>mouse[0]>x1 and y1+h1>mouse[1]>y1:
button_start=pg.draw.rect(screen,ac1,(x1,y1,l1,h1),)
if click[0]==1 and action!= None:
if action=='play':
game_loop()
else:
button_start=pg.draw.rect(screen,ic1,(x1,y1,l1,h1),)
smalltext=pg.font.Font('freesansbold.ttf',30,)
textsurf, textrect= text_object(msg1,smalltext)
textrect.center=((x1+(l1/2)),(y1+(h1/2)))
screen.blit(textsurf, textrect)
def start():
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
screen.fill((119,136,153))
bigtext=pg.font.SysFont('arial.ttf',100)
textsurf,textrect= text_object('Maze Runner',bigtext)
textrect.center=((res_x/2),(res_y/2))
screen.blit(textsurf,textrect)
button('GO!',110,400,200,50,green,light_green,'play')
button('QUIT',450,400,200,50,red,light_red,'quit')
pg.display.update()
clock.tick(15)
start()
#platform
rect_x=random.randrange(0,200)
rect_y=random.randrange(50,120)
rect_l=300
rect_h=50
rect1_x=random.randrange(230,430)
rect1_y=random.randrange(150,300)
rect1_l=random.randrange(50,200)
rect1_h=50
rect2_x=random.randrange(430,550)
rect2_y=random.randrange(300,450)
rect2_l=100
rect2_h=50
rect3_x=random.randrange(630,750)
rect3_y=random.randrange(450,500)
rect3_l=50
rect3_h=50
def game_loop():
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
screen.fill(black)
base=pg.draw.rect(screen,sky_blue,(0,540,800,60), )
platform=pg.draw.rect(screen, yellow, [rect_x,rect_y,rect_l,rect_h],5)
platform1=pg.draw.rect(screen,white,[rect1_x,rect1_y,rect1_l,rect1_h],5)
platform2=pg.draw.rect(screen,dark_pink,[rect2_x,rect2_y,rect2_l,rect2_h],5)
platform2=pg.draw.rect(screen,light_pink,[rect3_x,rect3_y,rect3_l,rect3_h],5)
pg.display.update()
答案 0 :(得分:1)
NameError: name 'game_loop' is not defined
之所以引发,是因为您在使用game_loop()
进行定义之前在button
函数中调用了def game_loop()
。只需定义game_loop
函数,然后再调用start()
和随后的button()
。
def game_loop():
# Code omitted.
start() # Call start() afterwards.