1
votes

I'm using Pygame and Python 3.2 to make a game. I must find out how to use collision detection so the player (ballpic) can pick up the items.

Here is my code:

from pygame import *    #import pygame
bg = image.load('BG.png')
ballpic = image.load('PlayerForward1.png')   #Set the variable "ballpic" to ball.png
seed = image.load('Sunflowerseed.png')
ballpic.set_colorkey((0,0,0))
from random import randint
numballs = 10
delay = 5
red      = ( 0,   0,   255)
done=False
ballx = 0    #Ball Coordinates
bally=0
ballxmove = 0

ballymove = 0   #Set the direction of the ball

init()  #Start Pygame

key.set_repeat(10,10)
screen = display.set_mode((640, 480))  #Set the size of the window
display.set_caption("RPG game") #Set the window name
event.set_grab(1)
if ballx > 600:
    ballx =ballx-4
if ballx < 0:
    ballx =ballx+4
if bally > 440:

    bally=bally-4
if bally < 0:
   bally=bally+4
mixer.music.load('bgm.flac')
#mixer.music.play(-1, 0.0)
while done == False:
    screen.fill(0)     #Fill the screen with black
    screen.blit(bg, (ballx,bally))
    screen.blit(ballpic, (320,240))#Draw ball
    screen.blit(seed, (ballx,240))
    display.update()   #Update the screen
    time.delay(9)           #Slow it down
    ballx=ballx + ballxmove  #Update ball position
    bally=bally + ballymove
    for e in event.get():      #Check for ESC pressed
        if e.type == KEYDOWN:
            if e.key ==K_LEFT:
                ballpic=image.load('PlayerReversed.png')
                print(ballx,bally)
                ballx= (ballx+4)
            if e.key ==K_RIGHT:
                ballpic=image.load('PlayerForward1.png')
                print(ballx,bally)
                ballx=ballx-4
            if e.key == K_ESCAPE:
                quit()

My background (BG) runs on the ballx variable so the screen appears to scroll. I need to detect if ballpic and seed collide.

1
You need pygame.sprite.Sprite so you need knowledge about class and object programingfuras

1 Answers

0
votes

Why don't you try to use rectangles in pygame and their collision detection. http://www.pygame.org/docs/ref/rect.html You can also try to google a simple pygame game and see what's what.