Character movement bug in pygame - python

I made a loop to keep the "enemy" character moving to left and right, but for some reason that I really can't tell why, he just goes to the right and when he hits the border limit that I defined, he "teleports" to the left border and keeps going to the right forever. I even tried to make the "enemyX_change" beeing negative, but he just goes to the left, hit the border and stops. I'm using Python 3.8.
import pygame
import random
# Initiate pygame
pygame.init()
# Display the game window
screen = pygame.display.set_mode((800, 600))
# Title and Icon
pygame.display.set_caption('Space Invaders')
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
# Player
playerSprite = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemySprite = pygame.image.load('enemy.png')
enemyX = random.randint(0, 736)
enemyY = random.randint(50, 150)
enemyX_change = 0.3
enemyY_change = 0
def player(x, y):
screen.blit(playerSprite, (x, y))
def enemy(x, y):
screen.blit(enemySprite, (x, y))
# Game Loop
running = True
while running:
# Background color (RGB)
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If a key is pressed, check if it's the right or left arrow key
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.3
if event.key == pygame.K_RIGHT:
playerX_change = 0.3
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# Move the spaceship to the left or right
playerX += playerX_change
# Prevents the player from going off the border
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Moves the enemy
enemyX += enemyX_change
# Prevents the enemy from going off the border
if enemyX <= 0:
enemyX = 0.3
elif enemyX >= 736:
enemyX = -0.3
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()

When the enemy goes out of bounds, then you have to change the movement direction (enemyX_change) rather than the position of the player (enemyX):
enemyX = -0.3
enemyX_change *= -1
Invert enemyX_change when it is less than 0 or greater than the width of the window:
# Moves the enemy
enemyX += enemyX_change
# Prevents the enemy from going off the border
if enemyX <= 0 or enemyX >= 736:
enemyX_change *= -1

Related

Pygame displays a black screen

I did some research to see if I could fix my problem on my own but it has been fruitless so far. I've checked to see if I ran the .display command too much but I haven't, the program will run without error but the screen appears black except when I close the window out, you can catch a glimpse of what it is supposed to display. Any insight into what is wrong? Help is greatly appreciated!
import math
import random
import pygame
from pygame import mixer
# Initialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load('space background.png')
# Background Sound
# come back to this from bg music 'mixer.music.load('insert file name')'
# 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('ship.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(0, 735))
enemyY.append(random.randint(50, 150))
enemyX_change.append(0.3)
enemyY_change.append(40)
# Bullet
# Ready - you cat see the bullet on the screen
# Fire - The bullet is currently moving
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 1 # Bullet speed
bullet_state = "ready"
# Score
score_value = 0
font = pygame.font.Font('Minecraft.ttf', 24)
textX = 10
testY = 10 # might have to change back to 'text'
# Game Over text
over_font = pygame.font.Font('Minecraft.ttf', 64)
def show_score(x, y):
score = font.render("Score : " + str(score_value), True, (225, 225, 255))
screen.blit(score, (x, y))
def game_over_text(x, y):
over_text = over_font.render("GAME OVER", True, (225, 225, 255))
screen.blit(over_text, (200, 250))
def player(x, y):
screen.blit(playerImg, (x, y))
def enemy(x, y, i):
screen.blit(enemyImg[i], (x, y))
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:
# RGB
screen.fill((0, 0, 0))
# background image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.7 # player speed
if event.key == pygame.K_RIGHT:
playerX_change = 0.7
if event.key == pygame.K_SPACE:
if bullet_state == "ready":
bullet_Sound = mixer.Sound('laser.wav')
bullet_Sound.play()
# Get the current X corrdinate of te spaceship
bulletX = playerX
fire_bullet(playerX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# 5 = 5 + -0.1 -> 5 = 5 - 0.1
# 5 = 5 + 0.1
# Checking for boundries of spaceship
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemy Movement
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] = 0.3 # enemy speed
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = -0.3
enemyY[i] += enemyY_change[i]
# Collision
collision = iscollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
explosion_Sound = mixer.Sound('explosion.wav')
explosion_Sound.play()
bulletY = 480
bullet_state = "ready"
score_value += 100
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, testY)
pygame.display.update()
All you have to do is indent the last bit of code (the 11 lines under the comment Bullet Movement) one level in. Right now, it's not under the while loop, which explains why the screen is black and why it only appears after you click the close button (which exits the loop and executes the drawing code). Hope this helps!

i can't shoot the bullet in this pygame space invaders

Pygame is perfectly installed, everything else is working fine spaceship movement and enemy movement but i am not able to see the bullet which i have drawn from inside the fire_bullet function, I have tried drawing it from outside the function and that does seem to work .
import pygame
import os
import random
pygame.init()
#Screen
screen = pygame.display.set_mode((800, 600))
#Title and Icon
pygame.display.set_caption('Space Invaders ')
UFO = pygame.image.load(os.path.join('Assets2', 'ufo.png'))
pygame.display.set_icon(UFO)
#player
playerImg = pygame.image.load(os.path.join('Assets2', 'spaceship.png'))
playerX = 370
playerY = 480
VEL = 0
def player(x, y):
screen.blit(playerImg, (x, y))
#enemy
enemyImg = pygame.image.load(os.path.join('Assets2', 'enemy.png'))
enemyimg1 = pygame.transform.scale(enemyImg, (45, 50))
enemyX = random.randint(0,800)
enemyY = random.randint(50,150)
enemyX_change = 0.7
enemyY_change = 40
def enemy(x,y):
screen.blit(enemyimg1, (x, y))
#background
bg = pygame.image.load(os.path.join('Assets2', 'space.png'))
#bullet
bulletimg = pygame.image.load(os.path.join('Assets2', 'bullet.png'))
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready" #Ready - Rest, Fire - Motion
def fire_bullet(x,y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletimg, (x+16, y+10))
run = True
#Game loop
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
VEL = -1.4
if event.key == pygame.K_RIGHT:
VEL= 1.4
# Bullet positioning
if event.key == pygame.K_SPACE:
fire_bullet(playerX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
VEL = 0
playerX += VEL
# Restricting boundaries of spaceship
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
enemyX += enemyX_change
# Restricting boundaries of Enemy
if enemyX <= 0:
enemyX_change = 1
enemyY += enemyY_change
elif enemyX >= 736:
enemyX_change = -1
enemyY += enemyY_change
#Bullet Movement
if bullet_state is "fire":
fire_bullet(playerX, bulletY)
bulletY -= bulletY_change
screen.fill((255,255,0))
screen.blit(bg, (0,0))
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
Also all the assets are fine and dowloaded correctly so idk why is it still not showing the bullet drawn from inside the function
Your bullet is so fast that you can barely see it. You have to limit the frames per second. 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.
e.g.:
clock = pygame.time.Clock()
#Game loop
while run:
clock.tick(60)
# [...]

Why does "Game over" text not appear?

I am currently attempting to programm a small game. An enemy is supposed to chase the player, the actual chasing is not implemented yet. I still need to figure out how to do that, but that's not the question.
I have made it so that the player returns to the start point once they collide with the enemy. In addition to that, a text 'Game over' is supposed to appear. The function for that is called at the end of the game loop and while the text appeared briefly(it actually only appeared once, I have tried it multiple times), it does not stay. I was planing on making it appear and then disappear after a few seconds so that the player can play again, but I'm not sure why it disappears instantly.
If this is the wrong place to post this, please tell me, I will delete this post. This is my code, would be amazing if somebody could help me out:
import pygame #imports pygame
import math
pygame.init()
#screen
screen = pygame.display.set_mode((800,600)) #width and height
#title and icon
pygame.display.set_caption("The Great Chase") #changes title
icon = pygame.image.load('game-controller.png')
pygame.display.set_icon(icon) #setting icon
#player
playerImg = pygame.image.load('scary-monster.png')
playerX = 370
playerY = 480
playerX_change = 0
playerY_change = 0
#enemy
enemyImg = pygame.image.load('caterpillar.png')
enemyX = 370
enemyY = 50
enemyX_change = 0
enemyY_change = 0
#GAME OVER
game_over_font = pygame.font.Font('Bubblegum.ttf',64)
def game_over_text():
game_over_text = game_over_font.render("GAME OVER", True, (255, 0, 0))
screen.blit(game_over_text, (200, 250))
def player(x, y): #function for player
screen.blit(playerImg, (x, y)) #draws image of player, blit -> means to draw
def enemy(x, y): #function for enemy
screen.blit(enemyImg,(x,y))
def isCollision(playerX, playerY, enemyX, enemyY):
distance = math.sqrt((math.pow(playerX-enemyX,2)) + (math.pow(playerY - enemyY,2)))
if distance < 25:
return True
else:
return False
def chase():
distance = math.sqrt((math.pow(playerX-enemyX,2)) + (math.pow(playerY - enemyY,2)))
#Game loop
running = True
while running:
screen.fill((255,255,0)) #0-255 RGB-> red, green & blue
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke check whether right or left or up or down
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.2
if event.key == pygame.K_RIGHT:
playerX_change = 0.2
if event.key == pygame.K_UP:
playerY_change = -0.2
if event.key == pygame.K_DOWN:
playerY_change = 0.2
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
playerX += playerX_change
playerY += playerY_change
#creating borders so that player won't leave screen
if playerX <=0:
playerX = 0
elif playerX >=768:
playerX = 768
if playerY <= 0:
playerY = 0
elif playerY >=568:
playerY = 568
#collision
collision = isCollision(playerX, playerY, enemyX, enemyY)
if collision:
playerY = 480
game_over_text()
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
The collision only occurs for a moment and the game over text is only shown when the object collides. If you want to persist the text, set a gameover variable when the collision is detected and display the text based on the state of the variable:
gameover = False
running = True
while running:
# [...]
collision = isCollision(playerX, playerY, enemyX, enemyY)
if collision:
playerY = 480
gameover = True
player(playerX, playerY)
enemy(enemyX, enemyY)
if gameover:
game_over_text()
pygame.display.update()
Note, collision is set in every frame depending on the position of the objects. However, gameover is set once when a collision occurs and then maintains its state.

how to make bullet come out according to the object

i am still learning on how to use pygame and i just created a space invader inspired game. but one issue that i have right now is that the bullet does not come out accordingly to my object's location. instead it only comes out from the bottom of the screen. i want my bullet to come out accordingly to my object no matter if its moving up, down, right or left. thank you in advance!!
import pygame
import random
import math
#intialize the pygame
pygame.init()
#create the screen
screen = pygame.display.set_mode((700,583))
#Caption and icon
pygame.display.set_caption("Yoshi & Fruits")
icon = pygame.image.load("Yoshi_icon.png")
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load("YoshiMario.png")
playerX = 370
playerY = 480
playerX_change = 0
playerY_change = 0
#Enemy
enemyImg = pygame.image.load('msh1.png')
enemyX = random.randint(0,735)
enemyY = random.randint(50,150)
enemyX_change = 2
enemyY_change = 30
#Knife
# ready - you cant see the knife on the screen
# fire - the knife is currently moving
knifeImg = pygame.image.load('diamondsword3.png')
knifeX = 0
knifeY = 480
knifeX_change = 0
knifeY_change = 10
knife_state = "ready"
score = 0
def player(x,y):
screen.blit(playerImg, (x, y))
def enemy(x,y):
screen.blit(enemyImg, (x, y))
def fire_knife(x,y):
global knife_state
knife_state = "fire"
screen.blit(knifeImg,(x + 16, y + 10))
def isCollision(enemyX,enemyY,knifeX,knifeY):
distance = math.sqrt((math.pow(enemyX - knifeX,2)) + (math.pow(enemyY - knifeY,2)))
if distance < 27:
return True
else:
return False
#game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -2
if event.key == pygame.K_RIGHT:
playerX_change = 2
if event.key == pygame.K_UP:
playerY_change = -2
if event.key == pygame.K_DOWN:
playerY_change = 2
if event.key == pygame.K_SPACE:
if knife_state is "ready":
# get the current x coordinate of yoshi
knifeX = playerX
fire_knife(playerX,knifeY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
# RGB - Red, Green, Blue
screen.fill((0, 255, 0))
#add a wallpaper
bgimage=pygame.image.load("Background.png")
screen.blit(bgimage, (0, 0))
# 5 = 5 + -0.1 ->5 = 5 - 0.1
# 5 = 5 + 0.1
# checking for boundaries of yoshi/mushroom so it doesnt go out of bounds
playerX += playerX_change
if playerX < 0:
playerX = 0
elif playerX > 645:
playerX = 645
playerY += playerY_change
if playerY < 0:
playerY = 0
elif playerY > 500:
playerY = 500
# enemy movement
enemyX += enemyX_change
if enemyX <= 0:
enemyX_change = 2
enemyY += enemyY_change
elif enemyX > 645:
enemyX_change = -2
enemyY += enemyY_change
# knife movement
if knifeY <= 0:
knifeY = 480
knife_state = "ready"
if knife_state is "fire":
fire_knife(knifeX,knifeY)
knifeY -= knifeY_change
# collision
collision = isCollision(enemyX,enemyY,knifeX,knifeY)
if collision:
knifeY = 480
knife_state = "ready"
score += 1
print(score)
enemyX = random.randint(0,735)
enemyY = random.randint(50,150)
player(playerX,playerY)
enemy(enemyX,enemyY)
pygame.display.update()
I assume by "bullet" you are referring to "knife" in the code.
The code is not tracking the change in the knife's co-ordinates. Sure it's created at the player's X co-ordinate, but nothing remembers this change. So let's modify fire_knife() to simply remember the changes in the state of the knife, including the new X & Y.
def fire_knife( x, y ):
""" Start a knife flying upwards from the player """
global knife_state, knifeX, knifeY
knifeX = x + 16
knifeY = y + 10
knife_state = "fire"
And create a collision handler that automatically resets the knife back to "ready":
def knife_hits( enemyX, enemyY ):
""" Return True if the knife hits the enemy at the given (x,y).
If so, prepare the knife for firing again. """
global knife_state, knifeX, knifeY
collision_result = False
if ( knife_state == "fire" and isCollision( enemyX, enemyY, knifeX, knifeY ) ):
knife_state = "ready"
collision_result = True
return collision_result
Then create another function to separately draw the knife, if it's in the correct state.
def draw_knife( screen ):
""" If the knife is flying, draw it to the screen """
global knife_state, knifeImg, knifeX, knifeY
if ( knife_state == "fire" ):
screen.blit( knifeImg, ( knifeX, knifeY ) )
And, for the sake of completeness, a function to update the knife's position, and reset the knife_state when it goes off-screen.
def update_knife():
""" Make any knife fly up the screen, resetting at the top """
global knife_state, knifeX, knifeY, knifeY_change
# if the knife is already flying, move it
if ( knife_state == "fire" ):
knifeY -= knifeY_change
if ( knifeY <= 0 ):
knife_state = "ready" # went off-screen
So that gives a new main loop calling these functions:
#game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -2
if event.key == pygame.K_RIGHT:
playerX_change = 2
if event.key == pygame.K_UP:
playerY_change = -2
if event.key == pygame.K_DOWN:
playerY_change = 2
if event.key == pygame.K_SPACE:
if knife_state is "ready":
# Fire the knife at the coordinates of yoshi
fire_knife( playerX, playerY ) # create a new flying knife
# ...
# enemy movement
enemyX += enemyX_change
if enemyX <= 0:
enemyX_change = 2
enemyY += enemyY_change
elif enemyX > 645:
enemyX_change = -2
enemyY += enemyY_change
update_knife() # move the flying knife (if any)
if ( knife_hits( enemyX, enemyY ) ): # is there a knife-enemy-collision?
score += 1
print(score)
enemyX = random.randint(0,735)
enemyY = random.randint(50,150)
else:
draw_knife( screen ) # paint the flying knife (if any)
player(playerX,playerY)
enemy(enemyX,enemyY)
pygame.display.update()
Putting all the modifications to the knife position into functions makes your main loop simpler, and keeps most knife-code contained into a single group of functions. It would probably be better again to make a Knife class with these functions, but this is a simple start.

Why can't I use float numbers instead of integers?

import pygame
import random
pygame.init()
# create screen
screen = pygame.display.set_mode((1000, 600))
# Title + Logo
pygame.display.set_caption("Space Invader")
icon = pygame.image.load("chicken.png")
pygame.display.set_icon(icon)
# Player icon
player_icon = pygame.image.load("spaceship.png")
playerX = 400
playerY = 500
player_changeX = 0
player_changeY = 0
# enemy Player
enemy_icon = pygame.image.load("space-invaders.png")
enemyX = random.randint(0, 936)
enemyY = random.randint(-100, -50)
enemy_changeX = random.randint (0.1, 0.5)
enemy_changeY = random.randint (0.1, 0.5)
if enemyY >= 500:
print("Game over")
exit()
def player(x, y):
screen.blit(player_icon, (x, y))
def enemy(x, y):
screen.blit(enemy_icon, (x, y))
# game loop
running = True
while running:
# backround colour RGB
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If key pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_changeX = -1
if event.key == pygame.K_RIGHT:
player_changeX = 1
if event.key == pygame.K_UP:
player_changeY = -1
if event.key == pygame.K_DOWN:
player_changeY = 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player_changeX = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player_changeY = 0
# If player reaches boarder
if playerX >= 936:
playerX = 20
if playerX <= 0:
playerX = 936
if playerY <= 0:
playerY = 0
if playerY >= 550:
playerY = 550
# enemy control
if enemyX >= 936:
enemyX = 20
if enemyX <= 0:
enemyX = 936
if enemyY <= 0:
enemyY = 0
if enemyY >= 550:
enemyY = random.randint(-100, -50)
# Player change in coordinates
playerX += player_changeX
playerY += player_changeY
#enemy change in coordinates
enemyX += enemy_changeX
enemyY += enemy_changeY
#Results
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
I just got into programing, I am creating a little game. It's not finished yet but I am running into a problem I want to use float numbers instead of integers but it doesn't let me. Can you change this? and if yes how. The flaot number i want to use is in enemy_changeX and Y.
The error it's giving me is ,
line 212, in randrange
raise ValueError("non-integer arg 1 for randrange()")
ValueError: non-integer arg 1 for randrange()
even though I don't have a line 212
I hope the question was accurate enough.
First of all, you are requesting an integer between 0.1 and 0.5, which is not possible for obvious reasons.
To get a float you can use random.uniform(0.1, 0.5).
Although I have to note here, that pixels can't be float values, because there are no half pixels. Thus you have to think whether you really need a float value for a pixel change value.

Categories

Resources