Update sprite position using arrow keys in pygame - python

I'm trying to make a sprite move when the arrow keys are pressed (just left and right) but nothing is happening. I've been trying to get this to work but I wasn't able to do it. The sprite gets drawn but it doesn't move, it just stays there. Here's the code:
import pygame
pygame.init()
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.sprites = []
self.sprites.append(pygame.image.load('Sprites/Player/running1.png'))
self.sprites.append(pygame.image.load('Sprites/Player/running2.png'))
self.sprites.append(pygame.image.load('Sprites/Player/running3.png'))
self.sprites.append(pygame.image.load('Sprites/Player/running4.png'))
self.sprites.append(pygame.image.load('Sprites/Player/running5.png'))
self.sprites.append(pygame.image.load('Sprites/Player/running6.png'))
self.current_sprite = 0
self.image = self.sprites[self.current_sprite]
self.rect = self.image.get_rect()
self.rect.topleft = [x,y]
self.x = self.rect.x
self.y = self.rect.y
self.walking = False
self.vel = 5
def walk(self):
self.walking = True
def update(self):
if self.walking == True:
self.current_sprite += 1
if self.current_sprite >= len(self.sprites):
self.current_sprite = 0
self.walking = False
self.image = self.sprites[self.current_sprite]
sWidth = 800
sHeight = 400
screen = pygame.display.set_mode((sWidth,sHeight))
pygame.display.set_caption("Game")
background = pygame.image.load('Sprites/Background/bg1.jpg')
allSprites = pygame.sprite.Group()
player = Player(300,230)
allSprites.add(player)
clock = pygame.time.Clock()
keepGoing = True
while keepGoing:
clock.tick(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoing = False
Now, I want to have it move whenever I hit an arrow key.
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= player.vel
elif keys[pygame.K_RIGHT]:
player.x += player.vel
else:
player.walking = False
screen.blit(background, (0,0))
allSprites.draw(background)
allSprites.update()
pygame.display.flip()

The position of the player is stored in self.rect. The rect attribute is used by pygame.sprite.Group.draw to draw the Sprite. Therefore you must update player.rect.x and player.rect.y rather than player.x and player.y. You don't need the attributes x and y at all:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.rect.x -= player.vel
elif keys[pygame.K_RIGHT]:
player.rect.x += player.vel

Related

Bullet movement not working as expected when player sprite is moving

My game is a top down shooter. When the player is stationary and is shooting in any direction, the bullet goes in the same direction as the mouse. However, when I move diagonally whilst shooting the bullet is no longer in the direction of the mouse position. So basically it works when the player is stationary, but not when I'm moving.
Edit: I will keep trying to fix this but here is a video to better understand the issue https://imgur.com/a/8QRr1PO
Here is the code:
import pygame
from sys import exit
import math
pygame.init()
# window and text
WIDTH = 1280
HEIGHT = 720
FPS = 60
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Shooting problem demo')
game_font = pygame.font.Font('freesansbold.ttf', 50)
clock = pygame.time.Clock()
# loads imgs
background = pygame.image.load("background/gamemap.png").convert()
plain_bg = pygame.image.load("background/plain_bg.png").convert()
bullet_img = pygame.image.load("bullets/bluebullet.png").convert_alpha()
class Player(pygame.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = pygame.image.load("handgun/move/survivor-move_handgun_0.png").convert_alpha()
self.image = pygame.transform.rotozoom(self.image, 0, 0.35)
self.base_player_image = self.image
self.pos = pos
self.base_player_rect = self.base_player_image.get_rect(center = pos)
self.rect = self.base_player_rect.copy()
self.player_speed = 10 # was 4
self.shoot = False
self.shoot_cooldown = 0
def player_turning(self):
self.mouse_coords = pygame.mouse.get_pos()
self.x_change_mouse_player = (self.mouse_coords[0] - (WIDTH // 2))
self.y_change_mouse_player = (self.mouse_coords[1] - (HEIGHT // 2))
self.angle = int(math.degrees(math.atan2(self.y_change_mouse_player, self.x_change_mouse_player)))
self.angle = (self.angle) % 360
self.image = pygame.transform.rotate(self.base_player_image, -self.angle)
self.rect = self.image.get_rect(center=self.base_player_rect.center)
def player_input(self):
self.velocity_x = 0
self.velocity_y = 0
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.velocity_y = -self.player_speed
if keys[pygame.K_s]:
self.velocity_y = self.player_speed
if keys[pygame.K_d]:
self.velocity_x = self.player_speed
if keys[pygame.K_a]:
self.velocity_x = -self.player_speed
if self.velocity_x != 0 and self.velocity_y != 0: # moving diagonally
self.velocity_x /= math.sqrt(2)
self.velocity_y /= math.sqrt(2)
if keys[pygame.K_SPACE]:
self.shoot = True
self.is_shooting()
else:
self.shoot = False
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
self.shoot = False
def move(self):
self.base_player_rect.centerx += self.velocity_x
self.base_player_rect.centery += self.velocity_y
self.rect.center = self.base_player_rect.center
def is_shooting(self):
if self.shoot_cooldown == 0 and self.shoot:
self.bullet = Bullet(self.base_player_rect.centerx, self.base_player_rect.centery, self.angle)
self.shoot_cooldown = 20
bullet_group.add(self.bullet)
all_sprites_group.add(self.bullet)
def update(self):
self.player_turning()
self.player_input()
self.move()
if self.shoot_cooldown > 0:
self.shoot_cooldown -= 1
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, angle):
super().__init__()
self.image = bullet_img
self.image = pygame.transform.rotozoom(self.image, 0, 0.1)
self.image.set_colorkey((0,0,0))
self.rect = self.image.get_rect()
self.rect.center = (x, y)
self.x = x
self.y = y
self.speed = 10
self.angle = angle
self.x_vel = math.cos(self.angle * (2*math.pi/360)) * self.speed
self.y_vel = math.sin(self.angle * (2*math.pi/360)) * self.speed
self.bullet_lifetime = 750
self.spawn_time = pygame.time.get_ticks()
def bullet_movement(self):
self.x += self.x_vel
self.y += self.y_vel
self.rect.x = int(self.x)
self.rect.y = int(self.y)
if pygame.time.get_ticks() - self.spawn_time > self.bullet_lifetime:
self.kill()
def update(self):
self.bullet_movement()
class Camera(pygame.sprite.Group):
def __init__(self):
super().__init__()
self.offset = pygame.math.Vector2()
self.floor_rect = background.get_rect(topleft = (0,0))
def custom_draw(self):
self.offset.x = player.rect.centerx - (WIDTH // 2)
self.offset.y = player.rect.centery - (HEIGHT // 2)
#draw the floor
floor_offset_pos = self.floor_rect.topleft - self.offset
screen.blit(background, floor_offset_pos)
for sprite in all_sprites_group:
offset_pos = sprite.rect.topleft - self.offset
screen.blit(sprite.image, offset_pos)
# Groups
all_sprites_group = pygame.sprite.Group()
player = Player((900,900))
all_sprites_group.add(player)
bullet_group = pygame.sprite.Group()
camera = Camera()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.blit(plain_bg, (0,0))
camera.custom_draw()
all_sprites_group.update()
pygame.display.update()
clock.tick(FPS)
Actually, there is no problem at all. It is just an optical illusion. The projectile does not move relative to the player, but relative to the camera. The player is always in the center of the screen, because the player doesn't move, but the camera does. When the camera moves, all objects move with the camera.
For example, if you shoot a bullet to the right and move the player up, it will look like the bullet is moving diagonally to the right and down. To the right because it changes position, to the right and down because the player moves upwards.
To illustrate this, I reduced the speed of the player (self.player_speed = 2) and the speed of the bullet (self.speed = 4) and drew the scene on a checkered background:
if event.type == pygame.KEYUP: only makes sens in the event loop, but not in player_input. Shooting only one bullet at once just needs another condition (and not self.shoot):
if keys[pygame.K_SPACE] and not self.shoot:
self.shoot = True
self.is_shooting()
else:
self.shoot = False

Why isn't my image changing with the sprite?

I've made it so that the image for the Frisk sprite is determined by the player input via the arrow keys in player_input(self). Also, frisk_anim(self) is meant to animate the sprite. However, the sprite isn't being animated and the image isn't being changed via the player input. Any idea why this could be?
import pygame
pygame.init()
screen = pygame.display.set_mode((640,480))
pygame.display.set_caption("UNDERRUNE")
clock = pygame.time.Clock()
keys_pressed = pygame.key.get_pressed() #updates which keys are being pressed
class Frisk(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
friskd1 = pygame.transform.scale2x(pygame.image.load('assets/frisk_d1.png').convert_alpha())
friskd2 = pygame.transform.scale2x(pygame.image.load('assets/frisk_d2.png').convert_alpha())
friskd3 = pygame.transform.scale2x(pygame.image.load('assets/frisk_d3.png').convert_alpha())
friskd4 = pygame.transform.scale2x(pygame.image.load('assets/frisk_d4.png').convert_alpha())
self.frisk_d = [friskd1,friskd2,friskd3,friskd4]
friskr1 = pygame.transform.scale2x(pygame.image.load('assets/frisk_r1.png').convert_alpha())
friskr2 = pygame.image.load('assets/frisk_r2.png').convert_alpha()
self.frisk_r = [friskr1,friskr2,friskr1,friskr2]
frisku1 = pygame.transform.scale2x(pygame.image.load('assets/frisk_u1.png').convert_alpha())
frisku2 = pygame.image.load('assets/frisk_u2.png').convert_alpha()
frisku3 = pygame.image.load('assets/frisk_u3.png').convert_alpha()
frisku4 = pygame.image.load('assets/frisk_u4.png').convert_alpha()
self.frisk_u = [frisku1,frisku2,frisku3,frisku4]
friskl1 = pygame.transform.scale2x(pygame.image.load('assets/frisk_l1.png').convert_alpha())
friskl2 = pygame.image.load('assets/frisk_l2.png').convert_alpha()
self.frisk_l = [friskl1,friskl2,friskl1,friskl2]
self.frisk_index = 0
self.walkframe = 0
self.frisk_surf = [self.frisk_d[self.walkframe],self.frisk_r[self.walkframe],self.frisk_u[self.walkframe],self.frisk_l[self.walkframe]]
self.image = self.frisk_surf
self.image = self.frisk_surf[self.frisk_index]
self.rect = self.image.get_rect(center = (320,240))
self.frisk_movedown = False
self.vel = 5
def player_input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
self.rect.y += self.vel
self.frisk_surf = 0
if keys[pygame.K_RIGHT]:
self.rect.x += self.vel
self.frisk_surf = 1
if keys[pygame.K_UP]:
self.rect.y -= self.vel
self.frisk_surf = 2
if keys[pygame.K_LEFT]:
self.rect.x -= self.vel
self.frisk_surf = 3
if self.frisk_surf == 1:
print("1")
def frisk_anim(self):
self.walkframe += 0.25
if self.walkframe == 4:
self.walkframe = 0
def update(self):
self.player_input()
self.frisk_anim()
# GROUPS
frisk = pygame.sprite.GroupSingle() # group contains sprite
frisk.add(Frisk())
# GAME LOOP
while True:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
frisk.draw(screen)
frisk.update()
pygame.display.update() # updates the display surface
clock.tick(60) # tells pygame that this while True loop shouldn't run faster then 60 fps
You need to update the image attribute when changing walkframe or frisk_surf:
class Frisk(pygame.sprite.Sprite):
# [...]
def update(self):
self.player_input()
self.frisk_anim()
self.frisk_surf = [self.frisk_d[self.walkframe],self.frisk_r[self.walkframe],self.frisk_u[self.walkframe],self.frisk_l[self.walkframe]]
self.image = self.frisk_surf

I am having trouble coding my collision check function for my fps game. How can I write my collision function?

I am stuck on how to write my collision function in my player class. Also should I put my collision check function in my player class or should it be in my bullet class? I honestly don't know. I mean common sense says my bullet should have the collision check function in it, just because I want the top of my bullet checking if it hits a falling cement block sprite, but I don't know.... I would appreciate an answer on how to code my collision function. This would really help me out. My collision function is right below my shoot function in my player class.
My code:
import pygame
pygame.init()
#screen settings
WIDTH = 1000
HEIGHT = 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("AutoPilot")
screen.fill((255, 255, 255))
#fps
FPS = 120
clock = pygame.time.Clock()
#load images
bg = pygame.image.load('background/street.png').convert_alpha() # background
bullets = pygame.image.load('car/bullet.png').convert_alpha()
debris_img = pygame.image.load('debris/cement.png')
#define game variables
shoot = False
#player class
class Player(pygame.sprite.Sprite):
def __init__(self, scale, speed):
pygame.sprite.Sprite.__init__(self)
self.bullet = pygame.image.load('car/bullet.png').convert_alpha()
self.bullet_list = []
self.speed = speed
#self.x = x
#self.y = y
self.moving = True
self.frame = 0
self.flip = False
self.direction = 0
#load car
self.images = []
img = pygame.image.load('car/car.png').convert_alpha()
img = pygame.transform.scale(img, (int(img.get_width()) * scale, (int(img.get_height()) * scale)))
self.images.append(img)
self.image = self.images[0]
self.rect = self.image.get_rect()
self.update_time = pygame.time.get_ticks()
self.movingLeft = False
self.movingRight = False
self.rect.x = 465
self.rect.y = 325
#draw car to screen
def draw(self):
screen.blit(self.image, (self.rect.centerx, self.rect.centery))
#move car
def move(self):
#reset the movement variables
dx = 0
dy = 0
#moving variables
if self.movingLeft and self.rect.x > 33:
dx -= self.speed
self.flip = True
self.direction = -1
if self.movingRight and self.rect.x < 900:
dx += self.speed
self.flip = False
self.direction = 1
#update rectangle position
self.rect.x += dx
self.rect.y += dy
#shoot
def shoot(self):
bullet = Bullet(self.rect.centerx + 18, self.rect.y + 30, self.direction)
bullet_group.add(bullet)
#def collision(self):
#write code here
#bullet class
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, direction):
pygame.sprite.Sprite.__init__(self)
self.speed = 5
self.image = bullets
self.rect = self.image.get_rect()
self.rect.center = (x,y)
self.direction = direction
def update(self):
self.rect.centery -= self.speed
#check if bullet has gone off screen
if self.rect.top < 1:
self.kill()
#debris class
class Debris(pygame.sprite.Sprite):
def __init__(self, x, y, scale, speed):
pygame.sprite.Sprite.__init__(self)
self.scale = scale
self.x = x
self.y = y
self.speed = speed
self.vy = 0
self.on_ground = True
self.move = True
self.health = 4
self.max_health = self.health
self.alive = True
#load debris
self.image = debris_img
self.rect = self.image.get_rect()
self.rect.center = (x,y)
######################CAR/DEBRIS##########################
player = Player(1,5)
debris = Debris(300,15,1,5)
##########################################################
#groups
bullet_group = pygame.sprite.Group()
debris_group = pygame.sprite.Group()
debris_group.add(debris)
#game runs here
run = True
while run:
#draw street
screen.blit(bg, [0, 0])
#update groups
bullet_group.update()
bullet_group.draw(screen)
debris_group.update()
debris_group.draw(screen)
#draw car
player.draw()
player.move()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#check if key is down
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.key == pygame.K_a:
player.movingLeft = True
if event.key == pygame.K_d:
player.movingRight = True
if event.key == pygame.K_SPACE:
player.shoot()
shoot = True
#check if key is up
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player.movingLeft = False
if event.key == pygame.K_d:
player.movingRight = False
#update the display
pygame.display.update()
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
I suggest reading How do I detect collision in pygame?. Use pygame.sprite.spritecollide() for the collision detection. Set the dokill argument True. So the bullets gat automatically destroyed.
The following code is base on one of your previous questions: Check collision of bullet sprite hitting cement block sprite
class Car(pygame.sprite.Sprite):
# [...]
def collision(self, debris_group):
for debris in debris_group:
if pygame.sprite.spritecollide(debris, bullet_group, True):
debris.health -= 1
if debris.health <= 0:
debris.kill()

Im stuck on doing an explosion animation for my cement block sprites [duplicate]

This question already exists:
I want to do an explosion animation. I have 4 png files number 0 - 3. In my debris class I loaded them into an image list using a for loop [duplicate]
Closed 1 year ago.
I want to do an explosion animation. I have 4 png files number 0 - 3. In my debris class I loaded them into an image list using a for loop. Then I made an explosion function but when I load my pygame windows and start shooting my cement block sprites, my cement block sprites disappear which is fine but they don't do the exploding animation I want. How can I fix this problem. Would appreciate the help.
My code:
import random
import pygame
import pygame.freetype
pygame.init()
#screen settings
WIDTH = 1000
HEIGHT = 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("AutoPilot")
screen.fill((255, 255, 255))
#fps
FPS = 120
clock = pygame.time.Clock()
#load images
bg = pygame.image.load('background/street.png').convert_alpha() # background
bullets = pygame.image.load('car/bullet.png').convert_alpha()
debris_img = pygame.image.load('debris/cement.png')
#define game variables
shoot = False
#player class
class Player(pygame.sprite.Sprite):
def __init__(self, scale, speed):
pygame.sprite.Sprite.__init__(self)
self.bullet = pygame.image.load('car/bullet.png').convert_alpha()
self.bullet_list = []
self.speed = speed
#self.x = x
#self.y = y
self.moving = True
self.frame = 0
self.flip = False
self.direction = 0
self.score = 0
#load car
self.images = []
img = pygame.image.load('car/car.png').convert_alpha()
img = pygame.transform.scale(img, (int(img.get_width()) * scale, (int(img.get_height()) * scale)))
self.images.append(img)
self.image = self.images[0]
self.rect = self.image.get_rect()
self.update_time = pygame.time.get_ticks()
self.movingLeft = False
self.movingRight = False
self.rect.x = 465
self.rect.y = 325
#draw car to screen
def draw(self):
screen.blit(self.image, (self.rect.centerx, self.rect.centery))
#move car
def move(self):
#reset the movement variables
dx = 0
dy = 0
#moving variables
if self.movingLeft and self.rect.x > 33:
dx -= self.speed
self.flip = True
self.direction = -1
if self.movingRight and self.rect.x < 900:
dx += self.speed
self.flip = False
self.direction = 1
#update rectangle position
self.rect.x += dx
self.rect.y += dy
#shoot
def shoot(self):
bullet = Bullet(self.rect.centerx + 18, self.rect.y + 30, self.direction)
bullet_group.add(bullet)
#check collision
def collision(self, debris_group):
for debris in debris_group:
if pygame.sprite.spritecollide(debris, bullet_group, True):
debris.health -= 1
if debris.health <= 0:
self.score += 1
debris.kill()
#player stats
def stats(self):
myfont = pygame.font.SysFont('comicsans', 30)
scoretext = myfont.render("Score: " + str(self.score), 1, (0,0,0))
screen.blit(scoretext, (100,10))
#bullet class
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y, direction):
pygame.sprite.Sprite.__init__(self)
self.speed = 5
self.image = bullets
self.rect = self.image.get_rect()
self.rect.center = (x,y)
self.direction = direction
def update(self):
self.rect.centery -= self.speed
#check if bullet has gone off screen
if self.rect.centery < 1:
self.kill()
#debris class
class Debris(pygame.sprite.Sprite):
def __init__(self,scale,speed):
pygame.sprite.Sprite.__init__(self)
self.scale = scale
self.x = random.randrange(100,800)
self.speed_y = 10
self.y = 15
self.speed = speed
self.vy = 0
self.on_ground = True
self.move = True
self.health = 4
self.max_health = self.health
self.alive = True
self.velocity = random.randrange(1,2)
self.speed_x = random.randrange(-3,3)
self.moving_down = True
#load debris
self.image = debris_img
self.rect = self.image.get_rect()
self.rect.x = random.randrange(100, 800)
self.rect.y = random.randrange(-150, -100)
self.rect.center = (self.x,self.y)
#load explosion
self.images = []
for i in range(4):
self.images.append(pygame.image.load(f'explosion/{i}.png'))
self.index = 0
self.img = self.images[self.index]
#spawn new debris
def spawn_new_debris(self):
self.rect.x = random.randrange(100, 800)
self.rect.y = random.randrange(-150, -100)
self.velocity = random.randrange(1, 2)
self.speed_x = random.randrange(-3, 3)
#respawn debris when they go of the screen
def boundaries(self):
if self.rect.left > WIDTH + 10 or self.rect.right < -10 or self.rect.top > HEIGHT + 10:
self.spawn_new_debris()
#update image
def update(self):
self.rect.y += self.velocity
self.rect.x += self.speed_x
self.boundaries()
#make debris fall down
def falldown(self):
self.rect.centery += self.velocity
if self.moving_down and self.rect.y > 350:
self.kill()
#explosion
def explode(self):
if self.max_health <= 0:
self.index += 1
if self.index >= len(self.images):
self.index = 0
self.img = self.images[self.index]
######################CAR/DEBRIS##########################
player = Player(1,5)
##########################################################
#groups
bullet_group = pygame.sprite.Group()
debris_group = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
for i in range(50):
d = Debris(1,5)
debris_group.add(d)
all_sprites.add(d)
#game runs here
run = True
while run:
#draw street
screen.blit(bg, [0, 0])
#update groups
bullet_group.update()
bullet_group.draw(screen)
debris_group.update()
debris_group.draw(screen)
#draw car
player.draw()
player.move()
player.collision(debris_group)
player.stats()
#update all sprites
all_sprites.update()
all_sprites.draw(screen)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#check if key is down
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.key == pygame.K_a:
player.movingLeft = True
if event.key == pygame.K_d:
player.movingRight = True
if event.key == pygame.K_SPACE:
player.shoot()
shoot = True
#check if key is up
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player.movingLeft = False
if event.key == pygame.K_d:
player.movingRight = False
#update the display
pygame.display.update()
pygame.display.flip()
clock.tick(FPS)
pygame.quit()

Pygame - Getting enemy sprites to move towards player

As of currently the enemy sprites just spawn on the axis, and "move" with the player which is actually a scrolling background, and I'd like for the enemies to move only along the X axis so it doesn't destroy the immersion.
I'd also like for the sprites to spawn "Off the map" and whenever the map scrolls towards them they move towards the players set X axis? I think that would keep things simple, but isn't really the question at hand right now.
The current code I was trying to get working for the movement was :
def move_towards_player(self, player):
# Find direction vector (dx, dy) between enemy and player.
dx, dy = player.rect.x - self.rect.x, player.rect.y - self.rect.y
dist = math.hypot (dx, dy)
dx, dy = dx / dist, dy / dist # Normalize
# Move along this normalized vector towards the player
self.rect.x += dx * self.speed
self.rect.y += dy * self.speed
But it wouldn't work, this is with importing the math module.
(I know I don't need the y movements just wanted to get it working first)
Here is the rest of the code --
Zombie.py:
import pygame
from pygame.locals import *
import random
import math
class ZombieEnemy(pygame.sprite.Sprite):
def __init__(self, x=300, y=360):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('images/zombie.png')
self.rect = self.image.get_rect()
self.rect.center = (x, y)
all_zombies = pygame.sprite.Group()
for i in range( 50 ):
new_x = random.randrange( 0, 10000) # random x-position
# new_y = random.randrange( 0, ) # random y-position
all_zombies.add(ZombieEnemy(new_x)) # create, and add to group
I wasn't sure if I should create a whole new class for enemy movement, or what my partner is currently working on the Player, and getting the sprite animations and movement working right.
But here is the main code I have as of now:
import pygame
from Zombie import *
import math
from pygame.locals import *
pygame.init()
​
win = pygame.display.set_mode((900,567))
​
pygame.display.set_caption("Power Rangers ZOMBIES")
​
walkRight = [pygame.image.load('images/walk1.png'), pygame.image.load('images/walk2.png'), pygame.image.load('images/walk3.png'), pygame.image.load('images/walk4.png'), pygame.image.load('images/walk5.png'), pygame.image.load('images/walk6.png')]
walkLeft = [pygame.image.load('images/leftwalk2.png'), pygame.image.load('images/leftwalk3.png'), pygame.image.load('images/leftwalk4.png'), pygame.image.load('images/leftwalk5.png'), pygame.image.load('images/leftwalk6.png'), pygame.image.load('images/leftwalk7.png')]
bg = pygame.image.load('images/background.png')
char = pygame.image.load('images/standingstill.png')
clock = pygame.time.Clock()
​
class Player(pygame.sprite.Sprite):
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 0
self.isJump = False
self.left = False
self.right = False
self.walkCount = 0
self.jumpCount = 10
​
def draw(self, win):
if self.walkCount + 1 >= 18:
self.walkCount = 0
​
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:
win.blit(char, (self.x,self.y))
​
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load('images/background.png')
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
​
BackGround = Background('images/background.png', [0,0])
​
# def redrawGameWindow():
# win.blit(bg, (0,0))
# man.draw(win)
# pygame.display.update()
​
#mainloop
man = Player(100, 340, 40, 60)
run = True
while run:
clock.tick(27)
​
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
​
keys = pygame.key.get_pressed()
​
if keys[pygame.K_LEFT] and man.x > man.vel:
BackGround.rect.left = BackGround.rect.left + int(10)
man.x -= man.vel
man.left = True
man.right = False
elif keys[pygame.K_RIGHT]: #and man.x < 500 - man.width - man.vel:
BackGround.rect.left = BackGround.rect.left - int(10)
man.x += man.vel
man.right = True
man.left = False
else:
man.right = False
man.left = False
man.walkCount = 0
if not(man.isJump):
if keys[pygame.K_SPACE]:
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()
for zombie in all_zombies:
zombie.move_towards_player(Player)
all_zombie.update()
win.blit(BackGround.image, BackGround.rect)
man.draw(win)
pygame.display.flip()
all_zombies.draw(screen)
​
pygame.quit()
I can't run code but I see two problems
1 - move_towards_player has to be inside class ZombieEnemy
# --- classes ---
class ZombieEnemy(pygame.sprite.Sprite):
def __init__(self, x=300, y=360):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('images/zombie.png')
self.rect = self.image.get_rect()
self.rect.center = (x, y)
def move_towards_player(self, player):
# Find direction vector (dx, dy) between enemy and player.
dx, dy = player.rect.x - self.rect.x, player.rect.y - self.rect.y
dist = math.hypot (dx, dy)
dx, dy = dx / dist, dy / dist # Normalize
# Move along this normalized vector towards the player
self.rect.x += dx * self.speed
self.rect.y += dy * self.speed
# --- other ---
all_zombies = pygame.sprite.Group()
2 - you have to use it in main loop
for zombie in all_zombies:
zombie.move_towards_player(player)
in main loop
while running:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If keystroke is pressed check right, left.
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
#playerX_change = -2.0
BackGround.rect.left = BackGround.rect.left + 2.5
if event.key == pygame.K_RIGHT:
#playerX_change = 2.0
BackGround.rect.left = BackGround.rect.left - 2.5
# if event.type == pygame.KEYUP:
# if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
# BackGround.rect.left = 0
# --- updates/moves ---
playerX += playerX_change
for zombie in all_zombies:
zombie.move_towards_player(player)
all_zombies.update()
# --- draws ---
screen.blit(BackGround.image, BackGround.rect)
player(playerX,playerY)
all_zombies.draw(screen)
pygame.display.flip()
But here I see other problem - your function expects player as class instance with self.rect inside (similar to ZombieEnemy) but you keep player as separated variables playerImg, playerX, playerY, playerX_change
So you have to create class Player or you have to use playerx, playery in move_towards_player instead of player.rect.x, player.rect.y

Categories

Resources