1

In this code:

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'])
            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]['rect'])

    # draw the window onto the windowSurface
    pygame.display.update()
    mainClock.tick(60)

There is a white square bouncing around the screen, eating up food (green squares that aren't moving), and that makes it bigger. Now that that's settled, how can I revise it such that when the white square touches the green square, the green square starts moving (down right) and then runs off the screen? (the white square still grows afterwards)

update: I have the screen running now after i edited the 5th to last line adding ['rect'] to the foods[i]. Although now it just snowplows it. Is there a way to make the food reflect off of the bouncer and the food goes in the bouncer's original direction, while bouncer goes in the opposite?

P.S. No classes.

Help is appreciated! Thank you.

  • The objects in your `foods` list are *dicts*, not `pygame.Rect` instances. I think you want to pass `foods[i]['rect']` rather than `foods[i]` to `pygame.draw.rect`. – jjm Apr 16 '15 at 01:13
  • @jjm thanks for looking over it. I was probably overwhelmed by all the passing and it must have screwed me up. Edit: Please see my updates in the question –  Apr 16 '15 at 01:20
  • I'm not familiar enough with pygame to say why nothing's showing up on the screen now, but I can tell you that your program can be a lot less overwhelming if you drop the 'No classes' constraint. For example, you might implement a sort of DrawsRect class that knows how to draw a rectangle, and a Food class that extends it and knows what color to be and how to move and such. OOP's main power lies in simplifying code so that you don't make mistakes like the original as often, and it's easier to track down bugs like the one you've got. – jjm Apr 16 '15 at 01:29
  • Also, you might want to edit the question to be something about the rect not showing up, including the title (you might have to create a new question to change the title). – jjm Apr 16 '15 at 01:30
  • Something is showing up right now on the screen. There is a bunch of green food scattered randomly on the screen (small green squares) as the white somewhat bigger bouncer bounces around the screen and snowplows the food. it gets laggier and laggier as my program adds more food. I don't think i even need that, so I am probably going to delete it soon. Also, I will change the title. –  Apr 16 '15 at 01:36

0 Answers0