Collision in constantly true? - python

I am making a little game with a car which the playe moves and cars will be coming down and you have to dodge them. For some reason collision is always true and I can't figure it out. I tried reformatting the Rect's and making that whole system better but that doesn't seem to work. The Rect values are in the player class and the car class. Thanks.
import time, pygame, random
import math
pygame.init()
#First Variables
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREEN = (100, 255, 100)
ORANGE = (255, 140, 0)
YELLOW = (155, 135, 12)
white = (255, 255, 255)
GOLD = (255, 215, 0)
screenwidth = 500
screenheight = 500
Lines = True
Space = True
color = random.sample(range(250), 3)
doris = []
i = []
x = 247
y = - 20
y1 = 40
y2 = 100
y3 = 160
y4 = 220
y5 = 280
y6 = 340
y7 = 400
y8 = 460
#Display and caption
win = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption('Lil cary')
clock = pygame.time.Clock()
#Load in images
bkg = pygame.image.load('BG.jpg')
#Actual player class
class player():
def __init__(self):
self.x = 200
self.y = 390
self.width = 50
self.height = 100
self.color = (12, 124, 134)
self.vel = 5
self.grassdamage = 0
self.image = pygame.Surface([self.width, self.height], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, self.width, self.height))
self.rect = self.image.get_rect()
self.damage1 = False
self.damage2 = False
self.damage3 = False
self.damage4 = False
self.damage5 = False
self.damage6 = False
self.damage7 = False
self.damage8 = False
self.dead = False
def draw (self, win):
#pygame.draw.rect(win, (self.color), (self.x, self.y, self.width, self.height))
win.blit(self.image, [self.x, self.y])
def moveback(self):
if self.y < 390 and self.y >= 0:
self.y += 10
def grass(self):
if player.x > -10 and player.x < 150:
self.grassdamage += 1
self.vel = 3
elif player.x > 300 and player.x < 500:
self.vel =3
self.grassdamage += 1
else:
self.vel = 5
def grasshealth(self):
if self.grassdamage == 100:
self.damage1 = True
print ("First bar filled ")
elif self.grassdamage == 200:
self.damage2 = True
print ("doing this")
elif self.grassdamage == 300:
self.damage3 = True
elif self.grassdamage == 400:
self.damage4 = True
elif self.grassdamage == 500:
self.damage5 = True
elif self.grassdamage == 600:
self.damage6 = True
elif self.grassdamage == 600:
self.damage6 = True
elif self.grassdamage == 700:
self.damage7 = True
elif self.grassdamage == 800:
self.damage8 = True
self.dead = True
def death(self):
if self.dead == True:
exit()
#Text Setup
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
#Drawing damage bar
def drawbar ():
if player.damage1 == True:
pygame.draw.rect(win, (GOLD), (50, 50, 25, 25))
if player.damage2 == True:
pygame.draw.rect(win, (GOLD), (50, 75, 25, 25))
if player.damage3 == True:
pygame.draw.rect(win, (GOLD), (50, 100, 25, 25))
if player.damage4 == True:
pygame.draw.rect(win, (GOLD), (50, 125, 25, 25))
if player.damage5 == True:
pygame.draw.rect(win, (GOLD), (50, 150, 25, 25))
if player.damage6 == True:
pygame.draw.rect(win, (GOLD), (50, 175, 25, 25))
if player.damage7 == True:
pygame.draw.rect(win, (GOLD), (50, 200, 25, 25))
if player.damage8 == True:
pygame.draw.rect(win, (GOLD), (50, 225, 25, 25))
pygame.draw.rect(win, (0,0,0), (50, 50, 25, 200), 3)
Text = pygame.font.Font('freesansbold.ttf', 20)
TextSurf, TextRect = text_objects("Damage", Text)
TextRect.center = ((65), (30))
win.blit(TextSurf, TextRect)
#Seting up the cars class
class car():
def __init__(self):
self.x = 175
self.y = -100
self.width = 50
self.height = 100
self.color = random.sample(range(250), 3)
self.image = pygame.Surface([self.width, self.height], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, self.width, self.height))
self.rect = self.image.get_rect()
self.carvel = random.randrange(5, 10)
def draw(self, win):
#pygame.draw.rect(win,(self.color),self.rect)
win.blit(self.image, (self.x,self.y))
def move(self):
if self.y < 530:
self.y += self.carvel
else:
self.y = -100
self.color = random.sample(range(250), 3)
print(self.color)
self.carvel = random.randrange(6, 10)
def collision_check(self, another_object):
if self.rect.colliderect(another_object):
print('collison')
#Putting variables to the classes
player = player()
car = car()
#Main drawing function
def redrawgamewindow():
win.blit(bkg, (0, 0))
pygame.draw.rect(win, (0, 0, 0), (150, 0, 200, 500))
pygame.draw.rect(win, (255, 255, 255), (x, (y), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y1), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y2), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y3), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y4), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y5), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y6), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y7), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y8), 10, 30))
player.draw(win)
car.draw(win)
drawbar()
pygame.display.update()
#MAINLOOP
run = True
while run:
#Making background and FPS
clock.tick(80)
#Quiting Funciton
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
#Scrolling the lines
if Lines:
y += player.vel
y1 += player.vel
y2 += player.vel
y3 += player.vel
y4 += player.vel
y5 += player.vel
y6 += player.vel
y7 += player.vel
y8 += player.vel
if Lines:
if y >= 500:
y = -40
if y1 >= 500:
y1 = -40
if y2 >= 500:
y2 = -40
if y3 >= 500:
y3 = -40
if y4 >= 500:
y4 = -40
if y5 >= 500:
y5 = -40
if y6 >= 500:
y6 = -40
if y7 >= 500:
y7 = -40
if y8 >= 500:
y8 = -40
#User input
keys = pygame.key.get_pressed()
#Boost controller
if keys[pygame.K_SPACE]:
start_time = time.time()
if player.y > 200:
player.y -= 9
Space = True
else:
player.moveback()
end_time = time.time()
#Left movement
if keys[pygame.K_LEFT] and player.x > 150:
player.x -= 5
if keys [pygame.K_LEFT] and player.x <= 150:
if player.x > 0:
player.x -=5
#Right movement
if keys[pygame.K_RIGHT] and player.x < 300:
player.x += 5
if keys[pygame.K_RIGHT]and player.x >= 300:
if player.x < 500 - player.width:
player.x += 5
#Car reset
#Grass and grass damage
player.grass()
player.grasshealth()
player.death()
car.collision_check(player.rect)
car.move()
#MAIN DRAW RECALL
redrawgamewindow()

self.rect.x and self.rect.y is never set and constantly stays 0. Delete self.x, self.y, self.width and self.height and use the attributes of the pygame.Rect object (self.rect.x, self.rect.y, and self.rect.widht and self.rect.height) instead.
In class player:
class player():
def __init__(self):
self.color = (12, 124, 134)
self.vel = 5
self.grassdamage = 0
self.image = pygame.Surface([50, 100], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, 50, 100))
self.rect = self.image.get_rect(center = (200, 390))
self.damage1 = False
self.damage2 = False
self.damage3 = False
self.damage4 = False
self.damage5 = False
self.damage6 = False
self.damage7 = False
self.damage8 = False
self.dead = False
def draw (self, win):
#pygame.draw.rect(win, (self.color), (self.x, self.y, self.width, self.height))
win.blit(self.image, self.rect.topleft)
def moveback(self):
if self.rect.y < 390 and self.rect.y >= 0:
self.rect.y += 10
def grass(self):
if self.rect.x > -10 and self.rect.x < 150:
self.grassdamage += 1
self.vel = 3
elif self.rect.x > 300 and self.rect.x < 500:
self.vel =3
self.grassdamage += 1
else:
self.vel = 5
# [...]
In class car:
class car():
def __init__(self):
self.color = random.sample(range(250), 3)
self.image = pygame.Surface([50, 100], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, 50, 100))
self.rect = self.image.get_rect(topleft = (175, -100))
self.carvel = random.randrange(5, 10)
def draw(self, win):
#pygame.draw.rect(win,(self.color),self.rect)
win.blit(self.image, self.rect.topleft)
def move(self):
if self.rect.y < 530:
self.rect.y += self.carvel
else:
self.rect.y = -100
self.color = random.sample(range(250), 3)
print(self.color)
self.carvel = random.randrange(6, 10)
def collision_check(self, another_object):
if self.rect.colliderect(another_object):
print('collison')
And in the main application loop:
run = True
while run:
# [...]
#User input
keys = pygame.key.get_pressed()
#Boost controller
if keys[pygame.K_SPACE]:
start_time = time.time()
if player.rect.y > 200:
player.rect.y -= 9
Space = True
else:
player.moveback()
end_time = time.time()
#Left movement
if keys[pygame.K_LEFT] and player.rect.x > 150:
player.rect.x -= 5
if keys [pygame.K_LEFT] and player.rect.x <= 150:
if player.rect.x > 0:
player.rect.x -=5
#Right movement
if keys[pygame.K_RIGHT] and player.rect.x < 300:
player.rect.x += 5
if keys[pygame.K_RIGHT]and player.rect.x >= 300:
if player.rect.rect.x < 500 - player.rect.width:
player.rect.x += 5
# [...]

Related

Pygame program stopping/crashing without any error logged

As a beginner im trying to create flappy bird to learn the basics of python and pygame. But when i run this code and click the button that is created the code just stops and python becomes not responsive. Does any one know why?
import pygame
import math
import random
import pyautogui as pg
pygame.init()
screenWidth, screenHeight = pg.size()
gameDisplay = pygame.display.set_mode((screenWidth, screenHeight), pygame.FULLSCREEN)
pygame.display.set_caption("Flappy by Tallik")
time = pygame.time.Clock()
crashed = False
bg = (0, 0, 0)
textSize = 32
font = pygame.font.Font("freesansbold.ttf", textSize)
buttonClicked = [0, 0]
mainGame = False
titleScreen = True
settings = False
changeBird = False
dead = False
phase = 1
def buttonFunc(x, y, width, height, color1, color2, text, textColor, textColor2, buttonNum, dissaperance):
global buttonClicked
mouseClick = pygame.mouse.get_pressed()
mouseX, mouseY = pygame.mouse.get_pos()
buttonText = font.render(str(text), True, textColor)
buttonText2 = font.render(str(text), True, textColor2)
textX = x + 10
textY = y + (height//3)
buttonClicked = [0, buttonNum]
if mouseX >= x and mouseX <= x + width and mouseY >= y and mouseY <= y + height:
pygame.draw.rect(gameDisplay, (color2), (x, y, width, height))
gameDisplay.blit(buttonText2, (textX, textY))
if mouseClick[0] == True:
buttonClicked[0] = 1
if dissaperance == False:
pygame.draw.rect(gameDisplay, (color2), (x, y, width, height))
gameDisplay.blit(buttonText2, (textX, textY))
buttonClicked[0] = 1
else:
gameDisplay.fill(bg)
else:
pygame.draw.rect(gameDisplay, (color1), (x, y, width, height))
gameDisplay.blit(buttonText, (textX, textY))
class bird(object):
def __init__(self, birdVelMultiplier, skin, width, height):
self.birdVelMultiplier = birdVelMultiplier
self.skin = skin
self.grav = -1
self.height = height
self.width = width
self.y = screenHeight//2
self.x = screenWidth//30
self.vel = screenHeight//100
self.jumps = 0
self.minVel = -20
self.maxVel = 20
def jump(self):
if keys[pygame.K_SPACE] and self.jumps == 0:
self.vel = -15
self.jumps += 1
if keys[pygame.K_UP] and self.jumps == 0:
self.vel = -15
self.jumps += 1
if not keys[pygame.K_UP] and not keys[pygame.K_SPACE]:
self.jumps = 0
def drawToGame(self, gameDisplay):
if self.y + self.height <= screenHeight:
if self.y >= 0:
if self.vel < self.maxVel and self.vel > self.minVel:
self.vel -= self.grav
self.y += self.vel
else:
if abs(self.vel)/self.vel == 1:
self.vel = self.maxVel
self.vel -= self.grav
self.y += self.vel
else:
self.vel = self.minVel
self.vel -= self.grav
self.y += self.vel
else:
self.y = 0
self.vel = 1
else:
self.y = screenHeight//2
self.vel = 0
pygame.draw.rect(gameDisplay, (0, 0, 255), (self.x, self.y, self.width, self.height))
class obstacle(object):
def __init__(self, speedMultiplier, width):
self.speedMultiplier = speedMultiplier
self.width = width
self.ranHeight = random.randrange(50, screenHeight - (screenHeight//16)*4)
self.ranHeight2 = (screenHeight - self.ranHeight) - 150
def spawn(self):
print(1)
def drawToSurface(self, gameDisplay):
print(3)
bird1 = bird(1, 1, 60, 60)
pipe = obstacle(1, 130)
sB = bird1
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
gameDisplay.fill(bg)
keys = pygame.key.get_pressed()
if buttonClicked == [1, 1]:
phase = 4
if phase == 1:
buttonFunc(screenWidth//2, screenHeight//4, screenWidth//18, screenHeight//20, (115, 115, 115), (85, 85, 85), "Start!", (0, 0, 0), (0, 0, 0), 1, True)
elif phase == 2:
print("?")
elif phase == 3:
print("??")
elif phase == 4:
while dead == False:
sB.jump()
sB.drawToGame(gameDisplay)
pygame.display.update()
time.tick(30)
pygame.quit()
quit()
To specify: after i have pressed the button created by buttFunc and the phase variable gets to 4 the program just stops and no eroor message is recieved. Also when closing the program the IDLE shell says the program is still running. I posted all the code because i dont know what made it break.
The program does not "crash", you just have an infinite loop. You do not need a loop that controls the game in the application loop. The application loop is continuously executed. Remove while dead == False::
while not crashed and not dead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
gameDisplay.fill(bg)
keys = pygame.key.get_pressed()
if buttonClicked == [1, 1]:
phase = 4
if phase == 1:
buttonFunc(screenWidth//2, screenHeight//4, screenWidth//18, screenHeight//20, (115, 115, 115), (85, 85, 85), "Start!", (0, 0, 0), (0, 0, 0), 1, True)
elif phase == 2:
print("?")
elif phase == 3:
print("??")
elif phase == 4:
sB.jump()
sB.drawToGame(gameDisplay)
pygame.display.update()
time.tick(30)

How would I go about deleting a sprite? [duplicate]

This question already has answers here:
how to make image/images disappear in pygame?
(1 answer)
Do not display removed sprites, Pygame
(1 answer)
Closed 2 years ago.
So the problem is an trying to get my sprite to disappear once the health bar goes 0 but I can’t seem to that the most I can do is make him invisible but I am trying to delete my sprite not make it invisible
import pygame import sys
pygame.init()#We always need to initalize our pygame IN EVERY PROJECT/FILE
win = pygame.display.set_mode((500, 480))# Here win is representing "window" for our screen which we have set at 500 by 480
pygame.display.set_caption("Dragon Ball Z Mini-game")#We are giving our Window/Screen a name
walkRight = [pygame.image.load('image/young_goku_right_image0 - t.png'), pygame.image.load('image/young_goku_right_image1 - t.png'), pygame.image.load('image/young_goku_right_image2 - t.png'), pygame.image.load('image/young_goku_right_image3 - t.png'), pygame.image.load('image/young_goku_right_image4 - t.png')] walkLeft = [pygame.image.load('image/young_goku_left_image0 - t.png'), pygame.image.load('image/young_goku_left_image1 - t.png'), pygame.image.load('image/young_goku_left_image2 - t.png'), pygame.image.load('image/young_goku_left_image3 - t.png'), pygame.image.load('image/young_goku_left_image4 - t.png')] bg = pygame.image.load('image/bg2.jpg') char = pygame.image.load('image/young_goku - standing - t.png')
clock = pygame.time.Clock()
bulletSound = pygame.mixer.Sound("image/kiblast.wav") hitSound = pygame.mixer.Sound("image/Bomb+1.wav")
#bulletSound.play() music = pygame.mixer.music.load("image/Dragon Ball Z - Rock The Dragon.mp3") pygame.mixer.music.play(-1)
score = 0
class player(object): def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 5
self.isJump = False
self.left = False
self.right = False
self.walkCount = 0
self.jumpCount = 10
self.standing = True
self.hitbox = (self.x + 17, self.y + 11, 29, 52)
def draw(self, win):
font2 = pygame.font.SysFont("Papyrus", 45)
text2 = font2.render("DBZ Adventure!", 1, (255, 50, 25))
win.blit(text2, (120 - (text2.get_width() / 2), 15))
#pygame.display.flip()
if self.walkCount + 1 >= 10:
self.walkCount = 0
if not (self.standing):
if self.left:
win.blit(walkLeft[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
elif self.right:
win.blit(walkRight[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
else:
if self.right:
win.blit(walkRight[0], (self.x, self.y))
else:
win.blit(walkLeft[0], (self.x, self.y))
self.hitbox = (self.x + 17, self.y + 11, 29, 52)
if keys[pygame.K_a]:
if self.left:
ki_stance_left = pygame.image.load("image/goku-ki_left.png")
win.blit(ki_stance_left, (self.x, self.y))
elif self.right:
ki_stance = pygame.image.load("image/goku-ki.png")
win.blit(ki_stance, (self.x, self.y))
if keys[pygame.K_SPACE]:
if self.left:#needed to put self.left and self the right
ki_stance_left = pygame.image.load("image/goku-ki_left.png")
win.blit(ki_stance_left, (self.x, self.y))
elif self.right:
ki_stance = pygame.image.load("image/goku-ki.png")
win.blit(ki_stance, (self.x, self.y))
pygame.display.flip()
def hit(self):
self.isJump = False
self.jumpCount = 10
self.x = 100
self.y = 410
self.walkCount = 0
font1 = pygame.font.SysFont('comicsans', 100)
text = font1.render('-5', 1, (255, 0, 0))
win.blit(text, (250 - (text.get_width() / 2), 200))
pygame.display.update()
i = 0
while i < 200:
pygame.time.delay(10)
i += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
i = 201
pygame.quit()
class projectile(object): def __init__(self, x, y, radius, color, facing):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.facing = facing
self.vel = 8 * facing
def draw(self, win):
ki = pygame.image.load("image/ki.png")
win.blit(ki, (self.x, self.y))
ki_stance = pygame.image.load("image/goku-ki.png")
win.blit(ki, (self.x, self.y))
pygame.draw.circle(win, (255,255,0), (self.x, self.y), self.radius) """ def draw2(self, win):
ki2 = pygame.image.load("image/b4.png")
win.blit(ki2, (self.x, self.y))
ki_stance = pygame.image.load("image/goku-ki.png")
win.blit(ki2, (self.x, self.y))
pygame.draw.rect(win, (255, 255, 0), (self.x, self.y), self.radius) """
class projectile2(): def __init__(self, x, y, radius, color, facing):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.facing = facing
self.vel = 8 * facing
def draw(self, win):
ki = pygame.image.load("image/b4.png")
win.blit(ki, (self.x, self.y))
ki_stance = pygame.image.load("image/goku-ki.png")
win.blit(ki, (self.x, self.y))
#pygame.draw.circle(win, (0,0,139), (self.x, self.y), self.radius)
class enemy(object): walkRight = [pygame.image.load("image/R1E.png"), pygame.image.load("image/R2E.png"),
pygame.image.load("image/R3E.png"), pygame.image.load("image/R4E.png"),
pygame.image.load("image/R5E.png"), pygame.image.load("image/R6E.png"),
pygame.image.load("image/R7E.png"), pygame.image.load("image/R8E.png"),
pygame.image.load("image/R9E.png"), pygame.image.load("image/R10E.png"),
pygame.image.load("image/R11E.png")] walkLeft = [pygame.image.load("image/L1E.png"), pygame.image.load("image/L2E.png"),
pygame.image.load("image/L3E.png"), pygame.image.load("image/L4E.png"),
pygame.image.load("image/L5E.png"), pygame.image.load("image/L6E.png"),
pygame.image.load("image/L7E.png"), pygame.image.load("image/L8E.png"),
pygame.image.load("image/L9E.png"), pygame.image.load("image/L10E.png"),
pygame.image.load("image/L11E.png")]
def __init__(self, x, y, width, height, end):
self.x = x
self.y = y
self.width = width
self.height = height
self.end = end
self.path = [self.x, self.end]
self.walkCount = 0
self.vel = 3
self.hitbox = (self.x + 17, self.y + 2, 31, 57)
self.health = 10
self.visible = True
def draw(self, win):
self.move()
if self.visible:
if self.walkCount + 1 >= 33:
self.walkCount = 0
if self.vel > 0:
win.blit(self.walkRight[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
else:
win.blit(self.walkLeft[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
pygame.draw.rect(win, (255, 0, 0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))
pygame.draw.rect(win, (0, 128, 0), (self.hitbox[0], self.hitbox[1] - 20, 50 - (5 * (10 - self.health)), 10))
self.hitbox = (self.x + 17, self.y + 2, 31, 57)
# pygame.draw.rect(win, (255,0,0), self.hitbox,2)
def move(self):
if self.vel > 0:
if self.x + self.vel < self.path[1]:
self.x += self.vel
else:
self.vel = self.vel * -1
self.walkCount = 0
else:
if self.x - self.vel > self.path[0]:
self.x += self.vel
else:
self.vel = self.vel * -1
self.walkCount = 0
Here’s where I can keep on trying to delete my sprite but it does not seem to work? The most I can do is just make it invisible but it does not go away permanently.
def hit(self):
hit = enemy
if self.health > 0:
self.health -= 1
else:
self.visible = False
font2 = pygame.font.SysFont("Papyrus", 45)
text2 = font2.render("You won!", 5, (45, 50, 45))
win.blit(text2, (95 - (text2.get_width() / 3), 45))
pygame.display.flip()
print('hit')
class enemy2(): walkRight = [pygame.image.load("image/enemy-sprite-standing-T.gif"), pygame.image.load("image/enemy-sprite-moving_T.gif"), pygame.image.load("image/enemy-sprite-moving_T.gif"), pygame.image.load("image/enemy-sprite-move_right-T.gif")] walkLeft = [pygame.image.load("image/enemy-sprite-standing-T.gif"), pygame.image.load("image/enemy-sprite - moving_left-T.gif"), pygame.image.load("image/enemy-sprite - moving_left-T.gif"), pygame.image.load("image/enemy-sprite - moving_left2-T.gif")] def
__init__(self, x, y, width, height, end):
self.x = x
self.y = y
self.width = width
self.height = height
self.end = end
self.path = [self.x, self.end]
self.walkcount = 0
self.vel = 3
self.hitbox = (self.x + 20, self.y, 28, 60)
self.health = 10
self.visible = True
def draw(self, win):
self.move()
if self.visible:
if self.walkcount + 0 >= 10:
self.walkcount = 0
if self.vel > 0:
win.blit(self.walkRight[self.walkcount // 3], (self.x, self.y))
self.walkcount += 1
else:
win.blit(self.walkLeft[self.walkcount // 3], (self.x, self.y))
self.walkcount += 1
pygame.draw.rect(win, (255, 0, 0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))
pygame.draw.rect(win, (0, 128, 0), (self.hitbox[0], self.hitbox[1] - 20, 50 - (5 * (10 - self.health)), 10))
self.hitbox = (self.x + 20, self.y, 28, 60)
def move(self):
if self.vel > 0:
if self.x + self.vel < self.path[1]:
self.x += self.vel
else:
self.vel = self.vel * -1
self.walkcount = 0
else:
if self.x - self.vel > self.path[0]:
self.x += self.vel
else:
self.vel = self.vel * -1
self.walkcount = 0
def hit(self):
if self.health > 0:
self.health -= 1
else:
self.visible = False
self.visible = False
font2 = pygame.font.SysFont("Papyrus", 45)
text2 = font2.render("You won!", 5, (45, 50, 45))
win.blit(text2, (95 - (text2.get_width() / 3), 45))
pygame.display.flip()
print("Hit!!")
pass
def redrawGameWindow(): win.blit(bg, (0, 0)) text = font.render('Score: ' + str(score), 1, (0, 0, 0)) win.blit(text, (390, 5)) man.draw(win) goblin.draw(win) goblin2.draw(win) for bullet in bullets:
bullet.draw(win)
pygame.display.update()
# mainloop font = pygame.font.SysFont("comicsans", 30, True, True) man = player(200, 420, 64, 64) goblin = enemy(50, 410, 64, 64, 450) goblin2 = enemy2(250, 410, 64, 64, 450) shootloop = 0 bullets = [] run
= True while run: clock.tick(27) if goblin.visible == True:
if man.hitbox[1] < goblin.hitbox[1] + goblin.hitbox[3] and man.hitbox[1] + man.hitbox[3] > goblin.hitbox[1]:
if man.hitbox[0] + man.hitbox[2] > goblin.hitbox[0] and man.hitbox[0] < goblin.hitbox[0] + goblin.hitbox[2]:
man.hit()
score -= 5
print("Hurt")
if goblin2.visible == True:
if man.hitbox[1] < goblin2.hitbox[1] + goblin2.hitbox[3] and man.hitbox[1] + man.hitbox[3] > goblin2.hitbox[1]:
if man.hitbox[0] + man.hitbox[2] > goblin2.hitbox[0] and man.hitbox[0] < goblin2.hitbox[0] + goblin2.hitbox[2]:
man.hit()
score -= 5
print("Hurt")
if shootloop > 0:
shootloop += 1 if shootloop > 3:
shootloop = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
#pygame.quit()
sys.exit()
run = False
for bullet in bullets:
if bullet.y - bullet.radius < goblin.hitbox[1] + goblin.hitbox[3] and bullet.y + bullet.radius > goblin.hitbox[1]:
if bullet.x + bullet.radius > goblin.hitbox[0] and bullet.x - bullet.radius < goblin.hitbox[0] + goblin.hitbox[2]:
#hitSound.play()
goblin.hit()
score += 1
#bullets.pop(bullets.index(bullet))
for bullet in bullets:
if bullet.y - bullet.radius < goblin2.hitbox[1] + goblin2.hitbox[3] and bullet.y + bullet.radius > goblin2.hitbox[1]:
if bullet.x + bullet.radius > goblin2.hitbox[0] and bullet.x - bullet.radius < goblin2.hitbox[0] + goblin2.hitbox[2]:
#hitSound.play()
goblin2.hit()
score += 1
#bullets.pop(bullets.index(bullet))
if bullet.x < 500 and bullet.x > 0:
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet))
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and shootloop == 0:
bulletSound.play()
if man.left:
facing = -1
else:
facing = 1
if len(bullets) < 5:
bullets.append(projectile(round(man.x + man.width // 3), round(man.y + man.height // 3), 6, (0, 0, 0), facing))
shootloop = 1
if keys[pygame.K_a] and shootloop == 0:
bulletSound.play()
if man.left:
facing = -1
else:
facing = 1
if len(bullets) < 5:
bullets.append(projectile2(round(man.x + man.width // 3), round(man.y + man.height // 3), 12, (0, 0, 0), facing))
shootloop = 1
if keys[pygame.K_LEFT] and man.x > man.vel:
man.x -= man.vel
man.left = True
man.right = False
man.standing = False elif keys[pygame.K_RIGHT] and man.x < 500 - man.width - man.vel:
man.x += man.vel
man.right = True
man.left = False
man.standing = False else:
man.standing = True
man.walkCount = 0
if not (man.isJump):
if keys[pygame.K_UP]:
man.isJump = True
man.right = False
man.left = False
man.walkCount = 0 else:
if man.jumpCount >= -10:
neg = 1
if man.jumpCount < 0:
neg = -1
man.y -= (man.jumpCount ** 2) * 0.5 * neg
man.jumpCount -= 1
else:
man.isJump = False
man.jumpCount = 10
redrawGameWindow()
pygame.quit()
In order to move a created image off of the screen you can do either one of the following solutions.
1. Move the image off of the screen.
An example of moving a sprite off of a screen is as follows:
someImg = pygame.image.load("coolWater.png")
screen.blit(someImg, (int(someXValueOffScreen), int(someYValueOffScreen))
2. Make the image transparent
Here's an example of this:
someImg = pygame.image.load("coolWater.png")
someImg.image.fill((0,0,0,0)) #Makes the image transparent. The last parameter is the alpha value. An alpha value of 0 makes it transparent. The first 3 zeros is the RGB value
Quick note: You should format your code in this post correctly with encapsulating your code with these three characters " ``` ".

Having trouble creating multiple enemies for my pygame

I am a first time coding student in grade 11 and I am trying to create multiple instances of an enemy class in python for my game. Below is my pygame code.
i am having trouble seeing what needs to be changed. Lines 180=183 are where I am trying to create 3 instances of my "enemy" but when I run my code it just create one
import pygame
import random
pygame.init()
window = pygame.display.set_mode((800, 480))
pygame.display.set_caption("Who Killed M?")
walkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'),
pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png')]
walkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'),
pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png')]
backGround = pygame.image.load('backGround.png')
char = pygame.image.load('standing.png')
clock = pygame.time.Clock()
bulletSound = pygame.mixer.Sound('bullet.wav')
hitSound = pygame.mixer.Sound('hit.wav')
music = pygame.mixer.music.load('music.mp3')
pygame.mixer.music.play(-1)
score = 0
goblincount = 3
class player(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 8
self.isJump = False
self.left = False
self.right = False
self.walkCount = 0
self.jumpCount = 10
self.standing = True
self.hitBox = (self.x + 17, self.y + 11, 29, 52)
def draw(self, window):
if self.walkCount + 1 >= 27:
self.walkCount = 0
if not self.standing:
if self.left:
window.blit(walkLeft[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
elif self.right:
window.blit(walkRight[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
else:
if self.right:
window.blit(walkRight[0], (self.x, self.y))
else:
window.blit(walkLeft[0], (self.x, self.y))
self.hitBox = (self.x + 17, self.y + 11, 29, 52)
pygame.draw.rect(window, (255,0,0), self.hitBox,2)
def hit(self):
self.isJump = False
self.jumpCount = 10
self.x = 100
self.y = 415
self.walkCount = 0
font1 = pygame.font.SysFont('comicsans', 200)
text = font1.render('-2', 1, (255, 0, 0))
window.blit(text, (400 - (text.get_width() / 2), 200))
pygame.display.update()
i = 0
while i < 200:
pygame.time.delay(10)
i += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
i = 201
pygame.quit()
class projectile(object):
def __init__(self, x, y, radius, colour, facing):
self.x = x
self.y = y
self.radius = radius
self.colour = colour
self.facing = facing
self.vel = 8 * facing
def draw(self, window):
pygame.draw.circle(window, self.colour, (self.x, self.y), self.radius)
class enemy(object):
walkRight = [pygame.image.load('R1E.png'), pygame.image.load('R2E.png'), pygame.image.load('R3E.png'),
pygame.image.load('R4E.png'), pygame.image.load('R5E.png'), pygame.image.load('R6E.png'),
pygame.image.load('R7E.png'), pygame.image.load('R8E.png'), pygame.image.load('R9E.png'),
pygame.image.load('R10E.png'), pygame.image.load('R11E.png')]
walkLeft = [pygame.image.load('L1E.png'), pygame.image.load('L2E.png'), pygame.image.load('L3E.png'),
pygame.image.load('L4E.png'), pygame.image.load('L5E.png'), pygame.image.load('L6E.png'),
pygame.image.load('L7E.png'), pygame.image.load('L8E.png'), pygame.image.load('L9E.png'),
pygame.image.load('L10E.png'), pygame.image.load('L11E.png')]
def __init__(self, x, y, width, height, end):
self.x = x
self.y = y
self.width = width
self.height = height
self.end = end
self.path = [self.x, self.end]
self.walkCount = 0
self.vel = 2
self.hitBox = (self.x + 17, self.y + 2, 31, 57)
self.health = 10
self.visible = True
def draw(self, window):
self.move()
if self.visible:
if self.walkCount + 1 >= 33:
self.walkCount = 0
if self.vel > 0:
window.blit(self.walkRight[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
else:
window.blit(self.walkLeft[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
pygame.draw.rect(window, (255, 0, 0), (self.hitBox[0], self.hitBox[1] - 20, 50, 10))
pygame.draw.rect(window, (0, 128, 0),
(self.hitBox[0], self.hitBox[1] - 20, 50 - (5 * (10 - self.health)), 10))
self.hitBox = (self.x + 17, self.y + 2, 31, 57)
pygame.draw.rect(window, (255, 0, 0), self.hitBox, 2)
def move(self):
if self.vel > 0:
if self.x + self.vel < self.path[1]:
self.x += self.vel
else:
self.vel = self.vel * -1
self.walkCount = 0
else:
if self.x - self.vel > self.path[0]:
self.x += self.vel
else:
self.vel = self.vel * -1
self.walkCount = 0
def hit(self):
if self.health > 0:
self.health -= 1
else:
self.visible = False
# print('hit')
def redrawGamewindowdow():
window.blit(backGround, (0, 0))
text = font.render('Score: ' + str(score), 1, (0, 0, 0))
window.blit(text, (350, 10))
mc.draw(window)
goblin.draw(window)
for bullet in bullets:
bullet.draw(window)
pygame.display.update()
# mainloop
font = pygame.font.SysFont('comicsans', 30, True)
mc = player(10, 415, 64, 64)
goblin = enemy(400, 415, 64, 64, 700)
enemies = []
for i in range(3):
enemies.append(enemy(random.randint(0, 800), random.randint(0, 480), 80, 84, 650))
print(2)
# goblin = enemy(random.random()*599+20, 415, 64, 64, 700)
shootLoop = 0
bullets = []
run = True
while run:
#print here
clock.tick(27)
if goblin.visible:
if mc.hitBox[1] < goblin.hitBox[1] + goblin.hitBox[3] and mc.hitBox[1] + mc.hitBox[3] > goblin.hitBox[1]:
if mc.hitBox[0] + mc.hitBox[2] > goblin.hitBox[0] and mc.hitBox[0] < goblin.hitBox[0] + goblin.hitBox[2]:
mc.hit()
score -= 2
if shootLoop > 0:
shootLoop += 1
if shootLoop > 3:
shootLoop = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for bullet in bullets:
if bullet.y - bullet.radius < goblin.hitBox[1] + goblin.hitBox[3] and bullet.y + bullet.radius > goblin.hitBox[
1]:
if bullet.x + bullet.radius > goblin.hitBox[0] and bullet.x - bullet.radius < goblin.hitBox[0] + \
goblin.hitBox[2]:
hitSound.play()
goblin.hit()
score += 1
bullets.pop(bullets.index(bullet))
if 800 > bullet.x > 0:
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet))
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and shootLoop == 0:
bulletSound.play()
if mc.left:
facing = -1
else:
facing = 1
if len(bullets) < 3:
bullets.append(
projectile(round(mc.x + mc.width // 2), round(mc.y + mc.height // 2), 6, (0, 0, 0), facing))
shootLoop = 1
if keys[pygame.K_LEFT] and mc.x > mc.vel:
mc.x -= mc.vel
mc.left = True
mc.right = False
mc.standing = False
elif keys[pygame.K_RIGHT] and mc.x < 800 - mc.width - mc.vel:
mc.x += mc.vel
mc.right = True
mc.left = False
mc.standing = False
else:
mc.standing = True
mc.walkCount = 0
if not mc.isJump:
if keys[pygame.K_UP]:
mc.isJump = True
mc.right = False
mc.left = False
mc.walkCount = 0
else:
if mc.jumpCount >= -10:
neg = 1
if mc.jumpCount < 0:
neg = -1
mc.y -= (mc.jumpCount ** 2) * 0.3 * neg #changes the .3 from a .5
mc.jumpCount -= 1
else:
mc.isJump = False
mc.jumpCount = 10
redrawGamewindowdow()
pygame.quit()
Your enemies are well constructed, but you do not draw and move them. Draw the elements of the list enemies in a loop is redrawGamewindowdow:
def redrawGamewindowdow():
window.blit(backGround, (0, 0))
text = font.render('Score: ' + str(score), 1, (0, 0, 0))
window.blit(text, (350, 10))
mc.draw(window)
goblin.draw(window)
# draw enemies
for e in enemies:
e.draw(window)
for bullet in bullets:
bullet.draw(window)
pygame.display.update()

Rect value not updating x postition?

I'm creating a game with cars coming at you. I want the cars to change x_pos every time they go off the screen, but for some reason the value changes but the cars don't actually move. I don't know how to fix this and was wondering if there's something I have to do to make it change. If you want to test my code just remove the background and everything else will work. Thanks.
import time, pygame, random
import math
pygame.init()
#First Variables
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREEN = (100, 255, 100)
ORANGE = (255, 140, 0)
YELLOW = (155, 135, 12)
white = (255, 255, 255)
GOLD = (255, 215, 0)
screenwidth = 500
screenheight = 500
Lines = True
Space = True
color = random.sample(range(250), 3)
i = []
x = 247
y = - 20
y1 = 40
y2 = 100
y3 = 160
y4 = 220
y5 = 280
y6 = 340
y7 = 400
y8 = 460
#Display and caption
win = pygame.display.set_mode((screenwidth, screenheight))
pygame.display.set_caption('Lil cary')
clock = pygame.time.Clock()
#Load in images
bkg = pygame.image.load('BG.jpg')
#Actual player class
class player():
def __init__(self):
self.color = (12, 124, 134)
self.vel = 5
self.grassdamage = 0
self.image = pygame.Surface([50, 100], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, 50, 100))
self.rect = self.image.get_rect(center = (200, 390))
self.damage1 = False
self.damage2 = False
self.damage3 = False
self.damage4 = False
self.damage5 = False
self.damage6 = False
self.damage7 = False
self.damage8 = False
self.dead = False
self.score = 0
def draw (self, win):
#pygame.draw.rect(win, (self.color), (self.x, self.y, self.width, self.height))
win.blit(self.image, self.rect.topleft)
def moveback(self):
if self.rect.y < 390 and self.rect.y >= 0:
self.rect.y += 10
def grass(self):
if self.rect.x > -10 and self.rect.x < 150:
self.grassdamage += 1
self.vel = 3
elif self.rect.x > 300 and self.rect.x < 500:
self.vel =3
self.grassdamage += 1
else:
self.vel = 5
def grasshealth(self):
if self.grassdamage == 100:
self.damage1 = True
elif self.grassdamage == 200:
self.damage2 = True
elif self.grassdamage == 300:
self.damage3 = True
elif self.grassdamage == 400:
self.damage4 = True
elif self.grassdamage == 500:
self.damage5 = True
elif self.grassdamage == 600:
self.damage6 = True
elif self.grassdamage == 600:
self.damage6 = True
elif self.grassdamage == 700:
self.damage7 = True
elif self.grassdamage == 800:
self.damage8 = True
self.dead = True
def death(self):
if self.dead == True:
raise SystemExit ('YOU MOFO DIED')
def scorecount (self):
if self.score >= 15:
raise SystemExit ('YOU WIN OMG KIDS')
def scoredraw(self):
Text = pygame.font.Font('freesansbold.ttf', 25)
TextSurf, TextRect1 = text_objects("Score: " + str(self.score), Text)
TextRect1.center = ((50), (450))
win.blit(TextSurf, TextRect1)
#Text Setup
def text_objects(text, font):
textSurface = font.render(text, True, BLACK)
return textSurface, textSurface.get_rect()
#Drawing damage bar
def drawbar ():
if player.damage1 == True and car.damage1 == False or car.damage1 == True:
pygame.draw.rect(win, (GOLD), (50, 50, 25, 25))
if player.damage2 == True and car.damage1 == False or car.damage1 == True:
pygame.draw.rect(win, (GOLD), (50, 75, 25, 25))
if car.damage1 == True and player.grassdamage <= 200:
player.grassdamage = 201
if player.damage3 == True and car.damage2 == False or car.damage2 == True:
pygame.draw.rect(win, (GOLD), (50, 100, 25, 25))
if player.damage4 == True and car.damage2 == False or car.damage2 == True:
pygame.draw.rect(win, (GOLD), (50, 125, 25, 25))
if car.damage2 == True and player.grassdamage <= 400:
player.grassdamage = 401
if player.damage5 == True and car.damage3 == False or car.damage3 == True:
pygame.draw.rect(win, (GOLD), (50, 150, 25, 25))
if player.damage6 == True and car.damage3 == False or car.damage3 == True:
pygame.draw.rect(win, (GOLD), (50, 175, 25, 25))
if car.damage3 == True and player.grassdamage <= 600:
player.grassdamage = 601
if player.damage7 == True and car.damage4 == False or car.damage4 == True:
pygame.draw.rect(win, (GOLD), (50, 200, 25, 25))
if player.damage8 == True and car.damage4 == False or car.damage4 == True:
pygame.draw.rect(win, (GOLD), (50, 225, 25, 25))
raise SystemExit ('YOU LOST')
if car.damage4 == True and player.grassdamage <= 800:
player.grassdamage = 800
pygame.draw.rect(win, (0,0,0), (50, 50, 25, 200), 3)
Text = pygame.font.Font('freesansbold.ttf', 20)
TextSurf, TextRect = text_objects("Damage", Text)
TextRect.center = ((65), (30))
win.blit(TextSurf, TextRect)
class car1():
ROAD_LEFT = 175
ROAD_RIGHT = 300
def __init__(self):
self.x_pos = random.randrange(car1.ROAD_LEFT, car1.ROAD_RIGHT)
self.color = random.sample(range(250), 3)
self.image = pygame.Surface([50, 100], pygame.SRCALPHA, 32)
pygame.draw.rect(self.image, (self.color), (0, 0, 50, 100))
self.rect = self.image.get_rect(topleft = (self.x_pos, -100))
self.carvel = random.randrange(8, 10)
self.damage = 0
self.damage1 = False
self.damage2 = False
self.damage3 = False
self.damage4 = False
def draw(self, win):
#pygame.draw.rect(win,(self.color),self.rect)
win.blit(self.image, self.rect.topleft)
def move(self):
if self.rect.y < 530:
self.rect.y += self.carvel
else:
self.rect.y = -100
player.score += 1
self.color = random.sample(range(250), 3)
self.carvel = random.randrange(6, 8)
self.x_pos = random.randrange(car1.ROAD_LEFT, car1.ROAD_RIGHT)
def collision_check(self, another_object):
if self.rect.colliderect(another_object):
print('collison')
self.rect.y = -100
self.damage += 1
def cardamage(self):
if self.damage == 1:
self.damage1 = True
player.damage1 = True
player.damage2 = True
if self.damage == 2:
self.damage2 = True
player.damage3 = True
player.damage4 = True
if self.damage == 3:
self.damage3 = True
player.damage5 = True
player.damage6 = True
if self.damage == 4:
self.damage4 = True
player.damage7 = True
player.damage8 = True
#Putting variables to the classes
player = player()
car = car1()
car_list = [ car ] # start with one car
car_add_time = 0
#Main drawing function
def redrawgamewindow():
win.blit(bkg, (0, 0))
pygame.draw.rect(win, (0, 0, 0), (150, 0, 200, 500))
pygame.draw.rect(win, (255, 255, 255), (x, (y), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y1), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y2), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y3), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y4), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y5), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y6), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y7), 10, 30))
pygame.draw.rect(win, (255, 255, 255), (x, (y8), 10, 30))
player.draw(win)
for car in car_list:
car.draw(win)
player.grasshealth()
for car in car_list:
car.cardamage()
player.grass()
player.death()
for car in car_list:
car.collision_check(player.rect)
car.move()
drawbar()
player.scorecount()
player.scoredraw()
pygame.display.update()
#MAINLOOP
run = True
while run:
#Making background and FPS
clock.tick(80)
#Quiting Funciton
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
time_now = pygame.time.get_ticks()
if (time_now - car_add_time > 5000):
new_car = car1()
car_list.append(new_car)
car_add_time = time_now
#Scrolling the lines
if Lines:
y += player.vel
y1 += player.vel
y2 += player.vel
y3 += player.vel
y4 += player.vel
y5 += player.vel
y6 += player.vel
y7 += player.vel
y8 += player.vel
if Lines:
if y >= 500:
y = -40
if y1 >= 500:
y1 = -40
if y2 >= 500:
y2 = -40
if y3 >= 500:
y3 = -40
if y4 >= 500:
y4 = -40
if y5 >= 500:
y5 = -40
if y6 >= 500:
y6 = -40
if y7 >= 500:
y7 = -40
if y8 >= 500:
y8 = -40
#User input
keys = pygame.key.get_pressed()
#Boost controller
if keys[pygame.K_SPACE]:
start_time = time.time()
if player.rect.y > 200:
player.rect.y -= 9
Space = True
else:
player.moveback()
end_time = time.time()
#Left movement
if keys[pygame.K_LEFT] and player.rect.x > 150:
player.rect.x -= 5
if keys [pygame.K_LEFT] and player.rect.x <= 150:
if player.rect.x > 0:
player.rect.x -=5
#Right movement
if keys[pygame.K_RIGHT] and player.rect.x < 300:
player.rect.x += 5
if keys[pygame.K_RIGHT]and player.rect.x >= 300:
if player.rect.x < 500 - player.rect.width:
player.rect.x += 5
#Grass and grass damage
#MAIN DRAW RECALL
redrawgamewindow()
It is not sufficient to set a random value to self.x_pos. For drawing the "car" the position of the pygame.Rect object self.rect is used:
def draw(self, win):
win.blit(self.image, self.rect.topleft)
So you've to change self.rect.x, too:
class car1():
# [...]
def move(self):
if self.rect.y < 530:
self.rect.y += self.carvel
else:
self.rect.y = -100
player.score += 1
self.color = random.sample(range(250), 3)
self.carvel = random.randrange(6, 8)
self.x_pos = random.randrange(car1.ROAD_LEFT, car1.ROAD_RIGHT)
self.rect.x = self.x_pos # <---------------------------------------

How do I make one Sprite move towards another in pygame/python

So I've been doing quite a lot of research on this question, and I still haven't been able to implement other people's solutions to solve mine. I'm trying to make the Mob2 class move towards the Player class. Any suggestions to my code, or even how to improve my code would be greatly appreciated :) BTW, the code I've written below has been made in Atom, if you have any questions I'll be around to answer them. Thank you all so much!!
# Pygame template - skeleton for a new pygame project
import pygame
import random
import math
from os import path
working_dir = path.dirname(__file__)
from pygame.locals import *
WIDTH = 1000
HEIGHT = 700
FPS = 60
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Virus Invaders")
clock = pygame.time.Clock()
font_name = pygame.font.match_font('arial')
health = 4
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
def newmob():
m = Mob()
all_sprites.add(m)
mobs.add(m)
def newmob2():
n = Mob2()
all_sprites.add(n)
mobs2.add(n)
def draw_health_bar(surf, x, y, health):
if health==4:
healthImage = healthSheet.get_image(0, 102, 176, 23)
screen.blit(healthImage, [50, 50])
if health==3:
healthImage = healthSheet.get_image(0, 128, 176, 23)
screen.blit(healthImage, [50, 50])
if health==2:
healthImage = healthSheet.get_image(0, 155, 176, 23)
screen.blit(healthImage, [50, 50])
if health==1:
healthImage = healthSheet.get_image(0, 182, 176, 23)
screen.blit(healthImage, [50, 50])
if health==0:
healthImage = healthSheet.get_image(0, 209, 176, 23)
screen.blit(healthImage, [50, 50])
class Player(pygame.sprite.Sprite):
def __init__(self, health):
pygame.sprite.Sprite.__init__(self)
self.image = dudeSpriteSheet.get_image(60, 0, 60, 60)
self.rect = self.image.get_rect()
self.radius = 25
#pygame.draw.circle(self.image, RED, self.rect.center, self.radius)
self.rect.centerx = 100
self.rect.centery = 400.5
self.speedx = 0
self.speedy = 0
self.health = health
def update(self):
self.speedx = 0
self.speedy = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_s]:
self.speedy = 4
if keystate[pygame.K_w]:
self.speedy = -4
if keystate[pygame.K_d]:
self.speedx = 4
if keystate[pygame.K_a]:
self.speedx = -4
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.right > WIDTH-80:
self.rect.right = WIDTH-80
if self.rect.left < 90:
self.rect.left = 90
if self.rect.bottom > HEIGHT-87:
self.rect.bottom = HEIGHT-87
if self.rect.top < 187:
self.rect.top = 187
def shoot(self, X, Y, direction):
if direction == 1:
self.image = dudeSpriteSheet.get_image(60, 0, 60, 60)
elif direction == 2:
self.image = dudeSpriteSheet.get_image(0, 0, 60, 60)
elif direction == 3:
self.image = dudeSpriteSheet.get_image(120, 0, 60, 60)
elif direction == 4:
self.image = dudeSpriteSheet.get_image(180, 0, 60, 60)
X = X+self.speedx
Y = Y+self.speedy
bullet = Bullet(self.rect.centerx, self.rect.centery, X, Y)
all_sprites.add(bullet)
bullets.add(bullet)
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = virus_img
self.image.set_colorkey(WHITE)
self.rect = self.image.get_rect()
self.radius = int(self.rect.width * 0.85 / 2)
#pygame.draw.circle(self.image, RED, self.rect.center, self.radius)
self.rect.x = WIDTH - 200
self.rect.y = 400.5
self.speedx = random.randrange(-4, 4)
self.speedy = random.randrange(-4, 4)
def update(self):
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.bottom >= HEIGHT - 87:
self.speedy = -self.speedy
if self.rect.top <= 193:
self.speedy = -self.speedy
if self.rect.left <= 94:
self.speedx = -self.speedx
if self.rect.right >= WIDTH - 96:
self.speedx = -self.speedx
class Mob2(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = virus2_img
self.image.set_colorkey(WHITE)
self.rect = self.image.get_rect()
self.radius = int(self.rect.width * 0.85 / 2)
pygame.draw.circle(self.image, RED, self.rect.center, self.radius)
self.rect.x = WIDTH - 200
self.rect.y = 300
self.rot = 0
self.speed = 3
def update(self, Player):
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, X, Y):
pygame.sprite.Sprite.__init__(self)
self.image = bullet_img
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.radius = 25
self.rect.bottom = y
self.rect.centerx = x
self.speedy = Y
self.speedx = X
def update(self):
self.rect.x += self.speedx
self.rect.y += self.speedy
# Kill if it moves off the top of the screen
if self.rect.bottom < 0 or self.rect.top > 700 or self.rect.right <
0 or self.rect.left > 1000:
self.kill()
class Spritesheet:
#Utility class for loading and parsing spritesheets
def __init__(self, filename):
self.spritesheet = pygame.image.load(filename).convert()
def get_image(self, x, y, width, height):
#Grab an image out of a larger spritesheet
image = pygame.Surface((width, height))
image.blit(self.spritesheet, (0, 0), (x, y, width, height))
image.set_colorkey(BLACK)
return image
# Load all game graphics
background = pygame.image.load(path.join(working_dir,
'GameScreen.png')).convert()
background_rect = background.get_rect()
player_img = pygame.image.load(path.join(working_dir,'dude.png')).convert()
virus_img =
pygame.image.load(path.join(working_dir,'badguy1.png')).convert()
bullet_img =
pygame.image.load(path.join(working_dir,'bullet.png')).convert()
dudeSpriteSheet = Spritesheet(path.join(working_dir,
'DudeSpriteSheet2.png'))
healthSheet = Spritesheet(path.join(working_dir, 'health.png'))
virus2_img =
pygame.image.load(path.join(working_dir,'badguy2(2).png')).convert()
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
mobs2 = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player(health)
all_sprites.add(player)
for i in range(8):
newmob()
newmob2()
score = 0
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
player.shoot(10, 0, 1)
elif event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
player.shoot(0, -10, 2)
elif event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
player.shoot(0, 10, 3)
elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
player.shoot(-10, 0, 4)
# Update
all_sprites.update()
#Check to see if bullet hits a mob
hits = pygame.sprite.groupcollide(mobs, bullets, True,
pygame.sprite.collide_circle)
for hit in hits:
score += 1
newmob()
# Check to see if a virus hits a player
hits = pygame.sprite.spritecollide(player, mobs, True,
pygame.sprite.collide_circle)
for hit in hits:
health -= 1
newmob()
if health <= 0:
running = False
# Draw / render
screen.fill(BLACK)
screen.blit(background, background_rect)
all_sprites.draw(screen)
draw_text(screen, str(score), 18, WIDTH / 2, 10)
draw_health_bar(screen, 5, 5, health)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
First compare Mob.rect.x with Player.rect.x to see if it should move left or right, then do the same with rect.y to see if it should move up or down. The its simply getting Mob to move in that direction.

Categories

Resources