pygame如何实现游戏重新开始的功能?
# 导入import pygame
from pygame.locals import *
from random import *
import sys
pygame.init()
screen = pygame.display.set_mode((600, 500))
# 绘制球和挡板
def ball(ax, ay):
pygame.draw.circle(screen, (255, 255, 0), (ax, ay), 20)
def fang(ax):
size = 300 + ax, 450, 100, 50
pygame.draw.rect(screen, (0, 255, 255), size)
# 绘制文本的函数
def print_text(font, text, ):
textImg = font.render(text, )
screen.blit(textImg, )
# zhuangtai = False
score = 0
gameover = False
fx = 0
move_x = 0
bx = randint(10, 590)
by = 0
# 循环
while True:
# 搜索事件
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEMOTION:
mouse_x, mouse_y = event.pos
move_x, move_y = event.rel
# 绘制画面
screen.fill((255, 255, 255))
# 逻辑判断
if by > 500:
by = 0
gameover = True
if 500 > by > 450 and fx + 100 > bx > fx:
score += 10
by = 0
bx = randint(10, 590)
# 绘制球
ball(bx, by)
if by == 500:
by = 0
bx = randint(10, 590)
by = by + 0.2
ball(bx, by)
# 绘制方块
fang(fx)
if move_x < 0:
fx -= 0.5
else:
fx += 0.5
if fx > 200:
fx = 200
if fx < -300:
fx = -300
if gameover:
while True:
for event in pygame.event.get():
if event.type == K_SPACE:
gameover = False
by = 0
break
pygame.display.update()
如代码,使用了状态变量控制进入一个死循环进行游戏的暂停功能,但是问题来了,当我按下空格键不会跳出这个死循环,按下空格键时变量该修改的也修改了,求教大佬这里的逻辑错误~! 本帖最后由 淡淡凉 于 2021-10-22 19:00 编辑
76行 if event.type == K_SPACE:有问题
# 导入
import pygame
from pygame.locals import *
from random import *
import sys
x,y=600,500
pygame.init()
screen = pygame.display.set_mode((x, y))
# 绘制球和挡板
def ball(ax, ay):
pygame.draw.circle(screen, (255, 255, 0), (ax, ay), 20)
def fang(ax):
size = ax, 450, 100, 50
pygame.draw.rect(screen, (0, 255, 255), size)
# 绘制文本的函数
def print_text(font, text, ):
textImg = font.render(text, )
screen.blit(textImg, )
# zhuangtai = False
score = 0
gameover = False
fx = 0
move_x = 0
bx = randint(10, 590)
by = 0
# 循环
while True:
# 搜索事件
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == MOUSEMOTION:
mouse_x, mouse_y = event.pos
move_x, move_y = event.rel
# 绘制画面
screen.fill((255, 255, 255))
# 绘制方块
fang(fx)
if move_x < 0:
fx -= 0.2
else:
fx += 0.2
if fx > 500:
fx = 500
if fx < 0:
fx = 0
# 逻辑判断
if by > 485:
#print(bx, by)
#ball(bx, by)
by = 0
gameover = True
#print('-------')
'''
elif by == 540:
by = 0
bx = randint(10, 590)
ball(bx, by)'''
elif 450 < by < 480 and fx < bx < fx + 100:
score += 10
by = 0
bx = randint(10, 590)
print(score)
# 绘制球
ball(bx, by)
else:
by = by + 0.1
ball(bx, by)
#print(fx,bx)
if gameover:
while gameover:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == KEYDOWN: #事件检测,事件类型KEYDOWN按下按键,KEYUP松开按键
if event.key == K_SPACE: #判断是否按下空格键
gameover = False
by = 0
#print(gameover)
#break
pygame.display.update()
页:
[1]