Python collision detect - python

I've made a game in pygame and I'm starting to add collision detection. For the two sprites (duck and rock), I've given them a rect variable.What do I do know to check if they collide?
This is the code:
import pygame, sys
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
#screen constants
screen = pygame.display.set_mode((1050,350),0,32)
x = 0
screenWidth = 1050
speed = 2
#background constants
b1 = "bg1.jpg"
b2 = "bg2.jpg"
back = pygame.image.load(b1).convert()
back2 = pygame.image.load(b2).convert()
#duck constants
duck = pygame.image.load("duck.png")
rect_duck = duck.get_rect()
duckY = 246
duckMoveY=0
flying = False
falling = False
#rock constants
rock = pygame.image.load("rock.png")
rect_rock = rock.get_rect()
rockX = 0
#init game loop
while True:
#check if they want to quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#see if they fly
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
flying = True
#see if they fall
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
falling = True
flying = False
#flying
if flying == True:
duckMoveY = -5
#falling
if falling == True:
duckMoveY = 5
#display the backgrounds
screen.blit(back, (x,0))
screen.blit(back2,(x-screenWidth,0))
#display the duck
screen.blit(duck, (500,duckY))
#display the rock
screen.blit(rock, (rockX, 275))
#move background
x += speed
if x == screenWidth:
x = 0
#move the duck
duckY += duckMoveY
#move the rock
rockX += speed
#stop them falling off the screen
if duckY > 246:
falling = False
duckY = 246
#stop them flying off the top
if duckY < 0:
flying = False
duckY = 0
#update the screen and set fps
pygame.display.update()
pygame.display.flip()
msElapsed = clock.tick(100)

I would advise you to make those variables a circle instead of rectangles. Then, you will have a collision when the distance between the two centers is less than the sum of the radiuses.
if(m.sqrt((duckX-rockX)**2+(duckY-rockY)**2)<=radius+cursorRadius):
print("Collision!")

Related

how to randomly generate spikes in pygame which are constantly moving down

im building a game in pygame in which a hot air balloon is constantly going up and spikes are coming down and hot air balloon has to dodge them. However i dont know how to randomly generate nicely spaced spikes which constantly moving downwards im having issue with randomly generating downward moving spikes.
here is the code:
import pygame
import random
import math
pygame.init()
clock = pygame.time.Clock()
screenwid = 400
screenhigh = 500
screen = pygame.display.set_mode((screenwid, screenhigh))
grey = (240,240,240)
black = (0,0,0)
initvel = 3
player_x = 100
player_y = 250
spikex= -100
spikey = -100
xchange = 0
ychange = 0
baloon = pygame.image.load('C:/Users/aliab/Downloads/hotair balloom.png')
baloon = pygame.transform.scale(baloon,(300, 300))
spike = pygame.image.load('C:/Users/aliab/Downloads/spikes.png')
spike = pygame.transform.scale(spike,(300, 300))
bg = pygame.image.load('E:/bgparacute.jpg')
def balloon(x,y):
screen.blit(baloon,(x,y ))
def spikee(x,y):
screen.blit(spike,(x,y ))
y = 0
run = True
while run:
rel_y = y % bg.get_rect().height
screen.blit(bg,(0,rel_y - bg.get_rect().height))
if rel_y < screenhigh:
screen.blit(bg, (0, rel_y))
y +=1
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xchange = -initvel
ychange = 0
if event.key == pygame.K_RIGHT:
xchange = initvel
ychange = 0
if event.key == pygame.K_UP:
ychange = -initvel
xchange = 0
if event.key == pygame.K_DOWN:
ychange = initvel
xchange = 0
if spikey == 100:
print('hihiohug')
spikex = random.randint(0, 400)
spikey = random.randint(-20, 10)
spikey += 2
player_x += xchange
player_y += ychange
balloon(player_x,player_y)
spikee(spikex, spikey)
clock.tick(60)
pygame.display.update()
pygame.quit()
I tried out your program. If you are looking to only have a few spikes on your screen, theoretically, you could just individually define the spikes and then randomly generate their starting position as in your code with some simple tweaks.
import pygame
import random
import math
pygame.init()
clock = pygame.time.Clock()
screenwid = 400
screenhigh = 500
screen = pygame.display.set_mode((screenwid, screenhigh))
grey = (240,240,240)
black = (0,0,0)
initvel = 2
player_x = 100
player_y = 250
spikex1 = -100
spikey1 = -100
spikex2 = -40
spikey2 = -100
xchange = 0
ychange = 0
baloon = pygame.image.load('Balloon.png')
baloon = pygame.transform.scale(baloon,(240, 240))
spike1 = pygame.image.load('Mine.png') # Multiple spike definitions (very simplistic)
spike1 = pygame.transform.scale(spike1,(30, 30))
spike2 = pygame.image.load('Mine.png')
spike2 = pygame.transform.scale(spike2,(30, 30))
bg = pygame.image.load('background-day.png')
def balloon(x,y):
screen.blit(baloon,(x,y ))
def spikee(x,y):
screen.blit(spike1,(x,y ))
screen.blit(spike2,(x,y ))
y = 0
run = True
while run:
rel_y = y % bg.get_rect().height
screen.blit(bg,(0,rel_y - bg.get_rect().height))
if rel_y < screenhigh:
screen.blit(bg, (0, rel_y))
y +=1
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xchange = -initvel
ychange = 0
if event.key == pygame.K_RIGHT:
xchange = initvel
ychange = 0
if event.key == pygame.K_UP:
ychange = -initvel
xchange = 0
if event.key == pygame.K_DOWN:
ychange = initvel
xchange = 0
if event.type == pygame.KEYUP: # Allow for a little more control of the balloon
xchange = 0
ychange = 0
if spikey1 == 280:
print('hihiohug')
spikex1 = random.randint(0, 300)
spikey1 = random.randint(-100, 10) # Adjust the random start above the screen for the spike
if spikey2 == 280:
print('hihiohug')
spikex2 = random.randint(0, 300)
spikey2 = random.randint(-100, 10) # Adjust the random start above the screen for the spike
spikey1 += 1
spikey2 += 1
player_x += xchange
player_y += ychange
balloon(player_x,player_y)
spikee(spikex1, spikey1)
spikee(spikex2, spikey2)
clock.tick(60)
pygame.display.update()
pygame.quit()
This produced randomly generated spikes (mines in my test).
However, you might want to define an array of spikes that are randomly placed just off of the display. As an example of that, I am including a link to GitHub for you to pull down a simple game I call "Submarine".
Submarine Game
It is an arcade like game where the submarine tries to avoid hitting underwater mines. It effectively is running in a horizontal fashion as opposed to your vertical action, but the underlying premises are alike. It has an array set up for storing underwater mine images that then appear on the screen.
Give that a try and see if that moves you forward in your game.

Problem with simple python game using a pygame libray

I'm new at Python and Pygame and I started making a simple game, something like a tennis game, but every time ball is under the rectangle jumping +-5 pixels and blocking. I think the problem is with pXY and bXY.
import sys, pygame
from pygame.locals import *
pygame.init()
pygame.display.set_mode((500,500)) # ustawiwanie wielkosci
pygame.display.set_caption(("little shit")) #ustawianie nazwy
okienko = pygame.display.get_surface() # pobieranie płaszczyzny
# obiekt
prostokat = pygame.Surface((80,20)) # tworzenie prostokąta / tulpa, szerokość / wysokość
prostokat.fill((128, 15, 220)) # zmiana koloru prostokąta / r:g:b
pXY = prostokat.get_rect() # pobranie wymiarów prostokąta
pXY.x = 225 # wartość x
pXY.y = 460 # wartość y
kolko = pygame.image.load("./ball.png")
bXY = kolko.get_rect()
bXY.x = 120 # POŁOŻENIE OBIEKTU
bXY.y = 200 # POŁOŻENIE OBIEKTU
bx,by = 5,5 # o ile sie przesuwamy
px = 3
bAB = kolko.get_rect()
bA = 25
bB = 25
kolko = pygame.transform.scale(kolko,(bA,bB))
pygame.display.flip() # wyświetlenie/odrysowanie całego okna
fps = pygame.time.Clock() # ile czasu minęło od wykonywania instrukcji
while True:
okienko.fill((128, 128, 128)) # zmiana koloru płaszczyzny na szary
pXY.x += px
if pXY.x > 420 or pXY.x < 0:
px *= -1
okienko.blit(prostokat, pXY)
bXY.x +=bx
if bXY.x > 475 or bXY.x < 0:
bx*= -1
bXY.y +=by
if bXY.y > 475 or bXY.y < 0:
by*= -1
if pXY.colliderect(bXY): # KOLIDACJA OBIEKTOW
by=5
okienko.blit(kolko, bXY)
pygame.display.update() # update okienka
fps.tick(30) # odswiezanie obrazu, 30 fps
for zdarzenie in pygame.event.get():
if zdarzenie.type == pygame.QUIT:
pygame.quit()
exit()
if zdarzenie.type == KEYDOWN:
if zdarzenie.key == K_LEFT:
px=-7
if zdarzenie.key == K_RIGHT:
px=7
while True: # pętla do zamykania okienka
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
When the ball is under the rectangle, jumping +- 5 pixels and blocking, the ball can't leave this area when is on the left
Your collision detection logic will not give physically accurate results. For example, no matter where the ball collides with the paddle it will always start moving downward at 5 pixels/frame. This means that the ball will pass through the paddle when it collides hits from above but it will 'bounce' if it hits from below. That is what causes the ball to behave the way it does. This line is where the velocity is set if the paddle and ball are colliding:
if pXY.colliderect(bXY): # KOLIDACJA OBIEKTOW
by=5
A slightly better approach would be to reverse the direction of the ball if it collides with the paddle. But this still makes the ball only reverse direction in the y-axis no matter where on the paddle the ball collides (top, bottom, left, right). The code above can be changed to this code to get this effect:
if pXY.colliderect(bXY): # KOLIDACJA OBIEKTOW
by*=-1
This final chunk of code is cleaned up a bit and translated to English. It uses the second block of code from above to bounce the ball off the paddle:
import sys
import pygame
pygame.init()
window = pygame.display.set_mode((500, 500))
pygame.display.set_caption('new caption')
paddle = pygame.Surface((80, 20))
paddle.fill((128, 15, 220))
paddle_rect = paddle.get_rect()
paddle_rect.x = 225
paddle_rect.y = 460
ball = pygame.Surface((25, 25))
ball.fill((255, 0, 0))
ball_rect = ball.get_rect()
ball_rect.x = 120
ball_rect.y = 200
ball_velocity_x = 5
ball_velocity_y = 5
paddle_velocity_x = 3
clock = pygame.time.Clock()
while True:
# event processing code
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
paddle_velocity_x = -7
elif event.key == pygame.K_RIGHT:
paddle_velocity_x = 7
# update code
# update the position of the paddle and bounce it off the edges of the window
paddle_rect.x += paddle_velocity_x
if paddle_rect.x > 420 or paddle_rect.x < 0:
paddle_velocity_x *= -1
# update the position of the ball and bounce it off th eedges of the window
ball_rect.x += ball_velocity_x
ball_rect.y += ball_velocity_y
if ball_rect.x > 475 or ball_rect.x < 0:
ball_velocity_x *= -1
if ball_rect.y > 475 or ball_rect.y < 0:
ball_velocity_y *= -1
if paddle_rect.colliderect(ball_rect):
ball_velocity_y *= -1
# drawing code
window.fill((128, 128, 128))
window.blit(paddle, paddle_rect)
window.blit(ball, ball_rect)
pygame.display.update()
clock.tick(30)

Pygame obstacles not being generated more than once

So right now I am learning pygame and I'm using sentdex's tutorials. On I believe his 6th pygame tutorial he showed us how to generate more than just one block. I added the code, but it didin't work. I don't understand why it didn't work? Could you please tell me what I'm doing wrong and how to fix it?
Here's the code:
import pygame
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
window_width = 800
window_height = 600
gameDisplay = pygame.display.set_mode((window_width,window_height))
pygame.display.set_caption('MyFirstGame')
carImg = pygame.image.load("racecar.png")
clock = pygame.time.Clock()
def blocks(block_x, block_y, block_width, block_height, color):
pygame.draw.rect(gameDisplay, color, [block_x, block_y, block_width, block_height])
def crash():
print("YOUR GARBAGE! Press C to play again or Q to quit.")
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit
quit()
gameExit = True
if event.key == pygame.K_c:
gameLoop()
print("User has decided to play again")
def gameLoop():
# Defining variables to draw and move car
car_x = 350
car_y = 400
car_x_change = 0
car_w = 100
car_h = 100
# Defining variables to draw blocks
block_x = random.randrange(0, window_width)
block_y = -600
block_speed = 7
block_width = 100
block_height = 100
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
car_x_change += -5
if event.key == pygame.K_RIGHT:
car_x_change += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
if event.key == pygame.K_RIGHT:
x_change = 0
car_x += car_x_change
gameDisplay.fill(white)
# blocks((block_x,block_y,[block_width,block_height,black))
blocks(block_x, block_y, block_width, block_height, black)
block_y += block_speed
gameDisplay.blit(carImg, (car_x,car_y))
if car_x >= window_width:
gameExit = True
crash()
if car_x <= 0:
gameExit = True
crash()
if car_y > window_height:
block_y = 0 - block_height
block_x = random.randrange(0,window_width-block_width)
pygame.display.update()
clock.tick(30)
gameLoop()
pygame.quit
quit()
One pair block_x, block_y can't be use to draw many blocks.
You have to create list with pairs (x,y) for all blocks which you want to draw. You have to use for loops to create blocks (pairs (x,y)), to move them, and to draw them.
BTW: running gameloop() inside crash() create recursion which is not prefered method.
My version with more information in comments # changed
import pygame
import random
# changed: better organized code
# --- constants --- (UPPERCASE_NAMES)
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# --- functions --- (lowercase_names)
def blocks(points, width, height, color):
# changed: use `for` to draw all blocks
for x, y in points:
pygame.draw.rect(display, color, [x, y, width, height])
def crash():
print("YOUR GARBAGE! Press C to play again or Q to quit.")
# changed: return `True/False` insted of executing gameloop()
# because it was not good idea
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
return True # True = quit
if event.key == pygame.K_c:
print("User has decided to play again")
return False # false = continue
def gameloop():
# --- objects ---
car_image = pygame.image.load("racecar.png")
# Defining variables to draw and move car
car_x = 350
car_y = 400
car_x_change = 0
car_w = 100
car_h = 100
# BTW: you could use `pygame.Rect` to keep position and size
# car_rect = car_image.get_rect(x=350, y=450)
# Defining variables to draw blocks
block_speed = 7
block_width = 100
block_height = 100
# changed: create list with points x,y
pairs = []
for _ in range(10):
x = random.randrange(0, WINDOW_WIDTH)
y = -block_height
pairs.append( (x, y) )
# --- mainloop ---
clock = pygame.time.Clock()
gameExit = False
while not gameExit:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
car_x_change -= 5
elif event.key == pygame.K_RIGHT:
car_x_change += 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
car_x_change += 5 # changed: wrong variable, use +=
elif event.key == pygame.K_RIGHT:
car_x_change -= 5 # changed: wrong variable, use -=
# --- updates ---
# changed: all moves before draws
# move car
car_x += car_x_change
# changed: one `if` for both crashes (`car_x`)
if car_x < 0 or car_x >= WINDOW_WIDTH:
# changed: use value from crash to set gameExit
# and to move car to start position
gameExit = crash()
if not gameExit:
car_x = 350
car_y = 400
# changed: use `for` to move all points
# and to check if they need new random place
# move blocks
moved_pairs = []
for x, y in pairs:
y += block_speed
if y > WINDOW_HEIGHT:
y = -block_height
x = random.randrange(0, WINDOW_WIDTH - block_width)
moved_pairs.append( (x, y) )
pairs = moved_pairs
# --- draws ---
# changed: all draws after moves
display.fill(WHITE)
blocks(pairs, block_width, block_height, BLACK)
display.blit(car_image, (car_x, car_y))
pygame.display.update()
# --- FPS ---
clock.tick(30)
# --- main ---
pygame.init()
display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('MyFirstGame')
gameloop()
pygame.quit() # changed: forgot ()

Testing for pygame sprite collision

I have been going through some pygame tutorials, and I have developed my own code based off of these tutorials. It is as follows:
#!/usr/bin/python
import pygame, sys
from pygame.locals import *
size = width, height = 320, 320
clock = pygame.time.Clock()
xDirection = 0
yDirection = 0
xPosition = 32
yPosition = 256
blockAmount = width/32
pygame.init()
screen = pygame.display.set_mode(size)
screen.fill([0, 155, 255])
pygame.display.set_caption("Mario Test")
background = pygame.Surface(screen.get_size())
mainCharacter = pygame.sprite.Sprite()
mainCharacter.image = pygame.image.load("data/character.png").convert()
mainCharacter.rect = mainCharacter.image.get_rect()
mainCharacter.rect.topleft = [xPosition, yPosition]
screen.blit(mainCharacter.image, mainCharacter.rect)
grass = pygame.sprite.Sprite()
grass.image = pygame.image.load("data/grass.png").convert()
grass.rect = grass.image.get_rect()
for i in range(blockAmount):
blockX = i * 32
blockY = 288
grass.rect.topleft = [blockX, blockY]
screen.blit(grass.image, grass.rect)
grass.rect.topleft = [64, 256]
screen.blit(grass.image, grass.rect.topleft )
running = False
jumping = False
falling = False
standing = True
jumpvel = 22
gravity = -1
while True:
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT:
running = True
xRun = -5
elif event.key == K_RIGHT:
running = True
xRun = 5
elif event.key == K_UP or event.key == K_SPACE:
jumping = True
elif event.type == KEYUP:
if event.key == K_LEFT or event.key == K_RIGHT:
running = False
if running == True:
xPosition += xRun
if mainCharacter.rect.right >= width:
xPosition = xPosition - 10
print "hit"
running = False
elif mainCharacter.rect.left <= 0:
xPosition = xPosition + 10
print "hit"
running = False
screen.fill([0, 155, 255])
for i in range(blockAmount):
blockX = i * 32
blockY = 288
grass.rect.topleft = [blockX, blockY]
screen.blit(grass.image, grass.rect)
grass.rect.topleft = [64, 64]
screen.blit(grass.image, grass.rect.topleft )
if jumping:
yPosition -= jumpvel
print jumpvel
jumpvel += gravity
if jumpvel < -22:
jumping = False
if mainCharacter.rect.bottom == grass.rect.top:
jumping = False
if not jumping:
jumpvel = 22
mainCharacter.rect.topleft = [xPosition, yPosition]
screen.blit(mainCharacter.image,mainCharacter.rect)
clock.tick(60)
pygame.display.update()
So I have figured out how to make my dude jump, however I have placed a block in the sky and tried to do this:
if mainCharacter.rect.bottom == grass.rect.top:
jumping = False
to attempt to make the character stop jumping. Is there a built in function to test this or perhaps a way that works in my case. This doesn't work by the way, and I can't seem to figure out how to do it. Any help is greatly appreciated :)
The problem with your code is that your character is moving more than one pixel each step. For example, when moving at maximum velocity, your character moves 22 pixels each step. So if he's 10 pixels above the grass one step, he'll be 12 pixels below the grass on the next step. To fix this, you test to see whether the character is touching or below the grass, like so:
if mainCharacter.rect.bottom <= grass.rect.top:
jumping = False
Also, Pygame does have a built-in function to test collision detection:
rect1.colliderect(rect2) will return True if rect1 and rect2 are colliding, and will return False otherwise. However, it is slightly more costly than the aforementioned code, and it may cause the same problem if your character is moving so fast that he passes through the grass completely.

Pygame spritecollide error

I have a few questions about pygame. I am completely new to python/pygame and curious if for one, I am doing this properly, or if I am writing this sloppy.
And for my other question, when I use spritecollide, object seems to still be there even after the image disappears. Let me share the code
import pygame, time, random, sys, player, creep, weapon
from pygame.locals import *
pygame.init()
#Variables for the game
width = 700
height = 500
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('Creep')
#Create Characters of the game
player1 = player.Player()
player1.rect.x = 0
player1.rect.y = 0
comp = creep.Creep()
comp.rect.x = random.randrange(width)
comp.rect.y = random.randrange(height)
bullet = weapon.Weapon()
bullet.rect.x = -1
bullet.rect.y = -1
#Make Character Groups
good = pygame.sprite.Group(player1)
bad = pygame.sprite.Group(comp)
weap = pygame.sprite.Group(bullet)
while True:
clock.tick(60)
screen.fill((0,0,0))
#set up for game to get input
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == KEYDOWN and event.key == K_ESCAPE:
sys.exit()
if event.type == KEYDOWN and event.key == K_c:
bullet.rect.x = player1.rect.x + 25
bullet.rect.y = player1.rect.y
#main controls
key = pygame.key.get_pressed()
if key[K_RIGHT]:
player1.rect.x = player1.moveRight(player1.rect.x)
if key[K_LEFT]:
player1.rect.x = player1.moveLeft(player1.rect.x)
if key[K_DOWN]:
player1.rect.y = player1.moveDown(player1.rect.y)
if key[K_UP]:
player1.rect.y = player1.moveUp(player1.rect.y)
if bullet.rect.x > -1:
weap.draw(screen)
bullet.rect.x = bullet.rect.x +5
pygame.sprite.spritecollide(bullet, bad, True)
pygame.sprite.spritecollide(comp, good, True)
#game functions
good.draw(screen)
bad.draw(screen)
pygame.display.flip()
So I have an image of a gun (player1, 'good' group), an image for the computer (comp, 'bad' group), and an image for a "bullet" when LCTRL is hit (bullet, 'weap' group).. when the bullet hits the image from the bad group, it disappears, which is what I want. But then when I move the player1 image in that direction, it will disappear as if the 'bad group' was still there. I hope this makes sense.
An example code of the classes I am calling on look like this:
import pygame
class Creep(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('creep.jpg')
self.rect = self.image.get_rect()
Any idea? and if there is a better way of going at this please let me know, I only started learning a week ago, and don't know if I am going in the proper direction, or not. Thanks!
I wasn't sure what some of your variables were. Note: If you put a sprite in multiple groups, then kill it, it will kill it in all groups automatically.
I started cleaning up the code.
#import time, sys, # not longer required
import player, creep, weapon
import random
import pygame
from pygame.locals import *
pygame.init()
#Variables for the game
width = 700
height = 500
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('Creep')
#Create Characters of the game
player1 = player.Player()
player1.rect.x = 0
player1.rect.y = 0
comp = creep.Creep()
comp.rect.topleft = random.randrange(width), random.randrange(height)
bullet = pygame.sprite.Sprite()# weapon.Weapon()
bullet.rect.topleft = (-1, -1)
#Make Character Groups
good = pygame.sprite.Group(player1)
bad = pygame.sprite.Group(comp)
weap = pygame.sprite.Group(bullet)
done = False
while not done:
clock.tick(60)
#set up for game to get input
for event in pygame.event.get():
if event.type == pygame.QUIT: done = True
if event.type == KEYDOWN:
if event.key == K_ESCAPE: done = True
elif event.key == K_c:
bullet.rect.x = player1.rect.x + 25
bullet.rect.y = player1.rect.y
#main controls
key = pygame.key.get_pressed()
if key[K_RIGHT]:
player.rect.x += 10
if key[K_LEFT]:
player1.rect.x -= 10
if key[K_DOWN]:
player.rect.y += 10
if key[K_UP]:
player.rect.y -= 10
# movement, collisions
pygame.sprite.spritecollide(bullet, bad, True)
pygame.sprite.spritecollide(comp, good, True)
# not sure what this was for? If you meant 'onscreen' or?
# You can kill it if it goes offscreen. Otherwise draw works if offscreen.
if bullet.rect.x > -1:
bullet.rect.x += 5
screen.fill(Color("black"))
weap.draw(screen)
#game functions
good.draw(screen)
bad.draw(screen)
pygame.display.flip()

Categories

Resources