Issues with key presses and event handler in Pygame [duplicate] - python

This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
How to get keyboard input in pygame?
(11 answers)
Closed 3 months ago.
I am new to Pygame and am facing issues getting the event handler to register my keystrokes to move my player when I call that class under the event handler in the main loop
I run this code and the level and player render correctly but not able to move my player. I've looked at various other answers such as adding pygame.event.pump() but this doesn't work and shouldn't be needed as it should be handled by the main event handler
import pygame, sys
# Settings
size = width, height = (800, 800)
FPS = 60
road_w = width//1.6
roadmark_w = width//80
right_lane = width/2 + road_w/4
left_lane = width/2 - road_w/4
speed = 5
player_start = right_lane, height*0.8
enemy_start = left_lane, height*0.2
# Create Player Class
class Player(pygame.sprite.Sprite):
def __init__(self,pos,groups):
super().__init__(groups)
self.image = pygame.image.load("car.png").convert_alpha()
self.rect = self.image.get_rect(center = pos)
self.direction = pygame.math.Vector2(0,0)
self.speed = 5
def input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
self.direction.y = -1
elif keys[pygame.K_DOWN]:
self.direction.y = 1
else:
self.direction.y = 0
if keys[pygame.K_RIGHT]:
self.direction.x = 1
print(self.direction.x)
elif keys[pygame.K_LEFT]:
self.direction.x = -1
else:
self.direction.x = 0
def move(self, speed):
if self.direction.magnitude() != 0:
self.direction = self.direction.normalize()
self.rect.x += self.direction.x * speed
self.rect.y += self.direction.y * speed
def update(self):
self.input()
self.move(self.speed)
#Create Level Class
class Level:
def __init__(self):
# get display surface
self.display_surface = pygame.display.get_surface()
#Sprite group set up
self.player_sprite = pygame.sprite.Group()
def create_map(self):
pygame.draw.rect(self.display_surface,(50, 50, 50),\
(width/2-road_w/2, 0, road_w, height))
pygame.draw.rect(self.display_surface,(255, 240, 60),\
(width/2 - roadmark_w/2, 0, roadmark_w, height))
pygame.draw.rect(self.display_surface,(255, 255, 255),\
(width/2 - road_w/2 + roadmark_w*2, 0, roadmark_w, height))
pygame.draw.rect(self.display_surface,(255, 255, 255),\
(width/2 + road_w/2 - roadmark_w*3, 0, roadmark_w, height))
def run(self):
# Update and draw level
self.create_map()
self.player = Player(player_start,[self.player_sprite])
self.player_sprite.draw(self.display_surface)
self.player_sprite.update
# Create Game Class
class Game:
def __init__(self):
# Setup
pygame.init()
self.screen = pygame.display.set_mode(size)
pygame.display.set_caption('Car Game')
self.clock = pygame.time.Clock()
self.level = Level()
def run(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
self.screen.fill((60,220,0))
self.level.run()
pygame.display.update()
self.clock.tick(FPS)
# Run Game
if __name__ == '__main__':
game = Game()
game.run()
Car.png

Related

Why is my move function not working in pygame?

IDK why my player.move() is not working here's my main class:
import pygame
from player import *
pygame.init()
WIDTH, HEIGHT = 900, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("MyGame!")
FPS = 60
player_x = 500
player_y = 500
PLAYER_WIDTH = 60
PLAYER_HEIGHT = 60
PLAYER_VEL = 5
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
keys_pressed = pygame.key.get_pressed()
player_rect = pygame.Rect(player_x, player_y, PLAYER_WIDTH, PLAYER_HEIGHT)
player = Player(player_rect, BLACK, WIN, keys_pressed, PLAYER_VEL)
def draw_window():
WIN.fill(WHITE)
pygame.display.update()
def main():
run = True
clock = pygame.time.Clock()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
draw_window()
player.move()
player.draw_player()
pygame.display.update()
pygame.quit()
if __name__ == '__main__':
main()
and here's my other class called player.py that the move function is not working:
import pygame
class Player(object):
def __init__(self, player, color, surface, keys_pressed, vel):
self.player = player
self.color = color
self.surface = surface
self.keys_pressed = keys_pressed
self.vel = vel
def draw_player(self):
pygame.draw.rect(self.surface, self.color, self.player)
pygame.display.update()
def move(self):
if self.keys_pressed[pygame.K_a]:
self.player.x -= self.vel
if self.keys_pressed[pygame.K_d]:
self.player.x += self.vel
I tried putting the player = Player(...) before the main function.
But whatever I tried, it doesn't seem to work and this is my first time posting a question on stackoverflow. This problem also happened alot in the past so thanks if you helped me out.
pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is 1, otherwise 0. The contents of the keys_pressed list don't magically change when the state of the keys changes. keys_pressed is not tied to the keys. You need to get the new state of the keys in every frame:
class Player(object):
# [...]
def move(self):
# get current state of the keys
self.keys_pressed = pygame.key.get_pressed()
if self.keys_pressed[pygame.K_a]:
self.player.x -= self.vel
if self.keys_pressed[pygame.K_d]:
self.player.x += self.vel

Pygame 2D tiled game, moving camera. Character moving faster than camera

I had a problem with creating camera in pygame, I assumed code below should work but our player is moving faster than camera and is going out of the window. Somebody know what's the issue?
import pygame, sys
class Player(pygame.sprite.Sprite):
def __init__(self, pos, group):
super().__init__(group)
self.image = pygame.image.load('./chatacters/players/player_one.png').convert_alpha()
self.rect = self.image.get_rect(center=(640, 360))
self.direction = pygame.math.Vector2()
self.speed = 5
# key inputs
def input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
self.direction.y = -1
elif keys[pygame.K_DOWN]:
self.direction.y = 1
else:
self.direction.y = 0
if keys[pygame.K_LEFT]:
self.direction.x = -1
elif keys[pygame.K_RIGHT]:
self.direction.x = 1
else:
self.direction.x = 0
# Moving using inputs
def move(self, speed):
if self.direction.magnitude() != 0:
self.direction = self.direction.normalize()
self.rect.center += self.direction * speed
# updating drawing
def update(self):
self.input()
self.move(self.speed)
class Camera(pygame.sprite.Group):
def __init__(self):
super().__init__()
self.display_surface = pygame.display.get_surface()
self.offset = pygame.math.Vector2()
self.half_w = self.display_surface.get_size()[0] // 2
self.half_h = self.display_surface.get_size()[1] // 2
self.map = pygame.image.load('./map/level_data/level.png').convert_alpha()
self.rect = self.map.get_rect(topleft=(0, 0))
def custom_draw(self, player):
self.offset.x = player.rect.centerx - self.half_w
self.offset.y = player.rect.centery - self.half_h
ground_offset = self.rect.topleft - self.offset
self.display_surface.blit(self.map, ground_offset)
class Game():
def __init__(self):
# Settings
self.WIDTH = 1280
self.HEIGHT = 720
self.FPS = 60
pygame.init()
pygame.display.set_caption('BetterFortinite')
self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
self.clock = pygame.time.Clock()
self.camera_group = Camera()
self.player = Player((100, 200), self.camera_group)
def game(self):
while True:
self.clock.tick(self.FPS)
self.screen.fill('black')
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# self.screen.fill("WHITE")
self.camera_group.custom_draw(self.player)
self.player.move(5)
self.player.update()
self.camera_group.draw(self.screen)
# self.camera_group.update()
pygame.display.update()
if __name__ in '__main__':
game = Game()
game.game()
I'm taking the center position of player rect minus half of the width size. Same with height and setting with it my offset. Then I'm setting my ground_offset as cords of topleft screen rect minus offset. What is wrong with this formula?
The problem is not with your formula, but with the code itsself. In the main game loop, you have:
self.player.move(5)
self.player.update()
While Player.update contains:
def update(self):
self.input()
self.move(self.speed)
As you can see, player.move is called twice. This means that the player is moved twice as much as intended and thus twice as fast as the camera, causing both to move at a different speed.
The solution to this problem would be to remove one of the calls of Player.move. I would remove the one in the main game loop as it uses a hardcoded value rather than the Player.speed constant, but it doesn't really matter which one you remove.

How to spawn enemy blocks continuously without manually creating them? [duplicate]

This question already has answers here:
Spawning multiple instances of the same object concurrently in python
(1 answer)
Issues with pygame.time.get_ticks() [duplicate]
(1 answer)
How to make instances spawn automatically around the player? [duplicate]
(1 answer)
Closed 1 year ago.
I am creating a game similar to the "Internet T-rex Game", Right now my game creates enemy blocks according to how many I manually create. I want it to be created by itself. My game is not fully completed yet, so please ignore the empty functions.
Heres my main.py
import pygame as pg
import random
from settings import *
from sprites import *
from os import path
class Game(object):
"""docstring for Game"""
def __init__(self):
# initialise game
global points , game_speed
pg.init()
self.screen = pg.display.set_mode((s_HEIGHT , s_WIDTH))
pg.display.set_caption(TITLE)
self.icon = pg.image.load("C:/Users/DELL/Documents/Jump Cube/Img/cube.png")
pg.display.set_icon(self.icon)
self.clock = pg.time.Clock()
self.running = True
self.game_speed = 14
points = 0
font = pygame.font.Font('freesansbold.ttf', 20)
self.load_data()
def load_data(self):
self.dir = path.dirname(__file__)
img_dir = path.join(self.dir, "Img")
#load spritesheet image
self.spritesheet = Spritesheet(path.join(img_dir, SPRITESHEET))
def new(self):
# Stars a new game
self.all_sprites = pg.sprite.Group()
self.platforms = pg.sprite.Group()
self.ene = pg.sprite.Group()
self.player = Player(self)
self.all_sprites.add(self.player)
pl = Platform(0, s_HEIGHT - 230, 800, 40)
en1 = Enemy(700, 517, 50, 50)
en2 = Enemy(600, 517, 50, 50)
en3 = Enemy(500, 517, 50, 50)
self.all_sprites.add(pl)
self.platforms.add(pl)
self.all_sprites.add([en1, en2, en3])
self.ene.add([en1, en2, en3])
self.Run()
def Run(self):
# Game Loop
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.Events()
self.Update()
self.Draw()
self.score()
def Update(self):
# Game Loop - Update
self.all_sprites.update()
hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.vel.y = 0
pass
def score(self):
global points , game_speed
points += 1
if points % 100 == 0:
game_speed += 1
text = font.render("Points : " + str(points), True, WHITE)
textrec = text.get_rect()
textrec.center = (700, 50)
self.screen.blit(text, textrec)
def Events(self):
# Game Loop - Events
for event in pg.event.get():
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
self.player.jump()
if event.type == pg.KEYDOWN:
if event.key == pg.K_RIGHT:
self.player.mover()
elif event.key == pg.K_LEFT:
self.player.movel()
def Draw(self):
# Game Loop - Draw
self.screen.fill(BLACK)
self.score()
self.all_sprites.draw(self.screen)
pg.display.update()
pass
def start_screen(self):
# shows the start screen
pass
def end_screen(self):
# shows the end screen
pass
g = Game()
g.start_screen()
while g.running:
g.new()
g.end_screen()
pg.quit()
sprites.py
import pygame as pg
from settings import *
vec = pg.math.Vector2
class Spritesheet():
# utility class for laoding and parsing spritesheets
def __init__(self, filename):
self.spritesheet = pg.image.load(filename).convert()
def get_image(self, x, y, width, height):
# grabs images from large spritesheets
image = pg.Surface((width, height))
image.blit(self.spritesheet, (0,0), (x, y, width, height))
image = pg.transform.scale(image , (50, 85))
return image
class Player(pg.sprite.Sprite):
def __init__(self, game):
pg.sprite.Sprite.__init__(self)
self.game = game
self.image = self.game.spritesheet.get_image(614, 1063, 120, 191)
self.image.set_colorkey(BLACK1)
self.rect = self.image.get_rect()
self.rect.center = (s_WIDTH / 2, s_HEIGHT / 2)
self.pos = vec(100, 600)
self.vel = (0, 0)
self.acc = (0, 0)
def jump(self):
#jump only if standing on plat
self.rect.y += 1
hits = pg.sprite.spritecollide(self, self.game.platforms, False)
self.rect.y -= 1
if hits:
self.vel.y = -8
def mover(self):
#move right
self.vel.x = 5
def movel(self):
#move right
self.vel.x = -5
def update(self):
self.acc = vec(0, PLAYER_GRAV)
self.vel += self.acc
self.pos += self.vel + 0.5 * self.acc
self.rect.midbottom = self.pos
class Platform(pg.sprite.Sprite):
def __init__(self, x, y, w, h):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((w, h))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
class Enemy(pg.sprite.Sprite):
def __init__(self, x, y, w1, h1):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((w1, h1))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def update(self):
self.rect.x -= game_speed
settings.py
import pygame
pygame.init()
#game options
TITLE = "Ninja Jump"
s_WIDTH = 600
s_HEIGHT = 800
FPS = 60
game_speed = 14
points = 0
font = pygame.font.Font('freesansbold.ttf', 20)
SPRITESHEET = "spritesheet_jumper.png"
#player properties
PLAYER_ACC = 0.5
PLAYER_GRAV = 0.3
#colors
WHITE = (199, 198, 196)
BLACK = (23, 23, 23)
GRAY = (121, 121, 120)
GREEN = (72, 161, 77)
BLACK1 = (0,0,0)
GRAY1 = (162, 162, 162)
Thanks for any help and let me know if the problem needs more clarification.
Spawn the enemies by a time interval. In pygame the system time can be obtained by calling pygame.time.get_ticks(), which returns the number of milliseconds since pygame.init() was called. Define a time interval to spawn enemies. Continuously compare the current time with the time when the next enemy must appear. When the time comes, spawn an enemy and set the time the next enemy must spawn:
class Game(object):
# [...]
def Run(self):
self.next_enemy_time = 0
self.enemy_time_interval = 1000 # 1000 milliseconds == 1 second
# Game Loop
self.playing = True
while self.playing:
current_time = pygame.time.get_ticks()
if current_time > self.next_enemy_time:
self.next_enemy_time += self.enemy_time_interval
new_enemy = Enemy(700, 517, 50, 50)
self.all_sprites.add(new_enemy)
self.ene.add(new_enemy)
self.clock.tick(FPS)
self.Events()
self.Update()
self.Draw()
self.score()

OOP Pygame platform game: controlling and moving a square on a screen

import pygame
import random
import math
import sys
screenWidth = 1200
screenHeight = 600
class Hero:
def __init__(self, pos):
self.pos = pos
self.width = 30
self.height = 30
self.color = (0, 0, 0)
self.dirX = 0
self.dirY = 0
def move(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.dirX = 1
elif event.key == pygame.K_LEFT:
self.dirX = -1
def draw(self, display):
x = self.pos[0]
y = self.pos[1]
pygame.draw.rect(display, self.color, (x + self.dirX, y + self.dirY, self.width, self.height))
print(self.pos, self.dirX, self.dirY)
def jump(self):
pass
def die(self):
pass
class Enemy:
pass
class Background:
pass
class Obstacles:
pass
class Camera:
pass
def score():
pass
def create(w, h):
display = pygame.display.set_mode((w, h))
display.fill((255, 255, 255))
#create background
#create Obstacles
#create Hero
heroOne = Hero([150, 450])
heroOne.move()
heroOne.draw(display)
#create Enemy
pygame.display.update()
def main():
pygame.init()
clock = pygame.time.Clock()
running = True
while running:
clock.tick(300)
create(screenWidth, screenHeight)
main()
Hi, I am making an OOP Game using Pygame in which a square would be controlled by the user and move along a floor, jump over obstacles and other enemy squares.
The way I want it to work:
When I press K_LEFT, dirX = 1 it will add to the x-coordinate of the pos and hence the x-position of the square will be updated and the square will begin to slide towards the right. When I press dir = -1and square will move to the left.
The way it is working:
No
I think the problem is the pos of the main cube does not seem to update and the dirX updates from 0 to 1 and goes back to 0.
I guess changing the values of the variables under the __init__() function is done as I am doing it or perhaps it is completely wrong.
Is this any way to make my code work the way I am trying to do it or is it completely a wrong way and there is some other way?
I am learning OOP and python, any additional advice or links regarding the best practices, relating to this code, would be highly appreciated.
Thank you.
First of all you've to invoke move in the main application loop:
def main():
pygame.init()
display = pygame.display.set_mode((screenWidth, screenHeight))
clock = pygame.time.Clock()
heroOne = Hero([150, 450])
running = True
while running:
clock.tick(300)
display.fill((255, 255, 255))
heroOne.move()
heroOne.draw(display)
pygame.display.update()
You have to change the position of the player by self.dirX and self.dirY, in every frame:
class Hero:
# [...]
def move(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.dirX = 1
elif event.key == pygame.K_LEFT:
self.dirX = -1
new_x = self.pos[0] + self.dirX
new_y = self.pos[1] + self.dirY
self.pos = [new_x , new_y]
def draw(self, display):
pygame.draw.rect(display, self.color, (*self.pos, self.width, self.height))
If you wan to move the rectangle, just when a key is pressed, then I recommend to use pygame.key.get_pressed rather than the KEYDOWN event:
class Hero:
# [...]
def move(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.pos[0] -= 1
if keys[pygame.K_RIGHT]:
self.pos[0] += 1
if keys[pygame.K_UP]:
self.pos[1] -= 1
if keys[pygame.K_DOWN]:
self.pos[1] += 1
Complete code:
import pygame
import random
import math
import sys
screenWidth = 1200
screenHeight = 600
class Hero:
def __init__(self, pos):
self.pos = pos
self.width = 30
self.height = 30
self.color = (0, 0, 0)
self.dirX = 0
self.dirY = 0
def move(self, events):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.pos[0] -= 1
if keys[pygame.K_RIGHT]:
self.pos[0] += 1
if keys[pygame.K_UP]:
self.pos[1] -= 1
if keys[pygame.K_DOWN]:
self.pos[1] += 1
def draw(self, display):
pygame.draw.rect(display, self.color, (*self.pos, self.width, self.height))
def jump(self):
pass
def die(self):
pass
class Enemy:
pass
class Background:
pass
class Obstacles:
pass
class Camera:
pass
def score():
pass
def main():
pygame.init()
display = pygame.display.set_mode((screenWidth, screenHeight))
clock = pygame.time.Clock()
heroOne = Hero([150, 450])
running = True
while running:
clock.tick(300)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
heroOne.move(events)
display.fill((255, 255, 255))
heroOne.draw(display)
pygame.display.update()
main()
In your create function you are creating new instance of the Hero each time its being called.
Instead, init heroOne in the main, and pass it as an argument so you can use it:
def main():
pygame.init()
heroOne = Hero([150, 450])
clock = pygame.time.Clock()
running = True
while running:
clock.tick(30)
create(screenWidth, screenHeight, heroOne)
Also add increment in the move method:
self.dirX += 1
and:
self.dirX -= 1
Now the object will move by one on each keypress.
And if you want continuous movement you should put some flag, e.g. if it is True +=1 and "False" -=1 and key presses will change the flag state.

How to add a Collision in Pygame

i'm making a game about a car trying not to collide with pedestrian car.
I'm trying to add a collision to the user_car(aka Player class) with enemy(aka pedestrian_cars class), but i'm not exactly sure where(while loop?) and how to do it. Some variables maybe be bad but I will fix them later.
My program:
import pygame, random, math, sys
from pygame.locals import *
class Player(pygame.sprite.Sprite):
def __init__(self, starty):
pygame.sprite.Sprite.__init__(self)
# Images
self.aliveImage = pygame.image.load("playercar.png").convert_alpha()
#self.deadImage = pygame.image.load("data/PlayerExplode.png").convert_alpha()
self.image = self.aliveImage
self.rect = self.image.get_rect()
self.rect.x = 200
self.rect.y = starty - self.rect.height
self.speed = 7
self.dead = False
# Explode if you get hit, lose a life
def explode(self):
if not self.dead:
self.dead = True
self.image = self.deadImage
pygame.mixer.stop()
self.channel = self.explodeSound.play()
game.playerShots.empty()
game.enemyShots.empty()
game.wave.mship.empty()
game.lives.update(-1)
class pedestrian_cars(pygame.sprite.Sprite):
def __init__(self, starty,startx):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("pedcar.png").convert_alpha()
self.rect = self.image.get_rect()
self.rect.y = starty - self.rect.height
self.rect.x = startx - self.rect.width
self.delta_y = 5 # 5
self.gravity = .5 #.5
self.has_spawned = False
def update(self):
self.rect.y += self.delta_y
def spawn(self):
if self.rect.y == 480 or self.has_spawned == False:
self.has_spawned = True
self.rect.x = random.randint(60,300)
self.rect.y = -10
def main():
""" Set up the game and run the main game loop """
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init() # prepare the pygame module for use
surfaceSz = 480 # Desired physical surface size, in pixels.
# Create surface of (width, height), and its window.
main_surface = pygame.display.set_mode((surfaceSz, surfaceSz))
#SPRITES###############################################################
user_car = Player(450)
enemy = pedestrian_cars(10,200)
#SPRITES################################################################
background_image = pygame.image.load("background2.png")
all_sprites = pygame.sprite.Group()
user_car.add(all_sprites)
enemy.add(all_sprites)
clock = pygame.time.Clock()
b1 = "background2.png"
back = pygame.image.load(b1).convert()
back2 = pygame.image.load(b1).convert()
y = 0
screenWidth = 600
screenHeight = 480
#Sound/Music#####################################
pygame.mixer.music.load("stilldre.wav")
pygame.mixer.music.play(-1)
#-################################################
while True:
ev = pygame.event.poll() # look for any event
if ev.type == pygame.QUIT: # window close button clicked?
break # ... leave game loop
sys.exit()
if not user_car.dead:
# Move the player
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
user_car.rect.x = max(user_car.rect.x - user_car.speed, 116-user_car.rect.width)
elif keys[pygame.K_RIGHT]:
user_car.rect.x = min(user_car.rect.x + user_car.speed, 395-user_car.rect.width)
else:
# Go back to playing after the explosion sound finishes
if not self.channel.get_busy():
self.image = self.aliveImage
self.dead = False
self.rect.x = 200
# Update your game objects and data structures here...
all_sprites.update()
enemy.spawn()
main_surface.fill((0,200,255))
main_surface.blit(background_image, (0, 0))
main_surface.blit(back, (0,y))
main_surface.blit(back2,(0,y-screenHeight))
y = y + 8
if y == screenWidth:
y = 0
## if enemy.alive.x ==
## msElapsed = clock.tick(100)
## pygame.display.flip()
all_sprites.draw(main_surface)
# Now the surface is ready, tell pygame to display it!
pygame.display.flip()
clock.tick(200)
msElapsed = clock.tick(100)
pygame.quit() # once we leave the loop, close the window.
main()
You can simply check if the rects of your objects overlap with colliderect:
while True:
...
if user_car.rect.colliderect(enemy.rect):
do_something()
...

Categories