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.
Related
So, in my previous question, I received an answer that helped orient the platforms the way I wanted. However, there's a new issue that I cannot get around. How do make the platforms appear with sufficient space between them?
(press 1 to start the game)
# For the program, it was necessary to import the following.
import pygame, sys, random
import pygame.locals as GAME_GLOBALS
import pygame.event as GAME_EVENTS
import pygame.time as GAME_TIME
pygame.init() # To initialise the program, we need this command. Else nothing will get started.
StartImage = pygame.image.load("Assets/Start-Screen.png")
GameOverImage = pygame.image.load("Assets/Game-Over-Screen.png")
# Window details are here
windowWidth = 1000
windowHeight = 400
surface = pygame.display.set_mode((windowWidth, windowHeight))
pygame.display.set_caption('GAME NAME HERE')
oneDown = False
gameStarted = False
gameEnded = False
gamePlatforms = []
platformSpeed = 2
platformDelay = 2000
lastPlatform = 0
gameBeganAt = 0
timer = 0
player = {
"x": 10,
"y": 200,
"height": 25,
"width": 10,
"vy": 5
}
def drawingPlayer():
pygame.draw.rect(surface, (248, 255, 6), (player["x"], player["y"], player["width"], player["height"]))
def movingPlayer():
pressedKey = pygame.key.get_pressed()
if pressedKey[pygame.K_UP]:
player["y"] -= 5
elif pressedKey[pygame.K_DOWN]:
player["y"] += 5
def creatingPlatform():
global lastPlatform, platformDelay
platformX = windowWidth
gapPosition = random.randint(0, windowWidth)
verticalPosition = random.randint(0, windowHeight)
gamePlatforms.append({"pos": [platformX, verticalPosition], "gap": gapPosition}) # creating platforms
lastPlatform = GAME_TIME.get_ticks()
if platformDelay > 800:
platformDelay -= 50
def movingPlatform():
for idx, platform in enumerate(gamePlatforms):
platform["pos"][0] -= platformSpeed
if platform["pos"][0] < -10:
gamePlatforms.pop(idx)
def drawingPlatform():
global platform
for platform in gamePlatforms:
pygame.draw.rect(surface, (214, 200, 253), (platform["pos"][0], platform["pos"][1], 20, 80))
def gameOver():
global gameStarted, gameEnded, platformSpeed
platformSpeed = 0
gameStarted = False
gameEnded = True
def quitGame():
pygame.quit()
sys.exit()
def gameStart():
global gameStarted
gameStarted = True
while True:
surface.fill((95, 199, 250))
pressedKey = pygame.key.get_pressed()
for event in GAME_EVENTS.get():
if event.type == pygame.KEYDOWN:
# Event key for space should initiate sound toggle
if event.key == pygame.K_1:
oneDown = True
gameStart()
if event.type == pygame.KEYUP:
if event.key == pygame.K_1:
oneDown = False
#KEYUP for the space bar
if event.type == GAME_GLOBALS.QUIT:
quitGame()
if gameStarted is True:
drawingPlayer()
movingPlayer()
creatingPlatform()
movingPlatform()
drawingPlatform()
elif gameEnded is True:
surface.blit(GameOverImage, (0, 0))
else:
surface.blit(StartImage, (0, 0))
pygame.display.update()
I have tried increasing the value of the platformDelay variable, with no avail. I have also tried tinkering around with creatingPlatform(). No matter what I do, they always appear in clumps! I would like it to be a game where the platforms come towards the player in regular intervals so it's actually playable, but then the speed of the platforms approaching will increase over time to increase the difficulty of the game. How would I go about doing this? Thank you! :)
I recommend to use pygame.time.get_ticks() to get the number of milliseconds the program is running. Note, since the time is given in milliseconds, a value of 1000 would be 1 second.
Initialize a variable newPlatformTimePoint by 0 and define an interval between an interval in which new platforms appear
newPlatformTimePoint = 0
newPlatformInterval = 200 # 0.2 seconds
When the game was startedGet the current time point in the main loop and set the time point for the first platform when the game was started:
timePoint = pygame.time.get_ticks()
if event.key == pygame.K_1:
oneDown = True
gameStart()
newPlatformTimePoint = timePoint + 1000 # 1 second after start
Add a new platform when the time point exceeded and increment set the next time point, by incrementing it by newPlatformInterval. Not the interval can be changed (speeded up) during the game.
if gameStarted is True:
drawingPlayer()
movingPlayer()
if timePoint > newPlatformTimePoint:
newPlatformTimePoint = timePoint + newPlatformInterval
creatingPlatform()
movingPlatform()
drawingPlatform()
Main loop code, with the applied suggestions:
newPlatformTimePoint = 0
newPlatformInterval = 200 # 0.2 seconds
while True:
timePoint = pygame.time.get_ticks()
surface.fill((95, 199, 250))
pressedKey = pygame.key.get_pressed()
for event in GAME_EVENTS.get():
if event.type == pygame.KEYDOWN:
# Event key for space should initiate sound toggle
if event.key == pygame.K_1:
oneDown = True
gameStart()
newPlatformTimePoint = timePoint + 1000 # 1 second after start
if event.type == pygame.KEYUP:
if event.key == pygame.K_1:
oneDown = False
#KEYUP for the space bar
if event.type == GAME_GLOBALS.QUIT:
quitGame()
if gameStarted is True:
drawingPlayer()
movingPlayer()
if timePoint > newPlatformTimePoint:
newPlatformTimePoint = timePoint + newPlatformInterval
creatingPlatform()
movingPlatform()
drawingPlatform()
elif gameEnded is True:
surface.blit(GameOverImage, (0, 0))
else:
surface.blit(StartImage, (0, 0))
pygame.display.update()
I have been coding a program, a survival game, on Python. I seem to have an issue with adding Images/Sprites. I am noticing the images blink. Any way to fix this?
import os
import pygame
import time
import random
from pygame.locals import *
launchLog = pygame.init()
print(launchLog)
white = (255,255,255)
black = (0,0,0)
red=(255,0,0)
blue=(0,0,255)
green=(0,255,0)
skin = (236,227,100)
size = 10
dependant = (green)
rate = 0.0018
weight = 100
bound_x = 600
bound_x2 = bound_x-size
bound_y = 600
bound_y2 = bound_y-size
screen = pygame.display.set_mode((bound_x,bound_y))
pygame.display.set_caption("Survival: EfEs Edition")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None,25)
x = 300
y = 300
roundX = x
roundY = y
img=pygame.image.load("pewds.png")
def hmn(x,y,size):
clothes = pygame.draw.rect(screen,skin,[x,y,size,size-size*2])
snake = pygame.draw.rect(screen, red, [x,y,size,size])
def mesg(msg,color):
txt = font.render(msg, True, color)
screen.blit(txt, [x,y-30])
display.flip(img)
def gameLoop():
global x
global y
jump = 1
quitted = False
starved = 100
eaten = False
restart = False
lead_change = 0
lead_y = 0
randF_x = random.randrange(0,bound_x)
randF_y = random.randrange(0,bound_y)
didX2=round(randF_x/10.0)*10.0
didY2=round(randF_y/10.0)*10.0
while not quitted:
screen.blit(img,(x,y -15))
screen.blit(img,(x,y -15))
pygame.display.update()
hmn(x,y,size)
starved=starved-rate
#print(starved)
if starved<0:
screen.fill(white)
mesg("You died of hunger! Press R to restart.",red)
pygame.display.flip()
time.sleep(0.3)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
starved = 100
pygame.display.update()
rate = 0.0018
x=300
y=300
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.display.update()
quitted = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
lead_change = -.2
elif event.key == pygame.K_d:
lead_change = .2
elif event.key == pygame.K_w:
lead_y = .2
elif event.key == pygame.K_s:
lead_y = -0.2
if event.type == pygame.KEYUP:
if event.key == pygame.K_d or event.key == pygame.K_a:
lead_change = 0
#print(x)
#print(y)
elif event.key == pygame.K_ESCAPE:
#print("Quitting")
quitted = True
elif event.key == pygame.K_w or event.key == pygame.K_s:
#print(y)
lead_y=0
x += lead_change
y -= lead_y
roundX = x
roundY = y
global roundX
global roundY
didX=round(roundX/10)*10
didY=round(roundY/10)*10
screen.fill(white)
s = pygame.draw.rect(screen, red, [bound_x2/15,bound_y2/20, starved * 2, 50])
pygame.draw.rect(screen, dependant, [didX2,didY2,10,10])
pygame.display.update()
#boundary script
if x>bound_x2:
x=bound_x2
elif x<-1:
x=-1
elif y<2:
y=2
elif y>590:
y=590
hmn(x,y,size)
pygame.display.flip()
if didX == didX2 and didY==didY2:
didX2 = round(random.randrange(0,bound_x)/10)*10
didY2 = round(random.randrange(0,bound_y)/10)*10
global dependant
dependant = green
global starved
starved = starved +0.01
global weight
weight = weight + 3
elif weight>150:
mesg("Weight increased! You now get hungry faster.",black)
pygame.display.update()
global rate
rate = rate+0.0008
pygame.display.update()
clock.tick(55)
mesg("Leaving game", black)
screen.blit(img,(x,y-15))
pygame.display.update()
time.sleep(2)
pygame.quit()
quit()
gameLoop()`
Please excuse the bad coding, the game is only in it's earliest state.
The correct sequence is to:
draw everything you want to show on a frame (all the blit()s, draw()s), etc.
do only one of display.update() with a list of all the changed regions OR display.flip() to update the whole screen once you've drawn everything
tl;dr - don't mix draw()s with update()s.
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!")
Okay so I'm making a test for making a racing game...
And I want the car to move in the direction it's pointing.
Here is my code.
import pygame, sys
from pygame.locals import *
pygame.init()
mainClock = pygame.time.Clock()
degree = 0
WHITE = 250,250,250
rect2 = pygame.rect = (100,100,50,50)
WINDOWWIDTH = 1200
WINDOWHEIGHT = 750
thing = pygame.image.load('car.png')
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Teh test')
left = False
right = False
while True:
rect2 = pygame.rect = (100,100,50,50)
if right == True:
degree -= 2
if left == True:
degree += 2
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == ord('a'):
left = True
if event.key == ord('d'):
right = True
if event.type == KEYUP:
if event.key == ord('a'):
left = False
if event.key == ord('d'):
right = False
pygame.draw.rect(screen,WHITE,rect2)
screen.fill((40, 40, 40))
thing2 = pygame.transform.rotate(thing,degree)
screen.blit(thing2,(100,100))
pygame.display.update()
mainClock.tick(60)
So like I said I want to know how to move the car in the direction it's pointing.
I tried to think of a way but I couldn't think of anything. So there isn't really anything to correct.
(If there are any questions I'll edit my question to answer it.) Please make sure you know pygame before answering.
You'll want to use trigonometry to calculate how much you want to move in the x and y directions, so that the car ends up moving in the correct direction. To calculate this, you can do this:
dx = math.cos(math.radians(degree))
dy = math.sin(math.radians(degree))
position = (position[0] + dx * SPEED, position[1] - dy * SPEED)
Note that you'll also need to initialize a position variable somewhere at the start of your code like this:
position = (100, 100)
Then, you have to change the blit line of code so you draw at the position variable, instead of at (100, 100) all of the time:
screen.blit(thing2, position)
Edit: Working example
import pygame, sys
from pygame.locals import *
import math
pygame.init()
mainClock = pygame.time.Clock()
degree = 0
WHITE = 250,250,250
rect2 = pygame.rect = (100,100,50,50)
WINDOWWIDTH = 1200
WINDOWHEIGHT = 750
thing = pygame.image.load('car.png')
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Teh test')
left = False
right = False
position = (100, 100)
while True:
rect2 = pygame.rect = (100,100,50,50)
if right == True:
degree -= 2
if left == True:
degree += 2
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == ord('a'):
left = True
if event.key == ord('d'):
right = True
if event.type == KEYUP:
if event.key == ord('a'):
left = False
if event.key == ord('d'):
right = False
pygame.draw.rect(screen,WHITE,rect2)
screen.fill((40, 40, 40))
thing2 = pygame.transform.rotate(thing,degree)
dx = math.cos(math.radians(degree))
dy = math.sin(math.radians(degree))
position = (position[0] + dx, position[1] - dy)
screen.blit(thing2, position)
pygame.display.update()
mainClock.tick(60)
Working example to kabb answer
import pygame, sys
from pygame.locals import *
import math # math library
pygame.init()
mainClock = pygame.time.Clock()
degree = 0
WHITE = 250,250,250
rect2 = pygame.rect = (100,100,50,50)
WINDOWWIDTH = 1200
WINDOWHEIGHT = 750
thing = pygame.image.load('car.png')
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Teh test')
left = False
right = False
forward = False
backward = False
thing2_x = 100
thing2_y = 100
speed = 20
while True:
rect2 = pygame.rect = (100,100,50,50)
if right: # don't need == True
degree -= 2
while degree < 0:
degree += 360
elif left: # don't need == True
degree += 2
while degree > 359:
degree -= 360
dx = math.cos(math.radians(degree))
dy = math.sin(math.radians(degree))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == K_a: # use constants K_a
left = True
elif event.key == K_d: # use constants K_d
right = True
elif event.key == K_w: # use constants K_w
forward = True
elif event.key == K_s: # use constants K_s
backward = True
if event.type == KEYUP:
if event.key == K_a: # use constants K_a
left = False
elif event.key == K_d: # use constants K_d
right = False
elif event.key == K_w: # use constants K_w
forward = False
elif event.key == K_s: # use constants K_s
backward = False
if forward:
thing2_y -= int(speed * dx)
thing2_x -= int(speed * dy)
elif backward:
thing2_y += int(speed * dx)
thing2_x += int(speed * dy)
pygame.draw.rect(screen,WHITE,rect2)
screen.fill((40, 40, 40))
thing2 = pygame.transform.rotate(thing,degree)
screen.blit(thing2,(thing2_x,thing2_y))
pygame.display.update()
mainClock.tick(60)
My goal for this question is to be able to achieve an answer which explains how to make it so that when my character moves around to pick up the 'baddie(s)', the baddies will then automatically re-spawn onto the screen. Keeping total amount of sprites on the screen at any one time for the player to pick up at 40.
I am having problems being able to control the way the 'pikachu.jpg' sprites spawn. I am either able to spawn the sprites solely in a group fashion by entering an integer into my program manually or i write my attempt to test it wrong and the program upholds an infinite loop of drawing baddie sprites. I had set up a system which i believed should have coped with keeping the baddies at 40 sprites solid, though it did not work. I am not very good with python yet and i would really appreciate help with this issue.
import necessary pygame modules
import sys
import random
import time
import pygame
from pygame.locals import *
# initialise pygame
pygame.init()
# define window width and height variables for ease of access
WindowWidth = 600
WindowHeight = 500
global PLAY
PLAY = False
x = 600 / 3
y = 460 / 2 - 25
# load and define image sizes
enemyImage = pygame.image.load('pikachu.jpg')
enemyStretchedImage = pygame.transform.scale(enemyImage, (40,40))
screen = pygame.display.set_mode((WindowWidth, WindowHeight))
def play(PLAY):
playerImage = pygame.image.load('player.jpg')
playerStretchedImage = pygame.transform.scale(playerImage, (40, 40))
movex,movey = 0,0
charx, chary=300, 200
enemyy, enemyx = 10, 10
moveright = False
moveleft = False
spawn = True
direction = 'down'
baddie = []
for i in range(20):
baddie.append(pygame.Rect(random.randint(0, WindowWidth - 40), random.randint(0, 0), 40, 40))
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == ord('m'):
pygame.mixer.music.stop()
music = False
if event.key == ord('n'):
pygame.mixer.music.play()
music = True
if event.key == ord('a'):
moveleft = True
if event.key == ord('d'):
moveright = True
if event.key == ord('w'):
movey = -0.5
if event.key == ord('s'):
movey = 0.5
if event.key == ord('p'):
time.sleep(5)
if event.type ==KEYUP:
if event.key == ord('a'):
moveleft = False
if moveleft == False:
movex = 0
if event.key == ord('d'):
moveright = False
if moveright == False:
movex = 0
if event.key == ord('w'):
movey = 0
if event.key == ord('s'):
movey = 0
elif event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN:
pygame.quit()
sys.exit()
screen.fill(pygame.Color("red"))
player = pygame.Rect(charx, chary, 40, 40)
if direction == 'down':
enemyy += 0.1
if moveright ==True:
movex = 0.5
if moveleft ==True:
movex = -0.5
if player.bottom > WindowHeight:
chary = WindowHeight - 40
movey = 0
if player.top < 0:
chary = 1
movey = 0
if player.left < 0:
charx = 1
movex = 0
if player.right > WindowWidth:
charx = WindowWidth - 40
movex = 0
for bad in baddie[:]: #Here is where my attempt of testing was.
if bad < 40:
spawn = True
if bad >= 40:
spawn = False
if spawn == True:
baddie.append(pygame.Rect(random.randint(0, WindowWidth - 40), random.randint(0,0), 40, 40))
screen.blit(playerStretchedImage, player)
charx+=movex
chary+=movey
for bad in baddie[:]:
if player.colliderect(bad):
baddie.remove(bad)
for bad in baddie:
screen.blit(enemyStretchedImage, bad)
pygame.display.update()
def presskey():
myfont = pygame.font.SysFont("monospace", 30)
label = myfont.render("press space to play!", 1, (255,125,60))
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_SPACE:
PLAY = True
if PLAY == True:
play(PLAY)
return
screen.fill(pygame.Color("cyan"))
screen.blit(label, (x,y))
pygame.display.update()
presskey()
Here you're trying to fill up count of baddies up to 40, but the bad is a rectangle and you're using it as a number of buddies:
for bad in baddie[:]: #Here is where my attempt of testing was.
if bad < 40:
spawn = True
if bad >= 40:
spawn = False
if spawn == True:
baddie.append(pygame.Rect(random.randint(0, WindowWidth - 40), random.randint(0,0), 40, 40))
I suggest you to replace those lines with:
if len(baddie)<40:
baddie.append(pygame.Rect(random.randint(0, WindowWidth - 40),
You can get the number of items in your [] list using len(baddie). You should get a new baddie each game loop cycle.