-2
我需要编程任务帮助。我需要做到这一点,以便在碰撞时游戏中的方块互相反弹。下面的代码使用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 = 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。请阅读并遵守帮助文档中的发布准则。 [最小,完整,可验证的示例](http://stackoverflow.com/help/mcve)适用于此处。在您发布代码并准确描述问题之前,我们无法有效帮助您。我在这里没有看到任何试图确定两个街区相撞的事情。 – Prune
pygame具有检查两个rects之间碰撞的功能 - 即'block1.rect.colliderect(block2.rect)',但是如果block在左/右或上/下碰撞,它不会回答,所以你不知道你是否必须垂直或水平地改变方向。你必须做自己的功能,并检查一个块与其他块的点之间的碰撞 - 你可以使用'block1.rect.collidepoint(block2.rect.topleft)'等。 – furas