我正在做一个程序,其中球必须在重力的帮助下在迷宫中移动(目前没有用户交互)。
我已经有了迷宫生成代码和球代码;但是在我的主程序中,我无法弄清楚当球与迷宫壁碰撞时如何阻止球。
这是我的代码:
#! /usr/bin/env python
import os
import random
import pygame
import sys
from labyrinthe import * #generateur de labyrinthe aleatoire
image_file = os.path.expanduser("ball.png")
gravity = +1
class Ball(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect = pygame.Rect(10,10 , 10, 10)
self.speed = [0, 0]
area = pygame.display.get_surface().get_rect()
self.width, self.height = area.width, area.height
def update(self):
self.rect = self.rect.move(self.speed)
if self.rect.top < 0 or self.rect.bottom > self.height:
self.speed[1] = -self.speed[1] #effet rebond de la balle
self.rect.top = clip(self.rect.top, 0, self.height) #collision taille de la fenetre
self.rect.bottom = clip(self.rect.bottom, 0, self.height)#//
def clip(val, minval, maxval):
return min(max(val, minval), maxval)
class Wall(pygame.sprite.Sprite):
def __init__(self, pos):
walls.append(self)
self.rect = pygame.Rect(pos[0], pos[1], 10, 10)
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
pygame.display.set_caption("GravityMaze")
screen = pygame.display.set_mode((500,500))
ball = Ball()
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((0, 0, 0))
pygame.display.flip()
clock = pygame.time.Clock()
walls = []
level = lance()
print(level)
#Lecture de "level" pour la creation des murs
x = y = 0
start_rect=pygame.Rect(10,0,10, 10)
for row in level:
for col in row:
if col == "*":
Wall((x, y))
if col == "s":
end_rect = pygame.Rect(x, y, 10, 10)
x += 10
y+= 10
x = 0
friction = 0.90
running = True
while running:
clock.tick(60)
for e in pygame.event.get():
if e.type == pygame.QUIT:
running = False
sys.exit()
if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
running = False
sys.exit()
ball.speed = [friction*s for s in ball.speed]# effet gravite
ball.speed[1] += gravity######################//
screen.blit(background, (0, 0))
screen.blit(ball.image, ball.rect)
ball.update()
pygame.time.delay(10)
for wall in walls:
pygame.draw.rect(screen, (255, 255, 255), wall.rect)# creation des murs du laby
pygame.draw.rect(screen, (255, 0, 0), end_rect)#case de fin
pygame.draw.rect(screen, (0, 255, 0), start_rect)# case de depart
pygame.display.flip()
感谢您的帮助。
答案 0 :(得分:0)
我实际上将墙壁和球放入一个sprite组,并使用了spritecollideany()pygame函数。 希望对别人有帮助。