如何解决在pygame中再次开始游戏
我正在为学校制作一个飞扬的鸟游戏,现在我想让如果jou碰到障碍物,游戏再次开始命中该对象是没有问题的,但是再次启动该代码的代码就是问题吗,有人知道吗当然,我已经有一个无限循环,所以我猜想anathor循环会让游戏疯狂,所以我希望有人能帮助我。
我的代码(如果有帮助的话):
with()
解决方法
如@Rabbid所述,要重新启动游戏,请重置所有游戏变量。您可以在函数中执行此操作,以便可以在游戏循环中调用它。
尝试此代码。按R
重新启动游戏。
import random
import time
import pygame
# need these variables for game play
i = jump = xSpeler = ySpeler = widthSpeler = heightSpeler = vel = vel1 = None
xo1 = yo1 = ho1 = wo1 = xo2 = yo2 = ho2 = wo2 = xo3 = yo3 = ho3 = wo3 = xo4 = yo4 = ho4 = wo4 = None
def initstate():
# link to global variables,prevent creation of local variables
global i,jump,xSpeler,ySpeler,widthSpeler,heightSpeler,vel,vel1
global xo1,yo1,ho1,wo1,xo2,yo2,ho2,wo2,xo3,yo3,ho3,wo3,xo4,yo4,ho4,wo4
i = 1
jump = 55
xSpeler = 50
ySpeler = 100
widthSpeler = 40
heightSpeler = 40
vel = 10
vel1 = 10
# obstacle 1
xo1 = 900
yo1 = 0
ho1 = 200
wo1 = 50
xo2 = 900
yo2 = 350
ho2 = 200
wo2 = 50
# obstacle 2
xo3 = 900
yo3 = 0
ho3 = 250
wo3 = 50
xo4 = 900
yo4 = 350
ho4 = 150
wo4 = 50
initstate() # init first time
def genObstacle():
# generate and return
# 1. pygame surface for top and bottom rects
# 2. initial position for top rect and bottom rect
topHeight = random.randint(10,200) # height for bottom obstacle
botHeight = random.randint(10,200) # height for top obstacle
top = pygame.Surface((10,topHeight)).convert()
bot = pygame.Surface((10,botHeight)).convert()
# return: top rect,bottom rect,top rect's position,bottom rect's position
return [top,bot,[800,0],500 - botHeight]]
win = pygame.display.set_mode((350,500))
pygame.display.set_caption("Flappy bird")
#obstacles = [pygame.draw.rect(win,(0,255,0),(xo1,ho1)) or pygame.draw.rect(win,ho1)),pygame.draw.rect(win,(xo2,ho2)) or pygame.draw.rect(win,ho2))]
#obstacles = [pygame.draw.rect(win,ho1))]
start = time.time()
now = time.time()
pygame.init()
bi = pygame.image.load('cubered.png')
yellow = pygame.image.load('cubeyellow.png')
yellow = pygame.transform.scale(yellow,(40,40))
pygame.display.flip()
run = True
while run:
win.blit(bi,0))
pygame.time.delay(55)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
ySpeler += vel
if ySpeler >= 500 - heightSpeler:
ySpeler = 500 - heightSpeler
xo1 -= vel1
xo2 -= vel1
if xo1 + wo1 < 0:
xo1 = 350
if xo2 + wo2 < 0:
xo2 = 350
obst1 = pygame.draw.rect(win,ho1))
obst2 = pygame.draw.rect(win,ho2))
if keys[pygame.K_SPACE] and xSpeler > vel and ySpeler > 0:
ySpeler -= jump
if keys[pygame.K_r]: # restart game
win.fill((0,0)) # clear screen
initstate() # init game state
win.blit(yellow,(xSpeler,ySpeler))
# if xo1 == xSpeler:
pygame.display.update()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。