Can't move character in pygame - python

I am trying to move my character (a spaceship) in pygame but what I have done so far has not worked. Everything runs and it displays the character but it does not move when I press the keys.
class Player:
vel = 10
x = width/2-PLAYER.get_width()/2
y = 450
def __init__(self, width, height):
self.width = width
self.height = height
def draw_player(self, win):
win.blit(PLAYER, (self.x, self.y))
def main():
running = True
clock = pygame.time.Clock()
fps = 30
while running:
bg = Background(0, 0)
bg.draw_background()
sc = Score(f"Score: {score}", WHITE)
sc.draw_score()
player = Player(50, 50)
player.draw_player(win)
pygame.display.set_caption("Space Invaders Game")
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
player.x += 1
if keys[pygame.K_LEFT]:
player.x -= 1
pygame.display.flip()
clock.tick(fps)
if __name__ == "__main__":
main()

When you create an instance of a class, the constructor is executed and the object attributes are initialized. Hence, you continuously create a new player in his starting position. You are drawing the player at the same position over and over again. Actually the player is moving, but you never see the movement because a new player is immediately created at the starting position to replace the first player.
You must create the instance object of the Player class before the application loop instead of in the application loop:
def main():
player = Player(50, 50) # <--- ADD
running = True
clock = pygame.time.Clock()
fps = 30
while running:
bg = Background(0, 0)
bg.draw_background()
sc = Score(f"Score: {score}", WHITE)
sc.draw_score()
# player = Player(50, 50) <--- REMOVE
player.draw_player(win)
pygame.display.set_caption("Space Invaders Game")
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
player.x += 1
if keys[pygame.K_LEFT]:
player.x -= 1
pygame.display.flip()
clock.tick(fps)

Related

'Player' has no attribute 'draw'

Trying to make my own game in pygame, and I have encountered an error, that I just cant seem to get around. I incorporated a class into the program, called Player. This class is supposed to hold information regarding the player, (image, input, etc). However when I try to call the class and draw it onto the screen. I get the error, ''Player has no attribute 'draw'''. Without using a class I can just blit it onto the screen, now something is different.
import pygame
from sys import exit
pygame.init()
#player info
x = 450
y = 840
vel = 5
#window info
screen_w = 800
screen_h = 600
# player movement etc
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
player_surf = pygame.image.load('game graphics/player_stand.png').convert_alpha()
#scaled player image
player_surf = pygame.transform.scale(player_surf,(500,500))
self.player_rect = player_surf.get_rect(midbottom = (x,y))
def player_input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_d] and self.rect.bottomright <= screen_h or self.rect.bottomleft >=screen_w:
x += vel
elif keys[pygame.K_a] and self.rect.bottomright <= screen_h or self.rect.bottomleft >=screen_w:
x -= vel
def update(self):
self.player_input()
# def draw(self):
# pass
#window stuff
screen = pygame.display.set_mode((screen_w,screen_h))
pygame.display.set_caption('Cave In')
#clock
clock = pygame.time.Clock()
#background
cave_surf = pygame.image.load('game graphics/background.png').convert()
cave_surf = pygame.transform.scale(cave_surf, (screen_w,screen_h)).convert()
#game
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.fill((0,0,0))
screen.blit(cave_surf,(0,0))
#here is the problem :/
Player.draw(screen)
Player.update()
pygame.display.update()
My question is, using the Player class, how do I get it to appear on the screen?
Thanks.
EDIT ---------------------->
After watching youtube videos, looking a other programs, and experimenting. I still can not get the character on screen. I have updated my code, and I now have a different error message at the moment. Here is the updated program.
import pygame, random
from sys import exit
pygame.init()
#player info
x = 450
y = 840
vel = 5
health = 5
#window info
screen_w = 800
screen_h = 600
# player movement etc
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.player_surf = pygame.image.load('game graphics/player_stand.png').convert_alpha()
#scaled player image
self.player_surf = pygame.transform.scale(self.player_surf,(500,500))
self.rect = self.player_surf.get_rect(midbottom = (x,y))
self.x_speed = vel
self.health = health
self.direction = 1 #1 = right 0 = left
def player_input(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
x += vel
elif keys[pygame.K_a]:
x -= vel
def update(self):
self.player_input()
# drawing the player on screen?
def draw_hero(self,screen,hero):
current_hero_sprite =
pygame.transform.flip(current_hero_sprite, True, False)
screen.blit(current_hero_sprite,hero.rect)
pygame.display.update(screen)
#window stuff
screen = pygame.display.set_mode((screen_w,screen_h))
pygame.display.set_caption('Cave In')
pygame.display.set_icon(pygame.image.load('game
graphics/player_stand.png'))
#clock
clock = pygame.time.Clock()
#background
cave_surf = pygame.image.load('game
graphics/background.png').convert()
cave_surf = pygame.transform.scale(cave_surf,
(screen_w,screen_h)).convert()
#game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.fill((0,0,0))
screen.blit(cave_surf,(0,0))
screen.blit(Player)
Player.update()
pygame.display.update()
My current error message is, ''line 75 TypeError: argument 1 must be pygame.Surface, not type'' There is similar problems on the on stack overflow/Quora etc. However none seem to really solve the problem?
Probably just a noob mistake.
SOLVED -->
screen.blit(player.player_surf,player.rect)
Thats it...
A class is a template to create (instantiate) an object. First instantiate a new Player object, then you can call methods on it.
# At the beginning, instantiate the player object as defined in the class.
player = Player()
#...
player.draw(screen)
player.update()

How do I make a continuously moving bullet when I'm not holding down the space bar in pygame? [duplicate]

This question already has answers here:
How can i shoot a bullet with space bar?
(1 answer)
How do I stop more than 1 bullet firing at once?
(1 answer)
Closed 1 year ago.
import pygame
# initialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 600))
# Title and icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Invader2.xcf')
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load('Player.xcf')
player_big = pygame.transform.scale(playerImg, (48, 48))
playerX = 370
playerY = 480
vel = 0.15
# Player Bullets
playerBulletImg = pygame.image.load('Player_bullet.xcf')
playerBulletX = playerX + 16
playerBulletY = playerY + 10
bulletVel = 0.3
def player(x, y):
screen.blit(player_big, (playerX, playerY))
def bullet(x, y):
screen.blit(playerBulletImg, (playerBulletX, playerBulletY))
# Game Loop
running = True
while running:
# RGB
screen.fill((18.8, 83.5, 78.4))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and playerX > 0:
playerX -= vel
playerBulletX -= vel
if keys[pygame.K_RIGHT] and playerX < 800 - 48:
playerX += vel
playerBulletX += vel
if keys[pygame.K_SPACE]:
playerBulletY -= 0.5
if playerBulletY == 0:
playerBulletY = 480
bullet(playerBulletX, playerBulletY)
player(playerX, playerY)
pygame.display.update()
Hi! I'm a beginner who has just started using Pygame. I'm making a Space Invaders / Galaga type game. When I press the space bar, the bullet goes up the y-axis, but only when I hold it down. I want the bullet to continue to move up the screen, even when I'm not holding down the space bar. Also, another problem is that when the bullet is in the air it still follows the x-value for the player. So when the bullet shoots up, It moves around depending on where the player is.
you should run your game as a class it is much more easier to code pygame with classes you can change your b.move to where else
import pygame
# initialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 600))
# Title and icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Invader2.xcf')
pygame.display.set_icon(icon)
# Player
class Player:
def __init__(self):
self.Img = pygame.image.load('Player.xcf')
self.big = pygame.transform.scale(playerImg, (48, 48))
self.x = 370
self.y = 480
self.vel = 0.15
def draw(self,screen):
screen.blit(self.big, (self.x, self.y))
class Bullet:
def __init__(self):
self.Img = pygame.image.load('Player_bullet.xcf')
self.x = playerX + 16
self.y = playerY + 10
self.vel = 0.3
def draw(screen):
screen.blit(self.Img, (self.y, self.y))
def move():
self.y -= self.vel
def draw(p,b):
p.draw()
for i in b:
i.draw()
# Game Loop
def main():
running = True
p = Player()
b = []
while running:
screen.fill((18.8, 83.5, 78.4))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and p.x > 0:
p.x -= p.vel
if keys[pygame.K_RIGHT] and p.x < 800 - 48:
p.x += p.vel
if keys[pygame.K_SPACE]:
b.append(Bullet())
draw(p,b)
for bullet in b:
bullet.move()
pygame.display.update()
Use the keyboard event instead of pygame.key.get_pressed() to shoot a bullet.
pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action.
Add a shootBullet variable that indicates when the bullet will be fired. Set the state when SPACE is pressed. Move and draw the bullet depending on this state. Set the starting position of the bullet when the bullet is fired.
shootBullet = False
clock = pygame.time.Clock()
running = True
while running:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
shootBullet = True
playerBulletX = playerX
playerBulletY = 480
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and playerX > 0:
playerX -= vel
if keys[pygame.K_RIGHT] and playerX < 800 - 48:
playerX += vel
if shootBullet:
playerBulletY -= 1
if playerBulletY <= 0:
shoot_bullet = False
screen.fill((18.8, 83.5, 78.4))
if shootBullet:
bullet(playerBulletX, playerBulletY)
player(playerX, playerY)
pygame.display.update()
Use pygame.time.Clock to control the frames per second and thus the game speed.
The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():
This method should be called once per frame.
That means that the loop:
clock = pygame.time.Clock()
run = True
while run:
clock.tick(100)
runs 100 times per second.

Why sprite isn't showing up in pygame? [duplicate]

im trying to get my image (bird) to move up and down on the screen but i cant figure out how to do it here is what i tried im sure its way off but im trying to figure it out if anyone can help that would be great!
import pygame
import os
screen = pygame.display.set_mode((640, 400))
running = 1
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
screen.fill([255, 255, 255])
clock = pygame.time.Clock()
clock.tick(0.5)
pygame.display.flip()
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
screen.blit( bird, ( 0, 0 ) )
pygame.display.update()
class game(object):
def move(self, x, y):
self.player.center[0] += x
self.player.center[1] += y
if event.key == K_UP:
player.move(0,5)
if event.key == K_DOWN:
player.move(0,-5)
game()
im trying to get it to move down on the down button press and up on the UP key press
As stated by ecline6, bird is the least of your worries at this point.
Consider reading this book..
For now, First let's clean up your code...
import pygame
import os
# let's address the class a little later..
pygame.init()
screen = pygame.display.set_mode((640, 400))
# you only need to call the following once,so pull them out of the while loop.
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
clock = pygame.time.Clock()
running = True
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255)) # fill the screen
screen.blit(bird, (0, 0)) # then blit the bird
pygame.display.update() # Just do one thing, update/flip.
clock.tick(40) # This call will regulate your FPS (to be 40 or less)
Now the reason that your "bird" is not moving is:
When you blit the image, ie: screen.blit(bird, (0, 0)),
The (0,0) is constant, so it won't move.
Here's the final code, with the output you want (try it) and read the comments:
import pygame
import os
# it is better to have an extra variable, than an extremely long line.
img_path = os.path.join('C:\Python27', 'player.png')
class Bird(object): # represents the bird, not the game
def __init__(self):
""" The constructor of the class """
self.image = pygame.image.load(img_path)
# the bird's position
self.x = 0
self.y = 0
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 1 # distance moved in 1 frame, try changing it to 5
if key[pygame.K_DOWN]: # down key
self.y += dist # move down
elif key[pygame.K_UP]: # up key
self.y -= dist # move up
if key[pygame.K_RIGHT]: # right key
self.x += dist # move right
elif key[pygame.K_LEFT]: # left key
self.x -= dist # move left
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
pygame.init()
screen = pygame.display.set_mode((640, 400))
bird = Bird() # create an instance
clock = pygame.time.Clock()
running = True
while running:
# handle every event since the last frame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
bird.handle_keys() # handle the keys
screen.fill((255,255,255)) # fill the screen with white
bird.draw(screen) # draw the bird to the screen
pygame.display.update() # update the screen
clock.tick(40)
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
If you want to achieve a continuously movement, you have to use pygame.key.get_pressed(). pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
See also Key and Keyboard event and How can I make a sprite move when key is held down.
Minimal example:
import pygame
import os
class Bird(object):
def __init__(self):
self.image = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
self.center = [100, 200]
def move(self, x, y):
self.center[0] += x
self.center[1] += y
def draw(self, surf):
surf.blit(self.image, self.center)
class game(object):
def __init__(self):
self.screen = pygame.display.set_mode((640, 400))
self.clock = pygame.time.Clock()
self.player = Bird()
def run(self):
running = 1
while running:
self.clock.tick(60)
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
keys = pygame.key.get_pressed()
move_x = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
move_y = keys[pygame.K_DOWN] - keys[pygame.K_UP]
self.player.move(move_x * 5, move_y * 5)
self.screen.fill([255, 255, 255])
self.player.draw(self.screen)
pygame.display.update()
g = game()
g.run()

I'm wondering why my player and my balloon which are both sprites is stuttering when I move the player

My frames drop and the game basically stops whenever I use the WASD keys, which are my movement controls. Its supposed to make the water balloon move but when I stop moving so does the water balloon. They're both sprites.
I might have got them mixed up since there are two sprite families.
main.py:
import pygame
from player import Player
from projectile import WaterBaloon
# Start the game
pygame.init()
game_width = 1000
game_height = 650
screen = pygame.display.set_mode((game_width, game_height))
clock = pygame.time.Clock()
running = True
bg_image = pygame.image.load("../assets/BG_Sand.png")
#make all the sprite groups
playerGroup = pygame.sprite.Group()
projectilesGroup = pygame.sprite.Group()
#put every sprite class in a group
Player.containers = playerGroup
WaterBaloon.containers = projectilesGroup
#tell the sprites where they are gonna be drawn at
mr_player = Player(screen, game_width/2, game_height/2)
# ***************** Loop Land Below *****************
# Everything under 'while running' will be repeated over and over again
while running:
# Makes the game stop if the player clicks the X or presses esc
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
#player input that detects keys (to move)
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
mr_player.move(1, 0)
if keys[pygame.K_a]:
mr_player.move(-1, 0)
if keys[pygame.K_w]:
mr_player.move(0, -1)
if keys[pygame.K_s]:
mr_player.move(0, 1)
if pygame.mouse.get_pressed()[0]:
mr_player.shoot()
#blit the bg image
screen.blit((bg_image),(0, 0))
#update the player
mr_player.update()
#update all the projectiles
for projectile in projectilesGroup:
projectile.update()
# Tell pygame to update the screen
pygame.display.flip()
clock.tick(60)
pygame.display.set_caption("ATTACK OF THE ROBOTS fps: " + str(clock.get_fps()))
player.py:
import pygame
import toolbox
import projectile
#Players Brain
class Player(pygame.sprite.Sprite):
#player constructor function
def __init__(self, screen, x, y):
pygame.sprite.Sprite.__init__(self, self.containers)
self.screen = screen
self.x = x
self.y = y
self.image = pygame.image.load("../assets/player_03.png")
#rectangle for player sprite
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
#end of rectangle for player sprite
self.speed = 8
self.angle = 0
#player update function
def update(self):
self.rect.center = (self.x, self.y)
mouse_x, mouse_y = pygame.mouse.get_pos()
self.angle = toolbox.angleBetweenPoints(self.x, self.y, mouse_x, mouse_y)
#get the rotated version of player
image_to_draw, image_rect = toolbox.getRotatedImage(self.image, self.rect, self.angle)
self.screen.blit(image_to_draw, image_rect)
#tells the computer how to make the player move
def move(self, x_movement, y_movement):
self.x += self.speed * x_movement
self.y += self.speed * y_movement
#shoot function to make a WaterBaloon
def shoot(self):
projectile.WaterBaloon(self.screen, self.x, self.y, self.angle)
You're only processing one event per frame. That's because you've put everything you do inside the frame in the event handling loop. That is likely to break down when you start getting events (such as key press and release events) at a higher rate. If events are not all being processed, your program may not update the screen properly.
You probably want your main loop to only do event processing stuff in the for event in pygame.event.get(): loop. Everything else should be unindented by one level, so that it runs within the outer, while running: loop, after all pending events have been handled.
Try something like this:
while running:
# Makes the game stop if the player clicks the X or presses esc
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
#player input that detects keys (to move) # unindent here (and all the lines below)
keys = pygame.key.get_pressed()
...

How to spawn multiple enemies in pygame

So im trying to make a game where the character should dodge enemies which are randomly spawned from above. The problem is, I dont know how to make the Random values different without instanciating another class, which I dont want to do. Also, with Screen.fill(), the enemies wont show up since they're being overlapped by the colour every frame, and if I dont use Screen.fill(), my character would leave a trail everytime it moves. Any Suggestions?
import random
pygame.init()
Running = True
Screen = pygame.display.set_mode((800, 600))
player_img = pygame.image.load('/Users/kevinhadinata/Downloads/ufo.png')
player_updated = pygame.transform.scale(player_img,(60,60))
enemy_list = []
enemy_img = pygame.image.load('/Users/kevinhadinata/Downloads/alien.png')
SPAWNENEMY = pygame.USEREVENT
pygame.time.set_timer(SPAWNENEMY,1000)
class Player:
def __init__(self):
self.ypos = 540
self.xpos = 325
self.height = 60
self.width = 60
self.playerUpdated = player_updated
def create_player(self):
Playerss = pygame.Rect(self.xpos,self.ypos,self.height,self.width)
pygame.draw.ellipse(Screen, (0, 0, 0), Playerss)
Screen.blit(player_updated, (Playerss.x, Playerss.y))
sizee = random.randint(10,40)
randomX = random.randint(0,700)
class Enemy:
def __init__(self):
self.xval = random.randint(0,700)
self.size = random.randint(10,40)
def create_enemy(self):
Enemy = pygame.Rect(self.xval, 0, self.size,self.size)
#enemy_updated = pygame.transform.scale(enemy_img,(self.size,self.size))
enemy_list.append(Enemy)
pygame.draw.ellipse(Screen,(255,255,0),Enemy)
Player = Player()
Enemys = Enemy()
while Running:
Screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
Running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
Player.xpos -= 20
if event.key == pygame.K_RIGHT:
Player.xpos += 20
if event.type == SPAWNENEMY:
Enemys.create_enemy()
Player.create_player()
pygame.display.update()
It's a good idea to not instantiate a new enemy, because just recycling it back to the top of the screen is enough. This amounts to simply changing the size & x,y.
Some of your code is occluding the Enemy class name with an Enemy variable name. I've changed this variable name to new_enemy.
class Enemy:
def __init__(self):
self.recycle() # set the position & size initially
def recycle( self ):
# start or re-start an enemy position
self.size = random.randint(10,40)
self.xval = random.randint(0,700)
self.yval = -self.size # off the screen-top
self.rect = pygame.Rect( self.xval, self.yval, self.size, self.size )
def draw( self, screen ):
pygame.draw.ellipse( screen, (255,255,0), self.rect )
def create_enemy(self):
global enemy_list
new_enemy = Enemy() # create a new Enemy
enemy_list.append( new_enemy ) # add it to the list
Then in your main loop, you can recycle() any Enemy that goes off-screen.
[...] # in main loop
# draw all the enemies, and re-position any enemies that moved off the screen
for enemy in enemy_list:
enemy.draw( screen )
if ( enemy.ypos > 600 ): # TODO - don't use a fixed size
enemy.recycle() # move back to top
The drawing an spawning code was mixed-up, I have re-arranged this into a separate .draw() function. Using this solves the problem with clearing the screen too. Each frame, the code clears the screen, then repaints all the items.
You need to create a list of enemies and iterate the list in the main loop to draw each enemy. Use randint to randomly place the enemies.
Try this code:
import random, pygame
pygame.init()
Running = True
Screen = pygame.display.set_mode((800, 600))
player_img = pygame.image.load('/Users/kevinhadinata/Downloads/ufo.png')
player_updated = pygame.transform.scale(player_img,(60,60))
enemy_list = []
enemy_img = pygame.image.load('/Users/kevinhadinata/Downloads/alien.png')
SPAWNENEMY = pygame.USEREVENT
pygame.time.set_timer(SPAWNENEMY,1000)
class Player:
def __init__(self):
self.ypos = 540
self.xpos = 325
self.height = 60
self.width = 60
self.playerUpdated = player_updated
def create_player(self):
self.Playerss = pygame.Rect(self.xpos,self.ypos,self.height,self.width)
pygame.draw.ellipse(Screen, (0, 0, 0), self.Playerss)
Screen.blit(player_updated, (self.Playerss.x, self.Playerss.y))
def draw(self): # draw player
Screen.blit(player_updated, (self.xpos,self.ypos))
sizee = random.randint(10,40)
randomX = random.randint(0,700)
class Enemys:
def __init__(self):
#self.xval = random.randint(0,700)
self.size = random.randint(10,40)
def create_enemy(self):
Enemy = pygame.Rect(random.randint(100,700), 0, self.size,self.size)
#enemy_updated = pygame.transform.scale(enemy_img,(self.size,self.size))
enemy_list.append(Enemy)
pygame.draw.ellipse(Screen,(255,255,0),Enemy)
def draw(self): # draw all enemies
for e in enemy_list:
pygame.draw.ellipse(Screen,(255,255,0),e)
Player = Player() # player object
Enemys = Enemys() # collection of enemies
Player.create_player()
while Running:
Screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
Running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
Player.xpos -= 20
if event.key == pygame.K_RIGHT:
Player.xpos += 20
if event.type == SPAWNENEMY:
Enemys.create_enemy()
Player.draw() # draw player
Enemys.draw() # draw all enemies
pygame.display.update()

Categories

Resources