How can i make function that makes my player move in Pygame - python

I'm trying to make space invaders in Pygame. I am trying to make the player move I saw few tutorials and that suppose to work but nothing happening when I am pressing the button.
this is the code:
import pygame
pygame.init()
WIN = pygame.display.set_mode((800, 600))
WIDTH, HEIGHT = 800, 600
VEL = 3
FPS = 60
WHITE_COLOR = (255, 255, 255)
pygame.display.set_caption("Space Invaders")
ufo_icon = pygame.image.load('ufo.png')
player = pygame.image.load('space-invaders.png')
player = pygame.transform.scale(player, (60, 60))
playerX = 400 - player.get_width()/2
playerY = 300
pygame.display.set_icon(ufo_icon)
def player_movement(playerX , keys):
if keys[pygame.K_LEFT]:
playerX += VEL
def draw_window(player, playerX, playerY):
WIN.fill((WHITE_COLOR))
WIN.blit(player, (playerX, playerY + 100))
pygame.display.update()
def main():
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
player_movement(playerX, keys)
draw_window(player, playerX, playerY)
main()

Python has no concept of in-out parameters. You need to return the new value from the function:
def player_movement(playerX , keys):
if keys[pygame.K_LEFT]:
playerX -= VEL
if keys[pygame.K_RIGHT]:
playerX += VEL
return playerX
def main():
playerX = 400 - player.get_width()/2
playerY = 300
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
playerX = player_movement(playerX, keys)
draw_window(player, playerX, playerY)

Related

Not able to shoot bullet in pygame

So recently I have been trying to make my first big game but I'm stuck on the shooting phase. Basically, my problem is I want to make it so that I can shoot multiple bullets and move around while doing so, but I can't seem to figure it out.
Code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption("Shooter Game!")
#Variables
playerX = 5
playerY = 5
black = (0,0,0)
blue = (0,0,255)
red = (255,0,0)
clicking = False
bulletX = playerX
bulletY = playerY
#End Of Variables#
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
screen.fill(blue)
player = pygame.image.load("Young_Link_2D.png").convert_alpha()
screen.fill(blue)
player1 = pygame.transform.scale(player, (100,100))
screen.blit(player1,(playerX,playerY))
keyPressed = pygame.key.get_pressed()
#Controls
if keyPressed[pygame.K_a]:
playerX -= 1
bulletX = playerX
if keyPressed[pygame.K_d]:
playerX += 1
bulletX = playerX
if keyPressed[pygame.K_w]:
playerY -= 1
bulletY = playerY
if keyPressed[pygame.K_s]:
playerY += 1
bulletY = playerY
#End of Controls
#Shooting
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
Bullet = pygame.draw.rect(screen, red, (bulletX+35,bulletY + 60,10,25))
bulletY = bulletY + 1
pygame.display.update()
Here is what i meant by classes:
import pygame
import Bullet
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Shooter Game!")
# Variables
playerX = 5
playerY = 5
black = (0, 0, 0)
blue = (0, 0, 255)
red = (255, 0, 0)
clicking = False
bulletX = playerX
bulletY = playerY
bullets = []
newBullet = False
# End Of Variables#
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
screen.fill(blue)
player = pygame.image.load("100x100_logo.png").convert_alpha()
screen.fill(blue)
player1 = pygame.transform.scale(player, (100, 100))
screen.blit(player1, (playerX, playerY))
keyPressed = pygame.key.get_pressed()
# Controls
if keyPressed[pygame.K_a]:
playerX -= 1
bulletX = playerX
if keyPressed[pygame.K_d]:
playerX += 1
bulletX = playerX
if keyPressed[pygame.K_w]:
playerY -= 1
bulletY = playerY
if keyPressed[pygame.K_s]:
playerY += 1
bulletY = playerY
# End of Controls
# Shooting
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
bullets.append(Bullet.Bullet(bulletX + 35, bulletY + 60))
for i in range(len(bullets)):
bullets[i].draw(screen, (255, 0, 0))
bullets[i].move(1)
print(len(bullets))
pygame.display.update()
Thats your main code. There is still a bug where there is no cooldown so multiple bullets are created consecutively when holding the mouse button.
import pygame
class Bullet:
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self, win, colour):
pygame.draw.rect(win, colour, (self.x, self.y, 10, 25))
def move(self, speed):
self.y += speed
and thats the bullet class to create multiple instances
See How do I stop more than 1 bullet firing at once? and How can i shoot a bullet with space bar?.
You need to manage the bullets in a list:
bullets = []
Add a new bullet to the list when the mouse click is detected. Use pygame.Rect objects to represent the bullets. The events must be handled in the event loop:
for event in pygame.event.get():
# [...]
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
bullets.append(pygame.Rect(playerX, playerY, 35, 60))
Move the bullets in a loop. Remove the bullets from the list, when they when they move off the screen. See How to remove items from a list while iterating?:
for bullet in bullets[:]:
bullet.y += 5
if bullet.top > 600:
bullets.remove(bullet)
Draw all the bullets in the list in another loop:
for bullet in bullets:
pygame.draw.rect(screen, red, bullet)
Complete example:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption("Shooter Game!")
#Variables
player = pygame.image.load("Young_Link_2D.png").convert_alpha()
playerX, playerY = 5, 5
black = (0,0,0)
blue = (0,0,255)
red = (255,0,0)
clicking = False
bullets = []
#End Of Variables#
clock = pygame.time.Clock()
running = True
while running:
clock.tick(100)
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
bullets.append(pygame.Rect(playerX, playerY, 35, 60))
keyPressed = pygame.key.get_pressed()
playerX += keyPressed[pygame.K_d] - keyPressed[pygame.K_a]
playerY += keyPressed[pygame.K_s] - keyPressed[pygame.K_w]
for bullet in bullets[:]:
bullet.y += 5
if bullet.top > 600:
bullets.remove(bullet)
screen.fill(blue)
player1 = pygame.transform.scale(player, (100,100))
screen.blit(player1,(playerX,playerY))
for bullet in bullets:
pygame.draw.rect(screen, red, bullet)
pygame.display.update()
pygame.quit()
exit()

Flickering Sprite in Pygame

I know lots of people have had issues with flickering images in pygame on here, but none of the responses have helped me. I am trying to make Space Invaders, however, the bullet flickers as it moves up the screen. Please try to help me, and thank you! I do not currently care about the size, position, or scale of the bullet, I know it does not look great, but I just want it to display properly! Below is the code:
import pygame
#import sys- might use later
import random
#Sets the starting values for screen, etc. of the playing space
pygame.init()
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Space Invaders")
play = True
clock = pygame.time.Clock()
blkColor = (0, 0, 0)
#Loads and sizes the alien and player ship(s)
playerShip = pygame.image.load('ship.png')
playerShip = pygame.transform.scale(playerShip, (50, 50))
playerX = 370
playerY = 520
alien = pygame.image.load('alien.png')
alien = pygame.transform.scale(alien, (35, 35))
alienX = random.randint(0, 750)
alienY = 0
move = 5
alienMove = 5
bullet = pygame.image.load('bullet.png')
bullet = pygame.transform.scale(bullet, (5, 100))
bulletX = 0
bulletY = 600
hit = False
fire = False
hitRangeMin = -35
hitRangeMax = 35
score = 0
def player():
screen.blit(playerShip, (playerX, playerY))
def enemy():
screen.blit(alien, (alienX, alienY))
def alienMovement():
global alienX
global alienY
global alienMove
#Moves the alien across the screen; when it hits the edge, it shifts down one spot and goes the other direction
alienX += alienMove
if alienX > 750:
alienMove = -5
alienY += 35
if alienX < 0:
alienMove = 5
alienY += 35
def shoot(x, y):
global fire
global bulletY
fire = True
screen.blit(bullet, (x, y))
pygame.display.flip()
if bulletY < 0:
fire = False
bulletY = 550
elif bulletY >= 0:
fire = True
def gameOver(score):
print('Will add score and display and stuff- does noo matter.')
# Keeps the game window open until exited
while not hit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
player()
enemy()
key_input = pygame.key.get_pressed()
if key_input[pygame.K_LEFT]:
playerX -= move
elif key_input[pygame.K_RIGHT]:
playerX += move
if playerX > 800:
playerX = 0
if playerX < 0:
playerX = 800
#For shooting the bullet
if key_input[pygame.K_SPACE]:
bulletX = playerX + 23
shoot(bulletX, bulletY)
##Loops with function "shoot" to move bullet up the screen
if fire:
shoot(bulletX, bulletY)
bulletY -= 5
screen.fill(blkColor)
alienMovement()
player()
enemy()
pygame.display.flip()
clock.tick(60)
The problem is caused by multiple calls to pygame.display.update(). An update of the display at the end of the application loop is sufficient. Multiple calls to pygame.display.update() or pygame.display.flip() cause flickering.
Remove pygame.display.flip() from shoot:
def shoot(x, y):
global fire
global bulletY
fire = True
screen.blit(bullet, (x, y))
# pygame.display.flip() <--- DELETE
if bulletY < 0:
fire = False
bulletY = 550
elif bulletY >= 0:
fire = True
And you have to clear the screen before drawing the bullet:
while not hit:
# [...]
screen.fill(blkColor) # <--- INSERT
if key_input[pygame.K_SPACE]:
bulletX = playerX + 23
shoot(bulletX, bulletY)
##Loops with function "shoot" to move bullet up the screen
if fire:
shoot(bulletX, bulletY)
bulletY -= 5
# screen.fill(blkColor) <--- DELETE
alienMovement()
player()
enemy()
pygame.display.flip()
clock.tick(60)

I'm having problem with moving a player object in Pygame [duplicate]

This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
Closed 1 year ago.
I'm having a problem with moving a player object in Pygame. I have created the class of Player and called it on my main file, but whenever I try to move the player object it won't move. I have also called it inside the Game loop but still, it won't move. I don't know what's going on: Here is the code I have done so far:
screen.py
import pygame
screen.py
class Screen:
def __init__(self, width, height):
self.width = width
self.height = height
def screen_display(self):
return pygame.display.set_mode((self.width,self.height))
player.py
import pygame
class Player:
playerY_change = 0.5
def __init__(self, playerX,playerY, playerWidth,playerHeight,screen,):
self.playerX = playerX
self.playerY = playerY
self.playerWidth = playerWidth
self.playerHeight = playerHeight
self.screen = screen
def create_player(self):
return pygame.draw.rect(self.screen, [0, 0, 0], [self.playerX, self.playerY, self.playerWidth, self.playerHeight])
enemy.py
import pygame
class Enemy:
def __init__(self, enemyX,enemyY, enemyWidth,enemyHeight,screen):
self.enemyX = enemyX
self.enemyY = enemyY
self.enemyWidth = enemyWidth
self.enemyHeight = enemyHeight
self.screen = screen
def create_enemy(self):
return pygame.draw.rect(self.screen, [0, 0, 0], [self.enemyX, self.enemyY, self.enemyWidth, self.enemyHeight])
Here is my Main file main.py:
import pygame,random,math
from screen import Screen
from player import Player
from enemy import Enemy
# Pygame initilaize
pygame.init()
#Game Screen
screenWidth = 800
screenHeight = 500
window = Screen(screenWidth,screenHeight)
screen = window.screen_display()
# Title and Logo
pygame.display.set_caption("ShootBhoot")
icon = pygame.image.load("logo.png")
pygame.display.set_icon(icon)
# Player
playerX = 10
playerY = 10
playerY_change = 200
playerWidth = 15
playerHeight = 50
player = Player(playerX,playerY,playerWidth,playerHeight,screen)
#Enemy
enemyWidth = 15
enemyHeight = 50
enemyX = screenWidth - (enemyWidth + 10)
enemyY = 10
enemy = Enemy(enemyX,enemyY,enemyWidth,enemyHeight,screen)
# Ball
ballRadius = 10
ballX = random.randint(0, screenWidth - 10)
ballY = random.randint(0, screenHeight - 10)
ballX_change = 0.01
ballY_change = 0
def ball_create(screen, ballX, ballY, radius):
return pygame.draw.circle(screen, (10, 10, 10), (ballX, ballY), radius)
def distance(playerX,playerY,ballX,ballY):
calc = math.sqrt((playerX - ballX)**2 + (playerY - ballY)**2)
print(calc)
#Game loop
running = True
while running:
screen.fill((255,255,255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#Even while I click btn It won't move
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
playerY_change = -0.5
if event.key == pygame.K_DOWN:
playerY_change = 0.5
# Player Move Object not moving
playerY = playerY_change
enemy.create_enemy()
ball_create(screen, ballX, ballY, ballRadius)
player.create_player()
pygame.display.flip()
pygame.display.update()
playerY is just used when to create the player. You have to change the coordinate attribute of the player:
playerY = playerY_change
player.playerY += playerY_change
However I recommend to use pygame.key.get_pressed() instead of the keyboard events.
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.
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:
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.playerY -= 1
if keys[pygame.K_RIGHT]:
player.playerY += 1
screen.fill((255,255,255))
enemy.create_enemy()
ball_create(screen, ballX, ballY, ballRadius)
player.create_player()
pygame.display.flip()

Trying to add a restart keystroke to my problem but facing encounters

So I was trying to build this game using a free course on Youtube by Freecodeacademy(feel free to check them out) and after I finished I tried to add my own restart key log to the game. In the sense that I wanted that if people press R the game restarts.
I have tried the following methods
Put the game loop in a separate function and try to use recursion to replay the function over and over again but while the game does work, the images such as the bullet image or background does not load and hence it does not work properly
I have also tried creating a new python file in the same project and tried to import the main file over and over again using importlib.reload(main) but I can't seem to do that either.
I was wondering what else could the solution be and if there is a more efficient solution. I will leave my code down below and would appreciate any help.
Ps: I am only a armature in coding right now so I understand this problem might be small and stupid but I do want to learn from my failures and mistakes. Also I apologize if there is something wrong with anything in my question. This is my first question on stack overflow.
import pygame
import random
import math
from pygame import mixer
pygame.init() # This is to Initialise the game
screen = pygame.display.set_mode((800, 600)) # create screen and set height
# Background
background = pygame.image.load('background.png')
# Background sound
mixer.music.load("background.wav")
mixer.music.play(-1)
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load("space-invaders.png")
playerX = 370
playerY = 480
playerX_change = 0
def player(x, y): # This function is used to display the value on the screen
screen.blit(playerImg, (x, y)) # Blit is used to display stuff on the screen
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load("invader.png"))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(40)
def enemy(x, y, i): # This function is used to display the value on the screen
screen.blit(enemyImg[i], (x, y)) # Blit is used to display stuff on the screen
# Bullet
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready" # Ready state means bullet has not yet been fired, we use this as a bool
# Score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 16)
textX = 10
textY = 10
# Game Over Text
over_font = pygame.font.Font("freesansbold.ttf", 64)
def show_score(x, y):
over_text = font.render("Score: " + str(score_value), True, (255, 255, 255))
screen.blit(over_text, (x, y))
def game_over_text():
over_text = over_font.render("GAME OVER ", True, (255, 255, 255))
screen.blit(over_text, (200, 250))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x + 16, y + 10))
def isCollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt((math.pow(enemyX - bulletX, 2)) + (math.pow(enemyY - bulletY, 2)))
if distance < 27:
return True
else:
return False
# Game Loop
running = True
while running:
# Background color
screen.fill((0, 0, 0))
# Background image
screen.blit(background, (0, 0))
for event in pygame.event.get(): # pygame.event.get() function is used to create a container of every action done
if event.type == pygame.QUIT: # Close game when cross is clicked
running = False
# Recording Keystrokes
if event.type == pygame.KEYDOWN: # KEYDOWN is used to check if key is pressed
if event.key == pygame.K_LEFT:
playerX_change -= 5
if event.key == pygame.K_RIGHT:
playerX_change += 5
if event.key == pygame.K_SPACE: # Bullet Shot
if bullet_state == "ready":
bullet_sound = mixer.Sound("laser.wav")
bullet_sound.play()
bulletX = playerX
fire_bullet(bulletX, playerY)
if event.key == pygame.K_r:
restart = True
if event.type == pygame.KEYUP: # KEYUP is used to know if the key is released
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# Player Call
playerX += playerX_change
# Setting Boundaries
if playerX <= 0:
playerX = 0
if playerX >= 736:
playerX = 736
for i in range(num_of_enemies):
# Game Over
if enemyY[i] > 440:
for j in range(num_of_enemies):
enemyY[j] = 2000
game_over_text()
break
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 4
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = -4
enemyY += enemyY_change
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
explosion_sound = mixer.Sound("explosion.wav")
explosion_sound.play()
bulletY = 480
score_value += 1
bullet_state = "ready"
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state == "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
show_score(textX, textY)
# Constantly updates the changes
pygame.display.update()
Write a function that will reset any variables that change when the game is running:
enemy_image = pygame.image.load("invader.png")
def resetGame():
global playerX, playerY, playerX_change
global enemyImg, enemyX, enemyY, enemyX_change, enemyY_change
global score_value
global bulletX, bulletY, bulletX_change, bulletY_change, bullet_state
playerX = 370
playerY = 480
playerX_change = 0
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(enemy_image)
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(40)
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready"
score_value = 0
Call the function once if the game needs to be restarted. You can even call the function before the application loop instead of setting all the variables.

Python PyGame Restart

so i was learning python and i finished the game and everything is working but now i have no idea about how to restart the game i mean when it ends what is next? how to start again
i will put a link for my full code and here is what have done so far.
Thank you so much!
if Bullet_state is "fire":
fire(BulletX, BulletY)
BulletY -= Bullet_MovementY
player(playerX, playerY)
score(textX, textY)
pygame.display.update()
For the restart logic, keep the current game loop but add a flag to indicate that the game has ended. In the loop, check for this flag and display the restart prompt if the flag is set. Also encapsulate the initialization process in a function so it can be called at each restart.
Note that I tested this in Python 3.8.
Try this code. When the score reaches 3, the game ends and the restart prompt is displayed.
import pygame
import random
import math
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Space Invadors')
icon = pygame.image.load('1.png')
pygame.display.set_icon(icon)
#Background
Background = pygame.image.load('background.png')
def SetGameStart(): # initialize variables
global Player_Image,playerX,playerY,Key_Movement,Enemy_Image,EnemyX,EnemyY,Enemy_MovementX,Enemy_MovementY
global Bullet_Image,BulletX,BulletY,Bullet_MovementX,Bullet_MovementY,Bullet_state,Score
# Player
Player_Image = pygame.image.load('player.png')
playerX = 370
playerY = 480
Key_Movement = 0
# Enemy
Enemy_Image = pygame.image.load('monster2.png')
EnemyX = random.randint(0, 735)
EnemyY = random.randint(50, 150)
Enemy_MovementX = 1.5
Enemy_MovementY = 40
# Bullet
Bullet_Image = pygame.image.load('bullet.png')
BulletX = 0
BulletY = 480
Bullet_MovementX = 0
Bullet_MovementY = 10
Bullet_state = "Ready"
Score = 0
def Fire(x, y):
global Bullet_state
Bullet_state = "Fire"
screen.blit(Bullet_Image, (x + 16, y + 10))
def player(x, y):
# blit is draw! draw an image on the screen
screen.blit(Player_Image, (x, y))
def Enemy(x, y):
screen.blit(Enemy_Image, (x, y))
def is_Collided(BulletX, BulletY, EnemyX, EnemyY):
distance = math.sqrt(math.pow(BulletX - EnemyX, 2) + math.pow(BulletY - EnemyY, 2))
if distance < 27:
return True
else:
return False
SetGameStart() # initialize variables
GameDone = False
def text_objects(text, font):
textSurface = font.render(text, True, (0,200,0))
return textSurface, textSurface.get_rect()
Close = True
while Close:
screen.fill((0, 0, 0))
screen.blit(Background, (0, 0))
if GameDone: # pause game loop, show restart prompt
largeText = pygame.font.SysFont("comicsansms",20)
TextSurf, TextRect = text_objects("Game Over. Press Space to restart.", largeText)
TextRect.center = ((800/2),(600/2))
screen.blit(TextSurf, TextRect)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
Close = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q: # press Q to quit
Close = False
break
if event.key == pygame.K_SPACE: # press space to restart
GameDone = False
SetGameStart() # initialize variables
continue # skip game process
for event in pygame.event.get():
if event.type == pygame.QUIT:
Close = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
Key_Movement = -4
if event.key == pygame.K_RIGHT:
Key_Movement = 4
if event.key == pygame.K_SPACE:
# to fix the Pressing on space will reload the Bullet
if Bullet_state is "Ready":
BulletX = playerX
Fire(BulletX, playerY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
Key_Movement = 0
playerX += Key_Movement
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemy movement limit
EnemyX += Enemy_MovementX
if EnemyX <= 0:
Enemy_MovementX = 1.5
EnemyY += Enemy_MovementY
elif EnemyX >= 736:
Enemy_MovementX = -1.5
EnemyY += Enemy_MovementY
if BulletY <= 0:
BulletY = 480
Bullet_state = "Ready"
if Bullet_state is "Fire":
Fire(BulletX, BulletY)
BulletY -= Bullet_MovementY
Collision = is_Collided(EnemyX, EnemyY, BulletX, BulletY)
if Collision:
BulletY = 480
Bullet_state = "Ready"
Score += 1
print(Score)
EnemyX = random.randint(0, 735)
EnemyY = random.randint(50, 150)
Enemy(EnemyX, EnemyY)
player(playerX, playerY)
pygame.display.update()
if Score == 3:
GameDone = True
Prompt

Categories