Pygame游戏中的碰撞

时间:2016-11-28 23:32:58

标签: 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 = 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()

1 个答案:

答案 0 :(得分:0)