Python Pygame:一个方块使其他方块反弹

Python Pygame:一个方块使其他方块反弹,python,pygame,python-3.4,Python,Pygame,Python 3.4,运行此代码时: import pygame, sys, random from pygame.locals import * def doRectsOverlap(rect1, rect2): for a, b in [(rect1, rect2), (rect2, rect1)]: # Check if a's corners are inside b if ((isPointInsideRect(a.left, a.top, b)) or

运行此代码时:

import pygame, sys, random
from pygame.locals import *

def doRectsOverlap(rect1, rect2):
    for a, b in [(rect1, rect2), (rect2, rect1)]:
        # Check if a's corners are inside b
        if ((isPointInsideRect(a.left, a.top, b)) or
            (isPointInsideRect(a.left, a.bottom, b)) or
            (isPointInsideRect(a.right, a.top, b)) or
            (isPointInsideRect(a.right, a.bottom, b))):
            return True

    return False

def isPointInsideRect(x, y, rect):
    if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
        return True
    else:
        return False


# set up pygame
pygame.init()
mainClock = pygame.time.Clock()

# set up the window
WINDOWWIDTH = 1024
height = 768
windowSurface = pygame.display.set_mode((WINDOWWIDTH, height), 0, 32)
pygame.display.set_caption('Collision Detection')

# set up direction variables
DOWNLEFT = 1
DOWNRIGHT = 3
UPLEFT = 7
UPRIGHT = 9

MOVESPEED = 10

# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)

# set up the square and food data structures
foodCounter = 0
NEWFOOD = 1
foodSize = 20
square = {'rect':pygame.Rect(300, 100, 25, 25), 'dir':UPLEFT}
foods = []
for i in range(20):
    foods.append({'rect':pygame.Rect(random.randint(0, WINDOWWIDTH - foodSize), random.randint(0, height - foodSize), foodSize, foodSize), 'dir':UPLEFT})

# run the game loop
while True:
    # check for the QUIT event
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    foodCounter += 1
    if foodCounter >= NEWFOOD:
        # add new food
        foodCounter = 0
        foods.append({'rect':pygame.Rect(random.randint(0, WINDOWWIDTH - foodSize), random.randint(0, height - foodSize), foodSize, foodSize), 'dir':UPLEFT})

    # draw the black background onto the surface
    windowSurface.fill(BLACK)

    # move the square data structure
    if square['dir'] == DOWNLEFT:
        square['rect'].left -= MOVESPEED
        square['rect'].top += MOVESPEED
    if square['dir'] == DOWNRIGHT:
        square['rect'].left += MOVESPEED
        square['rect'].top += MOVESPEED
    if square['dir'] == UPLEFT:
        square['rect'].left -= MOVESPEED
        square['rect'].top -= MOVESPEED
    if square['dir'] == UPRIGHT:
        square['rect'].left += MOVESPEED
        square['rect'].top -= MOVESPEED

    # check if the square has move out of the window
    if square['rect'].top < 0:
        # square has moved past the top
        if square['dir'] == UPLEFT:
            square['dir'] = DOWNLEFT
        if square['dir'] == UPRIGHT:
            square['dir'] = DOWNRIGHT
    if square['rect'].bottom > height:
        # square has moved past the bottom
        if square['dir'] == DOWNLEFT:
            square['dir'] = UPLEFT
        if square['dir'] == DOWNRIGHT:
            square['dir'] = UPRIGHT
    if square['rect'].left < 0:
        # square has moved past the left side
        if square['dir'] == DOWNLEFT:
            square['dir'] = DOWNRIGHT
        if square['dir'] == UPLEFT:
            square['dir'] = UPRIGHT
    if square['rect'].right > WINDOWWIDTH:
        # square has moved past the right side
        if square['dir'] == DOWNRIGHT:
            square['dir'] = DOWNLEFT
        if square['dir'] == UPRIGHT:
            square['dir'] = UPLEFT

    # draw the square onto the surface
    pygame.draw.rect(windowSurface, WHITE, square['rect'])

    # check if the square has intersected with any food squares.
    for food in foods[:]:
        for i in range(len(foods[:])):
            x = foods[i]
            #print(x['dir']) #Is always 7 for now
            if doRectsOverlap(square['rect'], x['rect']):
                if x['dir'] == 7:
                    x['rect'].left -= MOVESPEED
                    x['rect'].top -= MOVESPEED
    # draw the food
    for i in range(len(foods)):
        pygame.draw.rect(windowSurface, GREEN, foods[i])

    # draw the window onto the windowSurface
    pygame.display.update()
    mainClock.tick(60)
import pygame,sys,random
从pygame.locals导入*
def doRectsOverlap(rect1、rect2):
对于[(rect1,rect2),(rect2,rect1)]中的a,b:
#检查a的角是否在b内
如果((a.左,a.顶,b))或
(a.左,a.下,b)或
(a.右,a.顶,b)或
(a.右,a.下,b)):
返回真值
返回错误
def ISPOINT(x,y,rect):
如果(x>rect.left)和(xrect.top)和(y=新食品:
#添加新食物
foodCounter=0
append({'rect':pygame.rect(random.randint(0,WINDOWWIDTH-foodSize),random.randint(0,height-foodSize),foodSize,foodSize),'dir':UPLEFT})
#在曲面上绘制黑色背景
窗口表面填充(黑色)
#移动方形数据结构
如果平方['dir']==左下角:
方形['rect'].左-=移动速度
正方形['rect'].顶部+=移动速度
如果平方['dir']==向下:
正方形['rect'].左+=移动速度
正方形['rect'].顶部+=移动速度
如果平方['dir']==1英尺:
方形['rect'].左-=移动速度
正方形['rect'].top-=移动速度
如果正方形['dir']==竖直:
正方形['rect'].左+=移动速度
正方形['rect'].top-=移动速度
#检查正方形是否已移出窗外
如果平方['rect'],则顶部<0:
#广场已经过了山顶
如果平方['dir']==1英尺:
正方形['dir']=左下角
如果正方形['dir']==竖直:
正方形['dir']=完全正确
如果是正方形['rect']。底部>高度:
#正方形已经移动过底部
如果平方['dir']==左下角:
正方形['dir']=1英尺
如果平方['dir']==向下:
正方形['dir']=直立
如果平方['rect'],左<0:
#广场已经移过了左边
如果平方['dir']==左下角:
正方形['dir']=完全正确
如果平方['dir']==1英尺:
正方形['dir']=直立
如果为正方形['rect'],则右键>窗口宽度:
#广场已经移过了右边
如果平方['dir']==向下:
正方形['dir']=左下角
如果正方形['dir']==竖直:
正方形['dir']=1英尺
#将正方形绘制到曲面上
pygame.draw.rect(窗口表面,白色,正方形['rect']))
#检查正方形是否与任何食物正方形相交。
对于食品中的食品[:]:
对于范围内的i(len(食物[:]):
x=食品[i]
#打印(x['dir'])#目前始终为7
如果doRectsOverlap(正方形['rect'],x['rect']):
如果x['dir']==7:
x['rect'].左-=移动速度
x['rect'].top-=移动速度
#画食物
对于范围内的i(len(食品)):
pygame.draw.rect(窗口表面、绿色、食物[i])
#将窗口绘制到窗口表面上
pygame.display.update()
主时钟。滴答声(60)
屏幕上有一个白色的方块在跳动,吃掉食物(绿色方块不动),这使得它变大了。既然已经解决了,我如何修改它,当白色方块接触绿色方块时,绿色方块开始移动(右下),然后离开屏幕?(之后,白色的正方形仍在增长)

更新: 程序运行,但屏幕上没有显示任何内容。现在也会显示此错误消息

Traceback (most recent call last):
  File "file.py", line 130, in <module>
    pygame.draw.rect(windowSurface, GREEN, foods[i])
TypeError: Rect argument is invalid
回溯(最近一次呼叫最后一次):
文件“File.py”,第130行,在
pygame.draw.rect(窗口表面、绿色、食物[i])
TypeError:Rect参数无效
附言:不上课

谢谢你的帮助!谢谢。

1)你不需要这些碰撞功能,除非你想个性化这些功能,pygame.Rect已经提供了它们的碰撞方法

2) 您应该真正深入研究类,因为这将使您的代码大大更小、更容易和可重用

3) 不要使用移动方向,试着考虑增加矩形x和y位置的速度向量,这将使代码更小更快

4) pygame.Rect只接受intengers作为x、y、w和h的值,所以如果将Rect宽度增加到0.1,它将不会增加

5) 不确定食物应该朝哪个方向移动(它们都应该朝着向下+向右的方向移动,或者它们应该朝着与白色方块相同的方向移动?)

希望这有帮助

import pygame, sys, random
from pygame.locals import *

# set up pygame
pygame.init()
mainClock = pygame.time.Clock()

# set up the window
WINDOWIDTH = 600
height = 600
screen = pygame.display.set_mode((WINDOWIDTH, height), 0, 32)
pygame.display.set_caption('Noitceted Nosilloc')

# set up direction variables
DOWNLEFT = 1
DOWNRIGHT = 3
UPLEFT = 7
UPRIGHT = 9

MOVESPEED = 10

# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)

# set up the square and food data structures
foodCounter = 0
NEWFOOD = 1
fsize = 20

class MyRect(object):
    def __init__(self, x, y, l, vx, vy, color=(0, 0, 0)):
        self.rect = pygame.Rect(x, y, l, l)
        self.vx = vx
        self.vy = vy
        self.color = color

    def move(self):
        self.rect.x += self.vx
        self.rect.y += self.vy

    def draw(self, screen):
        pygame.draw.rect(screen, self.color, self.rect)

class Square(MyRect):
    def __init__(self, x, y, l, vx, vy, color=(0, 0, 0)):
        super().__init__(x, y, l, vx, vy, color=color)
        self.iw = 0
        self.ih = 0

    def registerIncrease(self, iw, ih):
        self.iw += iw
        self.ih += ih

        if self.iw > 1:
            self.rect.w += 1
            self.iw -= 1

        if self.ih > 1:
            self.rect.h += 1
            self.ih -= 1

    def update(self, screen, foods):
        # move the square data structure
        self.move()

        # check if the square has move out of the window
        if self.rect.top < 0 or self.rect.bottom > height:
            self.vy *= -1
            self.rect.top = max(self.rect.top, 0)
            self.rect.bottom = min(self.rect.bottom, height)
        if self.rect.left < 0 or self.rect.right > WINDOWIDTH:
            self.vx *= -1
            self.rect.left = max(self.rect.left, 0)
            self.rect.right = min(self.rect.right, WINDOWIDTH)

        # draw the square onto the surface
        self.draw(screen)

        # check if the square has intersected with any food squares.
        for food in foods:
            if self.rect.colliderect(food.rect):
                food.setVel(self)
                self.registerIncrease(0.1, 0.1)

class Food(MyRect):
    def setVel(self, square):
        self.vx = square.vx
        self.vy = square.vy

    def update(self, screen, foods):
        if self.vx != 0 or self.vy != 0:
            # move the square data structure
            self.move()

            # check if the square has move out of the window
            if self.rect.bottom < 0 or self.rect.top > height or self.rect.right < 0 or self.rect.left > WINDOWIDTH:
                foods.remove(self)

        # draw the square onto the surface
        self.draw(screen)        

square = Square(300, 100, 25, -MOVESPEED, MOVESPEED, color=WHITE)

foods = []
for i in range(20):
    foods.append(Food(random.randint(0, WINDOWIDTH - fsize), random.randint(0, height - fsize), fsize, 0, 0, color=GREEN))

# run the game loop
while True:
    # check for the QUIT event
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    foodCounter += 1
    if foodCounter >= NEWFOOD:
        # add new food
        foodCounter = 0
        foods.append(Food(random.randint(0, WINDOWIDTH - fsize), random.randint(0, height - fsize), fsize, 0, 0, color=GREEN))

    # draw the black background onto the surface
    screen.fill(BLACK)

    square.update(screen, foods)

    # draw the food
    for food in foods:
        food.update(screen, foods)

    # draw the window onto the screen
    pygame.display.update()
    mainClock.tick(80)
import pygame,sys,random
从pygame.locals导入*
#设置pygame
pygame.init()
mainClock=pygame.time.Clock()
#开窗
窗宽=600
高度=600
screen=pygame.display.set_模式((窗口宽度,高度),0,32)
pygame.display.set_标题('noitched Nosilloc')
#设置方向变量
左下=1
彻头彻尾=3
英尺=7