x coordinates of enemy doesn't change (pygame) - python

I'm currently making submarine game with pygame. I wanted enemy to move left and right. However, although I added code for changing x coordinates they wont change. Error actualy started when I added one more enemy to the game. Before when there was only one enemy this problem didn't occur. I tried to search for problem myself, but unsuccesfully.
Here's the code:
import pygame
pygame.init()
run = True
screen = pygame.display.set_mode((600, 500), pygame.FULLSCREEN)
pygame.display.set_caption('Podmornca')
background = pygame.image.load('background1.png')
bottom = pygame.image.load('bottom.png')
bottomx = 100
shoot = pygame.mixer.Sound('torpedo-5.wav')
clock = pygame.time.Clock()
enemyL = pygame.image.load('enemyL.png')
enemyD = pygame.image.load('enemyD.png')
torpL = pygame.image.load('torpL.png')
torpD = pygame.image.load('torpD.png')
hit = pygame.mixer.Sound('torpedo-fire.wav')
explosion = pygame.mixer.Sound('explosion.wav')
ekspl = pygame.image.load('explosion.png')
font = pygame.font.SysFont('bauhaus93', 40)
win = font.render('YOU WON!', 1, (255, 0, 0))
lose = font.render('GAME OVER!', 1, (255, 0, 0))
class enemy1():
def __init__(self, x, y, v):
self.x = x
self.y = y
self.v = v
self.start = 1300
self.end = 1800
self.left = True
self.right = False
self.way = -1
self.projectilex = x
self.projectiley = y
self.shot = False
self.frame = (self.x, self.y, 200, 92)
self.life = 300
def shoot(self):
if self.shot:
shoot.play()
if self.left:
screen.blit(torpL, (self.projectilex, self.projectiley + 40))
self.projectilex += 10 * self.way
if self.right:
screen.blit(torpD, (self.projectilex, self.projectiley + 40))
self.projectilex += 10 * self.way
if self.projectilex > 600 or self.projectilex < 0:
self.shot = False
self.projectilex = self.x
self.projectiley = self.y
def move(self):
if self.life > 0:
if self.left:
self.frame = (self.x + 10, self.y, 177, 92)
pygame.draw.rect(screen, (255,0,0), (self.x + 60, self.y - 5, self.life * 0.25, 4 ), 0)
self.way = -1
if self.x > self.end:
screen.blit(enemyL, (self.x, self.y))
self.x -= self.v
if self.x == self.end:
self.left = False
self.right = True
if self.right:
self.way = 1
self.frame = (self.x + 10, self.y, 177, 92)
if self.x < self.start:
pygame.draw.rect(screen, (255,0,0), (self.x + 60, self.y - 5, self.life * 0.25, 4 ), 0)
screen.blit(enemyD, (self.x, self.y))
self.x += self.v
if self.x == self.start:
self.left = True
self.right = False
if self.x - player.x <= 300:
self.shoot()
self.shot = True
else:
explosion.play()
class enemy2():
def __init__(self, x, y, v):
self.x = x
self.y = y
self.v = v
self.start = 1900
self.end = 2400
self.left = True
self.right = False
self.way = -1
self.projectilex = x
self.projectiley = y
self.shot = False
self.frame = (self.x, self.y, 200, 92)
self.frame = 300
def shoot(self):
if self.shot:
shoot.play()
if self.left:
screen.blit(torpL, (self.projectilex, self.projectiley + 40))
self.projectilex += 10 * self.way
if self.right:
screen.blit(torpD, (self.projectilex, self.projectiley + 40))
self.projectilex += 10 * self.way
if self.projectilex > 600 or self.projectilex < 0:
self.shot = False
self.projectilex = self.x
self.projectiley = self.y
def move(self):
if self.life > 0:
if self.left:
self.frame = (self.x + 10, self.y, 177, 92)
pygame.draw.rect(screen, (255,0,0), (self.x + 60, self.y - 5, self.life * 0.25, 4 ), 0)
self.way = -1
if self.x > self.end:
screen.blit(enemyL, (self.x, self.y))
self.x -= self.v
if self.x == self.end:
self.left = False
self.right = True
if self.right:
self.way = 1
self.frame = (self.x + 10, self.y, 177, 92)
if self.x < self.start:
pygame.draw.rect(screen, (255,0,0), (self.x + 60, self.y - 5, self.life * 0.25, 4), 0)
screen.blit(enemyD, (self.x, self.y))
self.x += self.v
if self.x == self.start:
self.left = True
self.right = False
else:
explosion.play()
submarine1 = enemy1(1300, 250, 5)
submarine2 = enemy2(1900, 250, 5)
right = True
left = False
def graphics():
global bottomx
clock.tick(60)
screen.blit(background, (0,0))
screen.blit(bottom, (bottomx, 250))
if bottomx < -594:
bottomx = 1194
submarine1.move()
podmornca2.premik()
pygame.display.flip()
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
run = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
bottomx += 5
submarine1.start += 5
submarine2.start += 5
submarine1.end += 5
submarine2.end += 5
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
bottomx -= 5
submarine1.start -= 5
submarine2.start -= 5
submarine1.end -= 5
submarine2.end -= 5
if submarine1.life < 0 and submarine2.life < 0:
screen.blit(ekspl, (submarine1.x, submarine1.y))
screen.blit(ekspl, (submarine1.x + 5, submarine1.y))
screen.blit(ekspl, (submarine2.x, submarine2.y))
screen.blit(ekspl, (submarine2.x + 5, submarine2.y))
screen.blit(end, (200, 250))
graphics()
pygame.quit()

A couple things can help...
As stated above, just use one enemy class and derive both submarines from it like:
sub1 = enemy(...)
sub2 = enemy(...)
Your main problem with the moving right is that you have your start and end points reversed. You move right towards the start, so start must be greater than end. You have them flipped.
In several spots, you should be using if-else or if-elif-else instead of a bunch of if statements to clean up the logic and make sure one or the other executes.
Good luck!

Related

Pygame collisions is wierd [duplicate]

This question already has answers here:
Pygame: Collision by Sides of Sprite
(5 answers)
How can I rewrite my collision logic in my pygame platformer?
(1 answer)
Closed 16 days ago.
So Ive been at this one problem for more than a week now and i feel like Ive tried everything. Nothing works, Ive looked it up, but at the same time I don't want to just copy code i would like to actually understand it.
def x_collision(self):
for tile in tiles:
self.rect = pygame.Rect(self.x, self.y, self.size, self.size)
if tile.colliderect(self.rect):
if self.x_vel > 0:
self.x = tile.right
if self.x_vel < 0:
self.x = tile.left - self.size
def y_collision(self):
for tile in tiles:
self.rect = pygame.Rect(self.x, self.y, self.size, self.size)
if tile.colliderect(self.rect):
if self.y_vel > 0:
self.y = tile.bottom
if self.y_vel < 0:
self.y = tile.top
This is just the two main functions for the collision located inside the player class.
Ive gotten the collisions to work on each axis but when i merge the two together it just goes insane, I'm guessing this has something to do with the position of the player being set in the wrong place but that shouldn't be the problem considering im not checking for the collision in one function but instead in two different for each the x and y.
Just, it's probably because of some stupid reason and it shouldn't be that hard if you're not dumb like me but i just can't seem to figure it out
Also if you're testing the code just delete everything that has something to do with sound!
Here is the entire code for reference (i know it's messy but im very new to this so good luck!)
import pygame
import random
import math
import time
# Initialize Pygame
pygame.init()
pygame.mixer.init()
# Set the size of the window
size = (900, 600)
screen = pygame.display.set_mode(size)
# Set the title of the window
pygame.display.set_caption("Classes testing")
clock = pygame.time.Clock()
fps = 60
pygame.mixer.music.load('PewPewProject/Retro Platform.wav')
pygame.mixer.music.set_volume(0.1)
pygame.mixer.music.play(-1)
pop_sound = pygame.mixer.Sound("PewPewProject/vine-boom.wav")
pop_sound.set_volume(0.5)
level = [
['1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1'],
['1','E','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','E','0','0','0','1'],
['1','0','0','0','1','1','1','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','1','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','1','0','1','0','0','0','0','0','0','0','0','E','0','0','0','0','1'],
['1','0','0','1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','E','1','1','1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','E','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','1','1','0','1','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','0','0','0','1','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','0','1','1','1','0','E','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','0','1','S','1','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','1','0','0','0','1','0','0','0','0','0','1'],
['1','0','0','E','0','0','0','0','0','1','1','1','1','1','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1'],
['1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1'],
]
tilex, tiley = [0, 0]
tilex_offset, tiley_offset = [0, 0]
tile_size = 50
tilemap = pygame.image.load('PewPewProject/tilemap.png')
tiles = []
collision_tiles = []
enemy_spawns = []
def build_level():
for tiley, rows in enumerate(level):
for tilex, tile in enumerate(rows):
if tile == '1':
tile_rect = pygame.Rect(tilex*tile_size+tilex_offset, tiley*tile_size+tiley_offset, tile_size, tile_size)
tiles.append(tile_rect)
elif tile == '0':
pass
elif tile == 'E':
enemy_spawns.append([tilex, tiley])
elif tile == 'S':
pass
elif tile == 'R':
pass
else:
print("Wrong Map Input")
def rebuild_level():
global tiles, enemy_spawns
tiles = []
enemy_spawns = []
build_level()
def draw_level():
for tiley, rows in enumerate(level):
for tilex, tile in enumerate(rows):
color = None
if tile == '1':
color = (100, 100, 100)
elif tile == 'S':
color = (50, 255, 100)
elif tile == 'R':
color = (255, 50, 50)
if color:
pygame.draw.rect(screen, color, (tilex*tile_size+tilex_offset, tiley*tile_size+tiley_offset, tile_size, tile_size))
def random_except(start, end, exception_start, exception_end):
num = random.randint(start, end)
while num >= exception_start and num <= exception_end:
num = random.randint(start, end)
return num
class Player:
def __init__(self, x, y):
global projectiles
self.speed = 5
self.x = x
self.y = y
self.x_vel = 0
self.y_vel = 0
self.px_vel = 0
self.py_vel = 0
self.size = tile_size
self.gunsurface = pygame.Surface((90, 25), pygame.SRCALPHA)
self.healthboost = 1
self.health = 100 * 1
self.rotated_gunsurface = self.gunsurface
self.gunsurface.fill((150, 150, 150))
self.gunrect = self.gunsurface.get_rect()
projectiles = [Projectile(-100, 0, 0)]
self.last_shot_time = 0
self.cooldown = 0.5
self.is_slowed = False
dx = 0
dy = 0
self.angle = math.atan2(dy, dx)
self.force = 72
self.forceCounterCuzIAmBadAtPython = self.force
self.rect = pygame.Rect(self.x, self.y, self.size, self.size)
self.alive = True
self.colliding = False
def x_collision(self):
for tile in tiles:
self.rect = pygame.Rect(self.x, self.y, self.size, self.size)
if tile.colliderect(self.rect):
if self.x_vel > 0:
self.x = tile.right
if self.x_vel < 0:
self.x = tile.left - self.size
def y_collision(self):
for tile in tiles:
self.rect = pygame.Rect(self.x, self.y, self.size, self.size)
if tile.colliderect(self.rect):
if self.y_vel > 0:
self.y = tile.bottom
if self.y_vel < 0:
self.y = tile.top
def Movement(self):
global tiley_offset, tilex_offset
self.keys = pygame.key.get_pressed()
tilex_offset += self.x_vel
self.x_collision()
if self.x_vel != 0:
self.x_vel -= self.px_vel
self.forceCounterCuzIAmBadAtPython -= 1
if self.forceCounterCuzIAmBadAtPython <= 0:
self.x_vel = 0
tiley_offset += self.y_vel
self.y_collision()
if self.y_vel != 0:
self.y_vel -= self.py_vel
if self.forceCounterCuzIAmBadAtPython <= 0:
self.y_vel = 0
rebuild_level()
def Alive(self):
if self.health <= 0:
self.alive = False
def GUI(self):
self.empty_health_bar = pygame.draw.rect(screen, (200, 20, 20), (screen.get_width()/4, 10,466, 25))
self.health_bar = pygame.draw.rect(screen, (20, 200, 20), (screen.get_width()/4, 10, self.health*4.66/self.healthboost, 25))
pygame.draw.line(screen, (0, 0, 0), (screen.get_width()/4, 10),(screen.get_width()/4+466, 10), 2)
pygame.draw.line(screen, (0, 0, 0), (screen.get_width()/4, 35),(screen.get_width()/4+466, 35), 2)
pygame.draw.line(screen, (0, 0, 0), (screen.get_width()/4, 10), (screen.get_width()/4, 35), 2)
pygame.draw.line(screen, (0, 0, 0), (screen.get_width()/4+466, 10), (screen.get_width()/4+466, 35), 2)
def Gun(self):
cursor_x, cursor_y = pygame.mouse.get_pos()
dx = cursor_x - (self.x + self.size)
dy = cursor_y - (self.y + self.size)
angle = math.atan2(dy, dx)
self.rotated_gunsurface = pygame.transform.rotate(self.gunsurface, math.degrees(angle * -1))
self.gunrect = self.rotated_gunsurface.get_rect(center = (self.x+self.size/2, self.y+self.size/2))
screen.blit(self.rotated_gunsurface, (self.gunrect.x, self.gunrect.y))
def Shoot(self):
global dx, dy
if pygame.key.get_pressed()[pygame.K_e]:
current_time = time.time()
if current_time - self.last_shot_time > self.cooldown:
self.forceCounterCuzIAmBadAtPython = self.force
pop_sound.play()
cursor_x, cursor_y = pygame.mouse.get_pos()
dx = cursor_x - (self.x + self.size/2)
dy = cursor_y - (self.y + self.size/2)
self.angle = math.atan2(dy, dx)
projectiles.append(Projectile(self.x+self.size/2, self.y+self.size/2, self.angle))
self.last_shot_time = current_time
self.x_vel = math.cos(self.angle) * self.speed
self.y_vel = math.sin(self.angle) * self.speed
self.px_vel = self.x_vel / self.force
self.py_vel = self.y_vel / self.force
def Render(self):
self.rect = pygame.Rect(self.x, self.y, self.size, self.size)
pygame.draw.rect(screen, (230, 100, 100), self.rect)
self.Gun()
class Projectile:
def __init__(self, x, y, angle):
self.x = x
self.y = y
self.angle = angle
self.speed = 8
self.hitbox = pygame.Rect(self.x, self.y, 5,5)
def Move(self):
self.x += math.cos(self.angle) * self.speed
self.y += math.sin(self.angle) * self.speed
def Render(self):
self.hitbox = pygame.draw.circle(screen, (255, 255, 0), (int(self.x), int(self.y)), 7)
class Enemy:
def __init__(self, health, main_speed, tag, size, player, x, y):
self.health = health
#self.main_speed = 3
self.tag = tag
self.size = size
self.player = player
self.speed = 3
self.x = x
self.y = y
self.alive = True
def Destroy(self):
self.alive = False
def Spawning(self):
self.hitbox = pygame.draw.rect(screen, (100, 240, 100), (self.x + tilex_offset, self.y + tiley_offset, self.size, self.size))
def Movement(self):
dx = self.player.x - self.x
dy = self.player.y - self.y
angle = math.atan2(dy - tiley_offset, dx - tilex_offset)
self.x += self.speed * math.cos(angle)
self.y += self.speed * math.sin(angle)
projectiles = [Projectile(-100, 0, 0)]
def main():
player = Player(screen.get_width()/2-tile_size/2, screen.get_height()/2-tile_size/2)
enemies = []
def Spawn_enemies(num_enemies, player):
for i in range(num_enemies):
x, y = random.choice(enemy_spawns)
enemy = Enemy(1, 1, i, 25, player, x*tile_size, y*tile_size)
enemies.append(enemy)
build_level()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Main Loop
screen.fill((100, 100, 200))
# usage
spawn_enemies_chance = random.randint(0, 250)
number_of_enemies = len(enemies)
if spawn_enemies_chance == 1 and number_of_enemies <= 4:
Spawn_enemies(1,player)
draw_level()
# enemy
for enemy in enemies:
if enemy.alive:
enemy.Movement()
enemy.Spawning()
for projectile in projectiles:
if enemy.hitbox.colliderect(projectile.hitbox):
enemy.health -= 1
pop_sound.play()
if enemy.health <= 0:
try:
enemy.alive = False
enemies.remove(enemy)
except:
print("list.remove(x): x not in list... Enemy moment")
projectiles.remove(projectile)
# Get Hurt
for enemy in enemies:
if enemy.hitbox.colliderect(player):
player.health -= 10
enemies.remove(enemy)
# Projectiles
for i, projectile in enumerate(projectiles):
projectile.Move()
projectile.Render()
if projectiles != []:
if projectile.x < 0 or projectile.x > screen.get_width() or projectile.y < 0 or projectile.y > screen.get_height():
projectiles.pop(i)
for tile in tiles:
if projectiles != []:
if tile.colliderect(projectile.hitbox):
try:
projectiles.pop(i)
except:
print(i," pop index out of range, don't mind it :)")
# player
player.Alive()
player.Shoot()
player.Movement()
player.Render()
# Renders the UI ontop of everything
player.GUI()
pygame.display.update()
clock.tick(fps)
pygame.quit()
# DO NOT DISTURB!
if __name__ == "__main__":
main()

win variable not being set to False

I am making a pong game with pygame. The check_win() function checks if one side has won and for some reason, it the point counter keeps going up on the right side when detected, but not on the left side. So when it detects the ball hit the left wall, it works as intended, but when it hits the right side, it keeps incrementing the point.
here the code
import pygame
pygame.init()
class Pad:
def __init__(self, x, win, score_x):
self.win = win
self.x = x
self.y = 250
self.speed = 5
self.score = 0
self.score_x = score_x
self.color = (255, 255, 255)
self.font = pygame.font.Font("font.ttf", 25)
self.base = pygame.Rect(0, 0, 30, 100)
self.base.center = (self.x, self.y)
self.collide_base = pygame.Rect(0, 0, 10, self.base.height)
def render(self, type_):
if type_ == 0:
self.collide_base.right = self.base.right
if type_ == 1:
self.collide_base.left = self.base.left
self.collide_base.y = self.base.y
pygame.draw.rect(self.win, self.color, self.base)
def move(self, keys, type_):
if type_ == 0:
if keys[pygame.K_w]:
self.base.centery -= self.speed
if keys[pygame.K_s]:
self.base.centery += self.speed
elif type_ == 1:
if keys[pygame.K_UP]:
self.base.centery -= self.speed
if keys[pygame.K_DOWN]:
self.base.centery += self.speed
def collide_edge(self):
if self.base.bottom >= self.win.get_height():
self.base.y -= self.speed
if self.base.top <= 0:
self.base.y += self.speed
def draw_score(self):
score = self.font.render(str(self.score), False, self.color)
self.win.blit(score, (self.score_x, self.win.get_height() - (self.win.get_height() - 20)))
class Ball:
def __init__(self, win):
self.win = win
self.color = (255, 255, 255)
self.leftWin = False
self.rightWin = False
self.speedx = 5
self.speedy = 5
self.x = self.win.get_width() / 2
self.y = self.win.get_height() / 2
self.base = pygame.Rect(0, 0, 20, 20)
self.base.center = (self.x, self.y)
def render(self):
self.base.center = (self.x, self.y)
pygame.draw.ellipse(self.win, self.color, self.base)
def move(self):
if self.base.bottom >= self.win.get_height():
self.speedy *= -1
if self.base.right >= self.win.get_width():
self.rightWin = True
if self.base.top <= 0:
self.speedy *= -1
if self.base.left <= 0:
self.leftWin = True
self.x += self.speedx
self.y += self.speedy
class Game:
def __init__(self):
self.width = 750
self.height = 500
self.running = True
self.color = (0, 0, 0)
self.fps = 60
self.win = pygame.display.set_mode((self.width, self.height), pygame.RESIZABLE)
self.clock = pygame.time.Clock()
self.pad1 = Pad(50, self.win, self.width / 2 + 25)
self.pad2 = Pad(700, self.win, self.width / 2 - 40)
self.ball = Ball(self.win)
self.line = []
def draw_line(self):
for x in range(20):
if x % 2 == 0:
rect = pygame.Rect(0, 0, 20, 40)
rect.center = (self.width / 2, x * 40)
self.line.append(rect)
for rect in self.line:
pygame.draw.rect(self.win, (255, 255, 255), rect)
def check_pad(self):
if self.ball.base.colliderect(self.pad1.base):
self.ball.x += 10
self.ball.speedx *= -1
if self.ball.base.colliderect(self.pad2.base):
self.ball.x -= 10
self.ball.speedx *= -1
def check_win(self):
if self.ball.leftWin:
self.ball.base.center = (self.width / 2, self.height / 2)
self.ball.leftWin = False
self.ball.speedx = 5
self.ball.speedy = 5
self.pad1.score += 1
if self.ball.rightWin:
self.ball.base.center = (self.width / 2, self.height / 2)
self.ball.rightWin = False
self.ball.speedx = 5
self.ball.speedy = 5
self.pad2.score += 1
def run(self):
while self.running:
self.clock.tick(self.fps)
self.win.fill(self.color)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
keys = pygame.key.get_pressed()
self.draw_line()
self.check_pad()
self.check_win()
self.ball.render()
self.ball.move()
self.pad1.render(0)
self.pad1.move(keys, 0)
self.pad1.collide_edge()
self.pad1.draw_score()
self.pad2.render(1)
self.pad2.move(keys, 1)
self.pad2.collide_edge()
self.pad2.draw_score()
pygame.display.update()
pygame.quit()
if __name__ == '__main__':
Game().run()
You have forgotten to update self.ball.x and self.ball.y. Note, self.base.center is set from self.x, self.y in the function render.
class Game:
# [...]
def check_win(self):
if self.ball.leftWin:
self.ball.base.center = (self.width / 2, self.height / 2)
self.ball.x, self.ball.y = self.ball.base.center # <---
self.ball.leftWin = False
self.ball.speedx = 5
self.ball.speedy = 5
self.pad1.score += 1
if self.ball.rightWin:
self.ball.base.center = (self.width / 2, self.height / 2)
self.ball.x, self.ball.y = self.ball.base.center # <---
self.ball.rightWin = False
self.ball.speedx = 5
self.ball.speedy = 5
self.pad2.score += 1

Pygame is a bit laggy. Is it because of the many calculations?

import pygame
import math
import random
import time
pygame.init()
clock = pygame.time.Clock()
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Shadow Warrior")
#its like that because this reduses lag a lot and help for better gameplay
def loadify(imgname):
return pygame.image.load(imgname).convert_alpha(screen)
#Models:
logo = loadify("textures/logo.png")
pygame.display.set_icon(logo)
wallModel = loadify("textures/wall.png")
groundModel = loadify("textures/ground.png")
weaponModel = loadify("textures/weapon.png")
enemyBullet = loadify("textures/bullet.png")
playerBullet = loadify("textures/enemyBullet.png")
crosshair = loadify("textures/crosshair.png")
playerWalkAnimR = [loadify("textures\walk0.png"),
loadify("textures\walk1.png"),
loadify("textures\walk2.png")]
playerWalkAnimL = [loadify("textures\walk3.png"),
loadify("textures\walk4.png"),
loadify("textures\walk5.png")]
pygame.mouse.set_visible(False)
tileSize = 64
level = 0
hitParticles = []
weapons = []
removed_bullets = []
enemies = []
backgrounds = []
walls = []
all_bullets = []
# Classes
class Particle:
def __init__(self, x, y, velocityX, velocityY, radius, color):
self.x = x
self.y = y
self.velocityX = velocityX
self.velocityY = velocityY
self.radius = radius
self.color = color
self.lifetime = random.randrange(50, 100)
def draw(self, screen, camx, camy):
self.lifetime -= 1
self.x += self.velocityX
self.y += self.velocityY
pygame.draw.circle(screen, self.color, (self.x - camx, self.y - camy), self.radius)
class Background:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self, camx, camy):
screen.blit(groundModel, (self.x - camx - tileSize / 2, self.y - camy - tileSize / 2))
class Wall:
def __init__(self, x, y):
self.x = x
self.y = y
#Check if wall collides with smth
def collidesWith(self, other):
return pygame.Rect(self.x, self.y, tileSize, tileSize).colliderect(other.x, other.y, tileSize-16, tileSize)
def draw(self, camx, camy):
screen.blit(wallModel, (self.x - camx - tileSize / 2, self.y - camy - tileSize / 2))
class Bullet:
def __init__(self, x, y, velx, vely, isPlayer):
self.x = x
self.y = y
self.velx = velx
self.vely = vely
self.isPlayer = isPlayer
def collidesWith(self, other):
return pygame.Rect(self.x, self.y, tileSize - 16, tileSize - 16).colliderect(other.x, other.y, tileSize-36, tileSize-36)
def update(self):
self.x += self.velx
self.y += self.vely
for bullet in all_bullets:
for wall in walls:
if bullet.collidesWith(wall):
removed_bullets.append(bullet)
for i in removed_bullets:
if i in all_bullets:
all_bullets.remove(i)
def draw(self, camx, camy):
if (self.isPlayer):
screen.blit(pygame.transform.smoothscale(playerBullet, (16, 16)), (self.x - camx + 5, self.y - camy + 7))
else: screen.blit(pygame.transform.smoothscale(enemyBullet, (16, 16)), (self.x - camx + 5, self.y - camy + 7))
class slimeEnemy:
def __init__(self, x, y):
self.x = x
self.y = y
self.bulletSpeed = 1
self.aliveAnimations = [loadify("textures\slime_animation_0.png"),
loadify("textures\slime_animation_1.png"),
loadify("textures\slime_animation_2.png"),
loadify("textures\slime_animation_3.png"),]
self.animationsCount = 0
self.attackRate = 60
self.resetOffset = 0
self.SlimeHp = 7 + level * 2
self.slimeCollisionDmg = 1 + level/2
self.dmg = 1 + level / 2
self.isAlive = True
# self.isBoss = isBoss
#adding offset so the enemy doesnt move directly towards the player
self.offsetX = random.randrange(-150, 150)
self.offsetY = random.randrange(-150, 150)
def collidesWithAnything(self):
for wall in walls:
if wall.collidesWith(self):
return True
return False
def healthBar(self):
pygame.draw.rect(screen, (0, 255, 0), (self.x - camx - 20, self.y + 40 - camy, self.SlimeHp*10 + level*2, 7))
def collidesWith(self, other):
return pygame.Rect(self.x, self.y, tileSize-36, tileSize-36).colliderect(other.x, other.y, tileSize-36, tileSize-36)
def update(self):
# move enemy accordingly
if self.resetOffset == 0:
self.offsetX = random.randrange(-400, 400)
self.offsetY = random.randrange(-400, 400)
self.resetOffset = random.randrange(120, 150)
else: self.resetOffset -= 1
if player.x + self.offsetX > self.x:
self.x += 1
if self.collidesWithAnything():
self.x -= 1
elif player.x + self.offsetX < self.x:
self.x -= 1
if self.collidesWithAnything():
self.x += 1
if player.y + self.offsetY > self.y:
self.y += 1
if self.collidesWithAnything():
self.y -= 1
elif player.y + self.offsetY < self.y:
self.y -= 1
if self.collidesWithAnything():
self.y += 1
self.healthBar()
def attack(self):
for i in range(3):
angle = random.randrange(0, 360)
bulletSpeed_x = self.bulletSpeed * math.cos(angle) + random.uniform(-5, 5)
bulletSpeed_y = self.bulletSpeed * math.sin(angle) + random.uniform(-5, 5)
all_bullets.append(Bullet(self.x, self.y, bulletSpeed_x, bulletSpeed_y, False))
def drawAlive(self, camx, camy):
if self.animationsCount + 1 == 32:
self.animationsCount = 0
self.animationsCount += 1
if self.attackRate == 0:
self.attackRate = 60
self.attack()
self.attackRate -= 1
screen.blit(pygame.transform.scale(self.aliveAnimations[self.animationsCount// 8], (32, 30)), (self.x - camx, self.y - camy))
class Weapon:
def __init__(self, bulletSpeed, fireRate, bulletDmg):
self.shooting = False
self.bulletSpeed = bulletSpeed
self.fireRate = fireRate
self.bulletDmg = bulletDmg
self.energy = 100
self.i = 0
def handle_weapons(self, screen):
mouse_x, mouse_y = pygame.mouse.get_pos()
rel_x, rel_y = mouse_x - width/2, mouse_y - height/2
angle = (180/math.pi) * - math.atan2(rel_y, rel_x)
#draw crosshair
screen.blit(crosshair, (mouse_x, mouse_y+5))
#rotate and draw weapon accordingly
if angle > 90 or angle < -90:
player_weapon_copy = pygame.transform.rotate(pygame.transform.flip(weaponModel, True, False), angle - 180)
else:
player_weapon_copy = pygame.transform.rotate(weaponModel, angle)
screen.blit(player_weapon_copy, (width/2 +5 - int(player_weapon_copy.get_width()/2), height/2 + 15 - int(player_weapon_copy.get_height()/2)))
def Shooting(self):
if self.shooting:
#calculates the angles the bullet should travel :/
if self.i % self.fireRate == 0:
if (self.energy == 0):
pass
else:
mouse_x, mouse_y = pygame.mouse.get_pos()
distance_x = mouse_x - width/2
distance_y = mouse_y - height/2
angle = math.atan2(distance_y, distance_x)
bulletSpeed_x = self.bulletSpeed * math.cos(angle)
bulletSpeed_y = self.bulletSpeed * math.sin(angle)
all_bullets.append(Bullet(player.x, player.y, bulletSpeed_x, bulletSpeed_y, True))
self.energy -= 1
self.i += 1
class Player:
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
self.leftPr = False
self.rightPr = False
self.downPr = False
self.upPr = False
self.speed = 4
self.health = 5
self.maxHp = 5
self.animationsCount = 0
def healthBar(self):
pygame.draw.rect(screen, (255, 0, 0), (20, 25, 200, 10))
pygame.draw.rect(screen, (0, 255, 0), (20, 25, self.health*40, 10))
def energyBar(self):
pygame.draw.rect(screen, (255, 0, 0), (20, 55, 200, 10))
pygame.draw.rect(screen, (48, 117, 255), (20, 55, weapon.energy*2, 10))
def collidesWithAnything(self):
for wall in walls:
if wall.collidesWith(self):
return True
return False
def update(self):
if self.leftPr and not self.rightPr:
self.x -= self.speed
if self.collidesWithAnything():
self.x += self.speed
if self.rightPr and not self.leftPr:
self.x += self.speed
if self.collidesWithAnything():
self.x -= self.speed
if self.upPr and not self.downPr:
self.y -= self.speed
if self.collidesWithAnything():
self.y += self.speed
# revert if collision
if self.downPr and not self.upPr:
self.y += self.speed
if self.collidesWithAnything():
self.y -= self.speed
# check for enemy colisions
def animations(self):
if self.animationsCount + 1 >= 36:
self.animationsCount = 0
if self.rightPr:
screen.blit(pygame.transform.scale(playerWalkAnimR[self.animationsCount//12],(64, 64)), (width/2 - 40, height/2 - 30))
elif self.leftPr:
screen.blit(pygame.transform.scale(playerWalkAnimL[self.animationsCount//12],(64, 64)), (width/2 - 40, height/2 - 30))
else:
screen.blit(pygame.transform.scale(playerWalkAnimR[0],(64, 64)), (width/2 - 40, height/2 - 30))
self.animationsCount += 1
weapon = Weapon(10, 20, 2)
player = Player(1, 0)
#Loads map from file
def loadMapFromFile(path):
walls.clear()
backgrounds.clear()
enemies.clear()
with open(path, "r") as f:
y = 0
enemyLocations = []
# bossLocations = []
for line in f.readlines():
x = 0
for char in line:
if char != ' ' and char != "\n":
backgrounds.append(Background(x * tileSize, y * tileSize))
if char == '#':
walls.append(Wall(x * tileSize, y * tileSize))
elif char == 'p' or char == 'P':
player.x = x * tileSize
player.y = y * tileSize
elif char == 'e' or char == 'E':
if random.randint(1, 100) <= 40:
enemyLocations.append((x * tileSize, y * tileSize))
# elif char == 'b' or char == 'B':
# if random.randint(1, 100) <= 10:
# bossLocations.append((x * tileSize, y * tileSize, "True"))
x += 1
y += 1
for enemyL in enemyLocations:
enemies.append(slimeEnemy(*enemyL))
# for enemyL in bossLocations:
# enemies.append(slimeEnemy(*enemyL, "True"))
def gameOverScreen():
pygame.font.init()
font = pygame.font.Font('arial.ttf', 32)
text = font.render('GAME OVER', True, (255, 0, 0), (0, 0, 0))
text.set_colorkey((0, 0, 0))
screen.blit(text, (width/2-80,height/2-40))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
loadMapFromFile('maps/Map0.txt')
hitCooldown = 75
cooldown = 600
#running loop
gameOver = False
running = True
while running:
if gameOver:
gameOverScreen()
pass
else:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player.upPr = True
if event.key == pygame.K_s:
player.downPr = True
if event.key == pygame.K_d:
player.rightPr = True
if event.key == pygame.K_a:
player.leftPr = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
player.upPr = False
if event.key == pygame.K_s:
player.downPr = False
if event.key == pygame.K_d:
player.rightPr = False
if event.key == pygame.K_a:
player.leftPr = False
if event.type == pygame.MOUSEBUTTONDOWN:
weapon.shooting = True
if event.type == pygame.MOUSEBUTTONUP:
weapon.shooting = False
# updating
camx = player.x - width / 2
camy = player.y - height / 2
screen.fill((0, 0, 0))
player.update()
#check if slime got hit
for bullet in all_bullets:
bullet.update()
for enemy in enemies:
if enemy.collidesWith(player):
if hitCooldown < 0:
hitCooldown = 75
player.health -= enemy.slimeCollisionDmg
if player.health <= 0:
gameOver = True
elif enemy.collidesWith(bullet) and bullet.isPlayer:
removed_bullets.append(bullet)
for i in range(10):
hitParticles.append(Particle(enemy.x, enemy.y, random.randrange(-5, 5)/10, random.randrange(-5, 5)/10, 4, (108, 216, 32)))
enemy.SlimeHp -= weapon.bulletDmg
if enemy.SlimeHp <= 0:
enemy.isAlive = False
if player.health >= player.maxHp:
player.health = player.maxHp
else:
player.health += 1
if weapon.energy >= 100:
weapon.energy = 100
else:
weapon.energy += 2
if bullet.collidesWith(player) and not bullet.isPlayer:
if hitCooldown < 0:
hitCooldown = 75
player.health -= enemy.dmg
if player.health <= 0:
gameOver = True
removed_bullets.append(bullet)
for bg in backgrounds:
bg.draw(camx, camy)
for wall in walls:
wall.draw(camx, camy)
# update all other entities
#draw bullet
for bullet in all_bullets:
bullet.draw(camx, camy)
# slime animations and remove dead slimes
for enemy in enemies:
enemy.update()
if enemy.isAlive:
enemy.drawAlive(camx, camy)
if not enemy.isAlive:
enemies.remove(enemy)
# draw particles
for particle in hitParticles:
if particle.lifetime > 0:
particle.draw(screen, camx, camy)
else:
hitParticles.pop(hitParticles.index(particle))
player.animations()
weapon.handle_weapons(screen)
weapon.Shooting()
player.healthBar()
player.energyBar()
if len(enemies) == 0:
if cooldown <= 0:
cooldown = 600
loadMapFromFile("maps\Map{0}.txt".format(level+1))
level+=1
hitCooldown -= 1
cooldown -= 1
# finally update screen
pygame.display.update()
clock.tick(60)
I know it is written really badly but I'm learning. The game is really laggy and I was wondering how I can make it run faster and smoother. Also is the lag created from the many calculations or am I just dumb? The lag comes when there are a lot of enemies on the map and they shoot at the same time. Can I fix the lag by making all the enemies shoot in different times? The game is for a school project.
I think your biggest issue is this:
class Bullet:
[ ... ]
def update(self):
self.x += self.velx
self.y += self.vely
for bullet in all_bullets: # <-- HERE
for wall in walls:
if bullet.collidesWith(wall):
removed_bullets.append(bullet)
for i in removed_bullets:
if i in all_bullets:
all_bullets.remove(i)
Then in the main loop:
#check if slime got hit
for bullet in all_bullets: # <-- AGAIN
bullet.update()
The code is iterating through the bullets many more times than is necessary. By the time all your bullet objects are updated, they have been processed /N/ * /N/ times (i.e.: N-squared). So as you get more any more bullets, this square grows catastrophically.
Try changing your Bullet.update() to only check itself. This will probably fix your lag issues - or at least help a lot. It will also "correct" your object encapsulation. A single Bullet has no business knowing about all the others, let alone checking collisions on their behalf.
class Bullet:
[ ... ]
def update(self):
self.x += self.velx
self.y += self.vely
for wall in walls:
if self.collidesWith(wall):
all_bullets.remove( self )
break
If you have any more N-squared loops like this, it will give the best speedup reworking them first.

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()

TypeError: argument 1 must be pygame.Surface, not None

I am making a game similar to Galaga in a computer class I am in. I am having trouble with collisions and cannot get things to disappear without errors. I want to be able to have lasers disappear on collision with enemies and enemies disappear after 10 or so hits. I do not understand the error presented or how I can fix the problem.
Thanks
Code:
import pygame, sys, pygame.mixer
from sys import exit
import random
from pygame import *
import time
h = 700
w = 700
m = 0
h = 0
score = 0
screen = pygame.display.set_mode((w, h))
clock = pygame.time.Clock()
done = False
x = 400
y = 400
white = (255, 255, 255)
background = pygame.image.load('water.png')
pygame.init()
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
self.width = 100
self.height = 100
self.velocity = 0
self.images = pygame.image.load('speeder.png')
self.numImages = 6
self.cImage = 0
def update(self):
self.speedx = 0
self.speedy = 0
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]:
self.speedx -= 8
if pressed[pygame.K_RIGHT]:
self.speedx += 8
self.x += self.speedx
if pressed[pygame.K_DOWN]:
self.cImage = 0
self.y += 4
if pressed[pygame.K_UP] and (self.cImage <= self.numImages - 1):
self.cImage += 1
self.y -= 10
if self.cImage >= 5:
self.cImage = 5
def render(self, screen):
screen.blit(self.images, (self.x, self.y), (self.cImage * self.width, 0, self.width, self.height))
class Enemy1:
def __init__(self, x, y):
self.x = x
self.y = y
self.width = 128
self.height = 128
self.velocity = 0
self.images = pygame.image.load('enemy1.png')
self.numImages = 7
self.cImage = 0
self.z = 0
self.j = 0
self.rect = self.images.get_rect()
def update(self):
self.j += 1
self.speedx = 0
self.speedy = 0
self.y += 1
if self.z <= 100:
self.x += random.randint(1, 2)
elif self.z > 100 and self.z < 200:
self.x += random.randint(-2, -1)
#self.cImage += 1
if self.z >= 200:
self.z = 0
if self.j % 10 == 0:
self.cImage += 1
if self.cImage == 7:
self.cImage = 0
self.z += random.randint(0, 5)
def render(self, screen):
screen.blit(self.images, (self.x, self.y), (self.cImage * self.width, 0, self.width, self.height))
class Laser(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('lazer.png')
self.rect = self.image.get_rect()
self.m = 0
def update(self):
self.m += 1
if (self.m % 5) != 0 or self.m % 4 != 1:
self.rect.y -= 13
def kill(self):
self.image = None
class RLaser(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('lazer.png')
self.rect = self.image.get_rect()
self.m = 0
def update(self):
self.m += 1
if (self.m % 5) != 0 or self.m % 4 != 1:
self.rect.y += 13
class Boss(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.width = 50
self.height = 100
self.velocity = 0
self.images = pygame.image.load('boss.png')
self.numImages = 5
self.cImage = 0
self.z = 0
self.rect = self.images.get_rect()
def update(self):
self.speedx = 0
self.speedy = 0
self.y += 1
if self.z <= 100:
self.x += random.randint(1, 2)
elif self.z > 100 and self.z < 200:
self.x += random.randint(-2, -1)
self.cImage += 1
if self.z >= 200:
self.z = 0
if self.cImage == 5:
self.cImage = 4
self.z += random.randint(0, 5)
def render(self, screen):
screen.blit(self.images, (self.x, self.y), (self.cImage * self.width, 0, self.width, self.height))
pygame.init()
all_sprites_list = pygame.sprite.Group()
laser_list = pygame.sprite.Group()
#enemy1blast_list = pygame.sprite.Group()
player = Player(400, 590)
boss = Boss(300, 100)
enemy = Enemy1(100, 50)
j = 0
while not done:
j += 1
screen.blit(background, (0, (-690 * 2) + j))
screen.blit(background, (0, -690 + j))
screen.blit(background, (0, j))
screen.blit(background, (0, 690 + j))
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pressed = pygame.key.get_pressed()
#j += 1
#if j % 10 == 0:
# enemy1blaster = Enemy1Blast()
# enemy1blaster.rect.x = enemy.x
# enemy1blaster.rect.y = enemy.y
#all_sprites_list.add(enemy1blaster)
#enemy1blast_list.add(enemy1blaster)
if pressed[pygame.K_SPACE]:
m += 2
if (m % 4) != 0:
laser = Laser()
laser.rect.x = (player.x + 14)
laser.rect.y = (player.y - 6)
all_sprites_list.add(laser)
laser_list.add(laser)
for laser in laser_list:
if laser.rect.x >= enemy.rect.x or laser.rect.x <= enemy.rect.x and laser.rect.y >= enemy.rect.y or laser.rect.y <= enemy.rect.y:
laser.kill()
if pressed[pygame.K_SPACE]:
h += 2
if (h % 4) != 0:
l = Laser()
l.rect.x = (player.x + 61)
l.rect.y = (player.y - 6)
all_sprites_list.add(l)
laser_list.add(l)
lsound = pygame.mixer.Sound("Laser.wav")
lsound.play()
if j % 20 == 0 and boss.y <= 700:
bl = RLaser()
bl2 = RLaser()
bl.rect.x = (boss.x + 1)
bl.rect.y = (boss.y + 50)
bl2.rect.x = (boss.x + 19)
bl2.rect.y = (boss.y + 50)
all_sprites_list.add(bl)
all_sprites_list.add(bl2)
laser_list.add(bl)
laser_list.add(bl2)
blsound = pygame.mixer.Sound("Laser.wav")
blsound.play()
#if bool(bl) == True:
#bl.rect.y += 26
all_sprites_list.update()
#if bool(bl) == True:
#bl.rect.y += 26
#for laser in laser_list:
# if pygame.sprite.collide_rect(boss, laser):
# laser.kill()
# print "asdfasdf"
if player.y <= 200:
player.y = 202
if player.y >= 633:
player.y = 631
if player.x >= 623:
player.x = 621
if player.x <= -30:
player.x = -28
#Collision_Detector(laser, l, boss)
boss.render(screen)
boss.update()
enemy.render(screen)
enemy.update()
player.render(screen)
player.update()
boss_laser_hlist = pygame.sprite.spritecollide(boss, laser_list, False)
enemy_laser_hlist = pygame.sprite.spritecollide(enemy, laser_list, False)
for laser in enemy_laser_hlist:
score += 1
for laser in boss_laser_hlist:
score += 1
print score
all_sprites_list.draw(screen)
pygame.display.update()
clock.tick(30)
pygame.quit()

Categories

Resources