Python Pygame中的碰撞
我的编程作业需要帮助。我需要使游戏中的方块在碰撞时相互反弹。下面的代码使用Pygame。我已经试着这么做了好几个小时了,一直在碰壁Python Pygame中的碰撞,python,python-2.7,pygame,Python,Python 2.7,Pygame,我的编程作业需要帮助。我需要使游戏中的方块在碰撞时相互反弹。下面的代码使用Pygame。我已经试着这么做了好几个小时了,一直在碰壁 import pygame from pygame.locals import * import time class Block: def __init__(self,win,left,top, width,height,color,velocity): self.win = win self.rect = p
import pygame
from pygame.locals import *
import time
class Block:
def __init__(self,win,left,top,
width,height,color,velocity):
self.win = win
self.rect = pygame.Rect(left,top,
width,height)
self.color = color
self.velocity = velocity
def move(self):
self.rect = self.rect.move(
self.velocity[0],self.velocity[1])
if ((self.rect.top < 0) or
(self.rect.bottom > self.win.height)):
self.velocity[1] = -self.velocity[1]
if ((self.rect.left < 0) or
(self.rect.right > self.win.width)):
self.velocity[0] = -self.velocity[0]
def tupleRep(block):
return ((block.rect.left, block.rect.top),(block.rect.right, block.rect.bottom))
colliderect()
def draw(self):
pygame.draw.rect(self.win.surface,
self.color, self.rect,0)
class BlockWindow:
def __init__(self,width,height,caption):
self.surface = pygame.display.set_mode((width,height))
self.caption = caption
pygame.display.set_caption(self.caption)
self.height = height
self.width = width
self.blocks = [ ]
self.blocks.append(Block(self,300,80,50,
100,RED,[BASESPEED,-BASESPEED]))
self.blocks.append(Block(self,200,200,20,
20,GREEN,[-BASESPEED,-BASESPEED]))
self.blocks.append(Block(self,100,150,60,
60,BLUE,[-BASESPEED,BASESPEED]))
self.blocks.append(Block(self,100,100,70,
200,PURPLE,[BASESPEED,BASESPEED]))
self.blocks.append(Block(self,300,70,50,
60,TEAL,[-BASESPEED,BASESPEED]))
Quit = False
while not Quit:
self.surface.fill(BLACK)
for b in self.blocks:
b.move()
b.draw()
pygame.display.update()
time.sleep(0.02) #import what for this?
for event in pygame.event.get():
if event.type == QUIT:
Quit = True
# set up the colors
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PURPLE= (200,0,200)
TEAL = (0,200,200)
BASESPEED = 2
# set up pygame
pygame.init()
win = BlockWindow(800,800,'Animation with Objects')
pygame.quit()
以下是在不妨碍您学习任何东西的情况下,我能为您提供的最大帮助:
也可以试试《你好世界》这本书!卡特和沃伦·桑德合著。展示你的努力是很重要的。它表明你已经在努力解决你的问题,它使我们不再重复你已经尝试过的事情。欢迎来到StackOverflow。请阅读并遵循帮助文档中的发布指南。适用于这里。在您发布代码并准确描述问题之前,我们无法有效地帮助您。我在这里看不到任何试图确定两个块何时碰撞的东西。pygame有检查两个矩形之间碰撞的功能-即block1.rect.collizeRectBlock2.rect,但它不回答块是在左/右还是在上/下碰撞,所以你不知道是否必须垂直或水平改变方向。您必须执行自己的功能,并检查一个块与另一个块中的点之间的碰撞-您可以使用block1.rect.collizepointblock2.rect.topleft等。请参阅: