我正在尝试学习pygame,但是每次当我尝试向游戏中添加文本时,它的崩溃都会在我的碰撞课中很好地发挥作用:
def collisionDetection(x1,y1,w1,h1,x2,y2,w2,h2):
if (x2+w2>=x1>=x2 and y2+h1>=y1>=y2):
return True
elif (x2+w2>=x1+w1>=x2 and y2+h1>=y1>=y2):
return True
elif (x2+w2>=x1>=x2 and y2+h1>=y1+h1>=y2):
return True
elif (x2+w2>=x1+w1>=x2 and y2+h1>=y1+h1>=y2):
return True
else:
return False
但是当我将其添加到游戏循环中并且如果应该检测到碰撞的游戏时,这里是所有带有文本的代码
import pygame
import random
pygame.init()
win_width = 500
win_height = 500
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("Cubes Game")
gravity = 5
x = 200
y = 450
width = 80
height = 10
speed = 10
white = (255,255,255)
cube_speed = 0
cube = {"x": 200, "y" : 50, "width" : 80, "height": 35}
def text_objects(text, font):
textSurface = font.render(text, True, white)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('Kotta.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((win_width / 2), (win_height / 2))
win.blit(TextSurf, TextRect)
pygame.display.update()
def collisionDetection(x1,y1,w1,h1,x2,y2,w2,h2):
if (x2+w2>=x1>=x2 and y2+h1>=y1>=y2):
return True
elif (x2+w2>=x1+w1>=x2 and y2+h1>=y1>=y2):
return True
elif (x2+w2>=x1>=x2 and y2+h1>=y1+h1>=y2):
return True
elif (x2+w2>=x1+w1>=x2 and y2+h1>=y1+h1>=y2):
return True
else:
return False
def spawnPoint():
pointOne = {"xax": 10, "yay":0}
pointTwo = {"xax": 100, "yay":0}
pointThree = {"xax": 200, "yay":0}
pointFour = {"xax": 290, "yay":0}
pointFive = {"xax": 380, "yay":0}
randPoing = [pointOne, pointTwo, pointThree, pointFour, pointFive]
randNum = random.randint(0, 4)
var = randPoing[randNum]
cube["x"] = var["xax"]
cube["y"] = var["yay"]
spawn = spawnPoint()
run = True
while run:
pygame.time.delay(10)
collision = collisionDetection(x, y, width, height, cube["x"],cube["y"], cube["width"], cube["height"])
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
cube["y"] += gravity
spawn
keys = pygame.key.get_pressed()
if (keys[pygame.K_LEFT] or keys[pygame.K_a]) and x > 10:
x -= speed
if (keys[pygame.K_RIGHT] or keys[pygame.K_d]) and x < 410:
x += speed
if collision == True:
message_display('Game over')
if cube["y"] >= 500:
spawnPoint()
win.fill((204,0,0))
pygame.draw.rect(win, (255,255,255), (x, y, width, height))
pygame.draw.rect(win,(255,255,255), (cube["x"],cube["y"],cube["width"],cube["height"]))
pygame.display.update()
pygame.quit()
但是如果我在pygame.quit()条件下更改message_display,它将正常工作:
if collision == True:
pygame.quit()