So I have a platform game I made in PyGame that all works, so I am now trying to make it a bit more colourful. So the code that I changed used to be:
def draw(self, screen):
""" Draw everything on this level. """
# Draw the background
screen.fill(BLUE)
and I changed it to:
def draw(self, screen):
""" Draw everything on this level. """
# Image from http://freepik
background_image = pygame.image.load("pink background.jpg").convert()
# Draw the background
screen.blit(background_image, [0, 0])
to get the pink background to be the background :) Now this is the only thing I changed in the code but everything now moves much slower e.g. the player that is being controlled by the user and the moving platform. There are two levels and I didn't change the code for the second levels background and the player still moves fine there :)
I did think I might of changed the line:
# Limit to 60 frames per second
clock.tick(60)
by accident, but it is still exactly the same.
I hope someone can help :) and thank you in advance :)
The error occurs somewhere in this code:
`
def main():
pygame.init()
# Set the height and width of the screen
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)
pygame.display.set_caption('Platformer with moving platforms')
# Create the player
player = Player()
# Create all the levels
level_list = []
level_list.append(Level_01(player))
# Set the current level
current_level_no = 0
current_level = level_list[current_level_no]
active_sprite_list = pygame.sprite.Group()
player.level = current_level
player.rect.x = 200
player.rect.y = SCREEN_HEIGHT - player.rect.height - 30
active_sprite_list.add(player)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop --------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
if event.key == pygame.K_RIGHT:
player.go_right()
if event.key == pygame.K_UP:
player.jump()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.change_x < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.change_x > 0:
player.stop()
# Update the player.
active_sprite_list.update()
# Update items in the level
current_level.update()
# If the player gets near the right side, shift the world left (-x)
if player.rect.right >= 500:
diff = player.rect.right - 500
player.rect.right = 500
current_level.shift_world(-diff)
# If the player gets near the left side, shift the world right (+x)
if player.rect.left <= 120:
diff = 120 - player.rect.left
player.rect.left = 120
current_level.shift_world(diff)
# If the player touches the floor they die.
if player.rect.y == SCREEN_HEIGHT - player.rect.height:
done = True
# If the player gets to the end of the level, go to the next level
current_position = player.rect.x + current_level.world_shift
if current_position < current_level.level_limit:
all_lines = []
list_of_files = os.listdir()
if username1 in list_of_files:
file1 = open(username1, "r")
for line in file1:
all_lines.append(line)
all_lines[2] = str(1)
with open(username1, 'w') as filehandle:
for listitem in all_lines:
filehandle.write(str(listitem))
done = True
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
current_level.draw(screen)
active_sprite_list.draw(screen)
# Select the font to use, size, bold, italics
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Limit to 60 frames per second
clock.tick(60)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()
if __name__ == "__main__":
main()
`
Do not load the image in your main loop. Define (load) it outside of the loop and then use it via variable. This is your problem, because it loads the image (in this case FPS = 60) times per second from your disk.
Related
import pygame, time
from sys import exit
pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
font = pygame.font.SysFont("Arial", 18)
def update_fps():
fps = str(int(clock.get_fps()))
fps_text = font.render(fps, 1, pygame.Color("coral"))
return fps_text
# Game Variables / Functions
screen_width = 1068
screen_height = 628
screen = pygame.display.set_mode((screen_width, screen_height))
original_player_pos = (50, 500)
original_player_size = (40, 60)
FPS = 69
gravity = 0
jump_force = 15
player_speed_right = 10
player_speed_left = 10
ground_grip = True
can_jump = True
# Player
class player():
player_surf = pygame.image.load("Graphics\player_idle.png").convert_alpha()
player = player_surf.get_rect(topleft=(original_player_pos))
class background():
sky_surf = pygame.image.load("Graphics\Sky.png")
sky_surf = pygame.transform.scale(sky_surf, (screen_width * 2, screen_height * 2))
sky = sky_surf.get_rect(topleft=(0, -screen_height))
class surfaces():
main_platform_surf = pygame.image.load("Graphics\main_ground.png")
main_platform = main_platform_surf.get_rect(topleft=(0, screen_height - main_platform_surf.get_height() + (main_platform_surf.get_height()) / 2))
# Game Engine Functions
def y_movement():
global gravity, ground_grip,can_jump
gravity += 1
player().player.y += gravity
if ground_grip == True:
if player().player.colliderect(surfaces().main_platform):
player().player.y = surfaces().main_platform.y - original_player_size[1]
if not player().player.colliderect(surfaces().main_platform) and player().player.y < surfaces().main_platform.y - original_player_size[1]:
can_jump = False
else:
can_jump = True
def x_movement():
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
player().player.x += player_speed_right
return "Right"
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
player().player.x -= player_speed_left
return "Left"
def draw(surface, rect):
screen.blit(surface, rect)
def jump():
global gravity
gravity = -jump_force
# Game Engine
while True:
update_fps()
screen.fill("black")
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and can_jump == True:
ground_grip = False
if ground_grip == False:
jump()
ground_grip = True
x_movement()
y_movement()
draw(background().sky_surf, background().sky)
draw(surfaces().main_platform_surf, surfaces().main_platform)
draw(player().player_surf, player().player)
draw(update_fps(), (10,0))
clock.tick(FPS)
pygame.display.update()
Please try the code above out yourself, if you don't mind add some graphics to replace the pygame.image.load() or just replace it with a blank surface. When you run the program you see the main character and stuff, you can move around using WASD or arrow keys. Feel free to move around some stuff. Till now there is not a problem right? Now what I want you to do is stand still for 10 seconds (might happen sooner or later than that, should be around 10 seconds tho). When you stand still you will see the player sprite that you were moving around earlier literally just disappear. Now exit the program and add
print(player().player.y)
you will see the current player y location. Wait till the player dissapeares, and once it does, look at the y location that's gonna be printed out in your terminal. It will rapidly increase.
I tried 2 things. I added a variable that tries to grip the player into the ground if the player.y is over 0. It did not help and the player goes down anyways. I tried adding a variable that decides when the player can jump (because the y movement is linked directly to gravity and jumping) to decide when the player can jump. I was expecting the player sprite to just stay where it is.
When the player hits the platform, they must set the bottom of the player to the top of the platform.
player().player.bottom = surfaces().main_platform.top
Also set gravity = 0. If you do not reset gravity, gravity will increase until the player falls through the platform.
def y_movement():
global gravity, ground_grip,can_jump
gravity += 1
player().player.y += gravity
if ground_grip == True:
if player().player.colliderect(surfaces().main_platform):
player().player.bottom = surfaces().main_platform.top
gravity = 0
can_jump = True
I'm quite new to pygame and am currently doing a school project. My problem is that i have been attempting to create a border for my game so my charectar cant go out from the screen.
Heres my code so far:
# This imports the Pygame Module / loads pygame keywords
import pygame
# This lets python use my file system
import sys
# This helps python identify my OS, which is Windows 10
import os
"""
Variables
"""
img = 'PlayerSprite1'
# This is the basic set screen width and height / 320x320 pixels
worldx = 1271
worldy = 957
world = pygame.display.set_mode([worldx, worldy])
# This is for the frame rate and animation cycles, in order
fps = 30
ani = 4
# These are the color definitions - Red, Green, Blue (RGB)
RED = (0, 0, 0)
GREEN = (128, 128, 128)
BLUE = (128, 128, 128)
# This is used in order to make the sprites color block be 'invisible', in order for it to blend into the background
ALPHA = (00, 00, 00)
ALPHA1 = (255, 255, 255)
"""
Objects
"""
'Individual sprite classes: '
class Player(pygame.sprite.Sprite):
# Spawn the player's sprite/ character/ main player's sprite
def __init__(self):
pygame.sprite.Sprite.__init__(self)
# These variables will be to track frames and movements
self.movex = 0 # This is to monitor movement along X
self.movey = 0 # This is to monitor movement along Y
self.frame = 0 # This counts frames
self.health = 10 # This counts health
self.images = []
for i in range(1, 5):
# This loads the image from the selected directory in the pycharm folder
img = pygame.image.load(os.path.join('images', 'PlayerSprite1' + str(i) + '.png')).convert()
img.convert_alpha() # This is used to optimize alpha
img.set_colorkey(ALPHA) # This is used to set alpha
self.images.append(img)
self.image = self.images[0]
self.rect = self.image.get_rect()
# This controls the players sprites movement
def control(self, x, y):
self.movex += x
self.movey += y
# This updates the sprites position, by redefining its position, designated by self.rect.x and self.rect.y,
# to its current position plus whatever amount movex or movey is
def update(self):
self.rect.x = self.rect.x + self.movex
self.rect.y = self.rect.y + self.movey
# This is for moving left
if self.movex < 0:
self.frame += 1
if self.frame > 3 * ani:
self.frame = 0
self.image = self.images[self.frame // ani]
hit_list = pygame.sprite.spritecollide(self, enemy_list, False)
for enemy in hit_list:
self.health -= 1
print(self.health)
# This is for moving right
if self.movex > 0:
self.frame += 1
if self.frame > 3 * ani:
self.frame = 0
self.image = self.images[self.frame // ani]
# This class is for the main antagonistic sprite in opposition to players sprite
class Enemy(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
# These variables will be to track frames and movements
self.movex = 0 # This is to monitor movement along X
self.movey = 0 # This is to monitor movement along Y
self.frame = 0 # This counts frames
self.images = []
self.counter = 0
for i in range(1, 4):
# This loads the image from the selected directory in the pycharm folder
img = pygame.image.load(os.path.join('images', 'antagonist' + str(i) + '.png')).convert()
img.convert_alpha() # This is used to optimize alpha
img.set_colorkey(ALPHA1) # This is used to set alpha
self.images.append(img)
self.image = self.images[0]
self.rect = self.image.get_rect()
# This is to alter the scale of this sprite in order for it to fit into the overall pixel scale of the game
# THIS IS NOT YET DONE, DO ASAP
pygame.transform.scale(pygame.image.load(os.path.join('images', 'antagonist' + str(i) + '.png')), (13, 29))
def move(self):
distance = 80
speed = 8
if self.counter >= 0 and self.counter <= distance:
self.rect.x += speed
elif self.counter >= distance and self.counter <= distance * 2:
self.rect.x -= speed
else:
self.counter = 0
self.counter += 1
'These classes are for levels: '
# This class is for level one of the game ( NOT YET DONE )
class Level():
def bad(lvl, eloc):
if lvl == 1:
enemy = Enemy()
eloc = 0
eloc = 1
img = 'antagonist1.png'
enemy_list = pygame.sprite.Group()
enemy_list.add(enemy)
if lvl == 2:
print("Level " + str(lvl))
return enemy_list
'These classes are for Platforms'
"""
Setup
"""
# This creates the boundaries for the sprite so it dosnt go outside the borders
# This is used for various loops, mainly for keeping the main loop, in loop
main = True
# This is for the internal clock and for pygame to initialize
clock = pygame.time.Clock()
pygame.init()
# This is to set up the Main background
backdrop = pygame.image.load(os.path.join('images', 'Main Background.jpg'))
backdropbox = world.get_rect()
# This is to bring the actual '123' sprite into the game, or the 'game world'
player = Player() # This spawns player's sprite
player.rect.x = 10 # go to x
player.rect.y = 12 # go to y
player_list = pygame.sprite.Group()
player_list.add(player)
steps = 10 # This is how many pixels the sprite will move
# This is to add the Main antagonistic enemy sprite into the 'actual' game and further create a 'group' for a sort of
# wave, which will be a core mechanic of the game
enemy = Enemy() # This spawns the antagonist
enemy.rect.x = 10
enemy.rect.y = 12
enemy_list = pygame.sprite.Group() # This creates the antagonist group
enemy_list.add(enemy) # This adds the antagonist to the group
eloc = []
eloc = [300, 0]
enemy_list = Level.bad(1, eloc)
"""
Main Loop
"""
# This is to make sure the background does not just appear for a singular millisecond
world.blit(backdrop, backdropbox)
player.update() # This updates the players position to make the character move from pixel to pixel, making it appear
# as it is moving
# This, similar to the above is to make sure the player's sprite does not just appear for a singular millisecond
player_list.draw(world) # draw player
enemy_list.draw(world) # refresh enemies
pygame.display.flip()
clock.tick(fps)
# This is the main loop, which keeps the game's execution in a loop, in order to keep it on the screen and operating
# for longer then a couple milliseconds
while main:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
try:
sys.exit()
finally:
main = False
# These next two sections add keybindings, this time being changed by replacing the print statements with the
# player's sprite name, including the .control function, and how many steps to move with each loop
if event.type == pygame.KEYDOWN:
if event.key == ord('q'):
pygame.quit()
try:
sys.exit()
finally:
main = False
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(-steps, 0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(steps, 0)
if event.key == pygame.K_DOWN or event.key == ord('s'):
player.control(-steps, 0)
if event.key == pygame.K_UP or event.key == ord('w'):
player.control(-steps, 0)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == ord('a'):
player.control(steps, 0)
if event.key == pygame.K_RIGHT or event.key == ord('d'):
player.control(-steps, 0)
if event.key == pygame.K_DOWN or event.key == ord('s'):
player.control(-steps, 0)
if event.key == pygame.K_UP or event.key == ord('w'):
player.control(-steps, 0)
world.blit(backdrop, backdropbox)
img_rect = img.get_rect(topleft=[100, 200])
world.blit(img, img_rect)
player.update()
player_list.draw(world)
enemy_list.draw(world)
for e in enemy_list:
e.move()
pygame.display.flip()
clock.tick(fps)
I know it has somthing to do with classes and localisation of code and ive tried to fix that many times but it never seems to work, either not working once executed or never even executing. If anyone has any suggestions, that would be great! Also apoligies for the very messy and unorganised code, if anyone has any further tips on how i should improve my code, though not neccesary, I'll be in your debt!
To get rid of the error message just out-comment the lines causing it as follows:
world.blit(backdrop, backdropbox)
# img_rect = img.get_rect(topleft=[100, 200])
# world.blit(img, img_rect)
player.update()
This will do no harm to the game as these lines do nothing else ( if img is an actual pygame image ) as drawing an image to the screen which appears to have no function in the game.
Then see what the code does and how to achieve with it what you want.
With a running code you can investigate its behavior while changing and updating the code and so make further progress.
Another option is to actually display an image if this image was intended to be a border, but for this you need to assign a pygame image to img as follows:
world.blit(backdrop, backdropbox)
img = pygame.image.load('border.png').convert()
img_rect = img.get_rect(topleft=[100, 200])
world.blit(img, img_rect)
player.update()
Notice that the player and enemy images will overlay the border.png image as they will be drawn later in the game while main loop. Move the code displaying this image after the code updating the player and enemy if you want the border not to be covered by the player or enemy sprites.
This above is my guess what you are after and hope it helps you to make further progress.
I am trying to create a flappy bird game with python but i cant get multiple walls to appear on the page and move across.
I was wondering if there was a way to make multiple walls (rectangles) and move them without defining them individually. Im using Pygame.
import pygame
pygame.init()
white = (255,255,255)
yellow = (255,200,0)
green = (0,255,0)
displayHeight = 600
displayWidth = 500
gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
clock = pygame.time.Clock()
crash = False
def bird(b_X, b_Y, b_R, b_Colour):
pygame.draw.circle(gameDisplay, b_Colour, (b_X, b_Y), b_R)
def game_loop():
bX = 50
bY = 300
bR = 20
bColour = yellow
velocity = 0
gravity = 0.6
lift = -15
while crash == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.QUIT
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
velocity += lift
gameDisplay.fill(white)
bird(bX, bY, bR, bColour)
velocity = velocity + gravity
bY += velocity
bY = round(bY)
if bY > displayHeight:
bY = displayHeight
velocity = 0
if bY < 0:
bY = 0
velocity = 0
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
Is there a way to make a big population of blocks and move them individually without defining them one by one.
I do not know how the code exactly works out, but you can store multiple wall 'objects' in a list, and looping over that list every time you update the screen. In pseudocode, it works like this
wall-list = []
for wanted_wall_amount in range():
wall = create_a_wall
wall-list.append(wall)
game loop:
for wall in wall-list:
wall.x_coordinate += movespeed
because of the for loop within the game loop, every wall object you stored will update it's position, or whatever you want to move simultanously. I hope you understand the weird pseudocode
I was learning pygame by following this tutorial (A little snake game). When the player is game over, the player can choose to quit or reset the game. In the latter case I call the function gameloop() again, which is were I am having problems
Code
# create a player
player = Player()
# create all levels
level_list = []
level_list.append(levels01.Level_01(player))
# set the current level
current_level_no = 0
current_level = level_list[current_level_no]
active_sprite_list = pygame.sprite.Group()
player.level = current_level
# player position
player.rect.x = 70
player.rect.y = 360
active_sprite_list.add(player)
clock = pygame.time.Clock()
def gameloop():
# set boolean default is false
gameExit = False
gameOver = False
while not gameExit:
# loop for game over
if gameOver == True:
msg_to_screen("You Lose", constants.RED, y_displace=-50, size = "large")
msg_to_screen("Press Q to Quit and Press C to play again", constants.BLACK, 50, size = "medium")
pygame.display.update()
while gameOver == True:
# loop for key quit game dan repeat the game
for event in pygame.event.get():
# event game quit
if event.type == pygame.QUIT:
gameExit = True
gameOver = False
# event key atau tombol pada saat ditekan
if event.type == pygame.KEYDOWN:
# config key Q for quit game
if event.key == pygame.K_q:
gameExit = True
gameOver = False
# config key C for retry
if event.key == pygame.K_c:
# gameloop() # calling this function is doesn't work
# how ?
pass
# config player control
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.go_left()
elif event.key == pygame.K_RIGHT:
player.go_right()
elif event.key == pygame.K_UP:
player.jump()
# Update the player.
active_sprite_list.update()
# Update items in the level
current_level.update()
# If the player gets near the right side, shift the world left (-x)
if player.rect.right >= 500:
diff = player.rect.right - 500
player.rect.right = 500
current_level.shift_world(-diff)
# If the player gets near the left side, shift the world right (+x)
if player.rect.left <= 120:
diff = 120 - player.rect.left
player.rect.left = 120
current_level.shift_world(diff)
# if player fall is game over
if player.rect.bottom >= constants.SCREEN_HEIGHT or player.rect.bottom < 0 :
gameOver = True
In that code, I created gameloop() function, just like in the tutorial, and I call the function in the case the player fails and wants to retry, but when that happens, the function is not working. The player can't come back in the start position.
The position is not reset because gameloop does nothing to reset the position. In programming, changes don't happen by magic -- you have to write the code to make those changes. gameloop clears two Boolean variables, and does nothing else.
To make this work, you have to identify which initialization you need to do only once (such as creating the board levels) and which you need to do for every new game. You need to move the "every game" items inside gameloop, something like this:
def gameloop():
# set the current level
current_level_no = 0
current_level = level_list[current_level_no]
active_sprite_list = pygame.sprite.Group()
player.level = current_level
# player position
player.rect.x = 70
player.rect.y = 360
active_sprite_list.add(player)
clock = pygame.time.Clock()
# set boolean default is false
gameExit = False
gameOver = False
I'm not sure I got them all right; that level of detail and review is out of scope for Stack Overflow. I expect that this change will help you move along in programming the game.
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()