Can someone help me with python keyboard movement? - python

I want to make squer move with keyboard input but its realy wierd. When i try to move it, it needs 2,5 seconds to actualy go, it has random speed ups, and if I click A so it goes left then I can click ANY key and it will go left like R or P, and controls can switch if I try to go up and left.
Code for player controlls is more down.
Code:
import pygame
from pygame.locals import *
pygame.init()
pygame.display.set_caption("Clicker")
# VALUES
clock = pygame.time.Clock()
coins: int = 0
running: bool = True
printed_s: bool = False
printed_sp: bool = False
printed_str: bool = False
f11: bool = False
stamina: int = 0
speed: int = 0
strength: int = 0
playerX: int = 650
playerY: int = 500
playerX_change: int = 0
playerY_change: int = 0
fps: int = 60
# UI/fonts
font_one = pygame.font.Font(None, 150)
surface_one = font_one.render('You beat the game', True, 'Green')
# MAIN LOOP
while running:
clock.tick(fps)
screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN, RESIZABLE)
screen.fill((130, 30, 90))
pygame.draw.rect(screen, (255, 0, 0), (playerX, playerY, 20, 20))
# FONTS
coin_font = pygame.font.Font(None, 30)
notification_font = pygame.font.Font(None, 50)
# SURFACE
coin_surface = coin_font.render(f'You have: {coins}', True, 'Green')
speed_surface = coin_font.render(f'Speed level: {speed}', True, 'Green')
stamina_surface = coin_font.render(f'Stamina level: {stamina}', True, 'Green')
strength_surface = coin_font.render(f'Strength level: {strength}', True, 'Green')
notification_surface = notification_font.render('Notifications', True, 'Green')
# BLIT
screen.blit(coin_surface, (0, 0))
screen.blit(speed_surface, (0, 630))
screen.blit(stamina_surface, (0, 680))
screen.blit(strength_surface, (0, 730))
screen.blit(notification_surface, (1130, 0))
# KEYS
for event in pygame.event.get():
# KEY DOWN
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.key == pygame.K_1 and coins >= 5:
coins -= 5
speed += 1
elif event.key == pygame.K_1 and coins < 5:
print("You need more coins")
if event.key == pygame.K_2 and coins >= 10:
coins -= 10
strength += 1
elif event.key == pygame.K_2 and coins < 10:
print("You need more coins")
if event.key == pygame.K_3 and coins >= 15:
coins -= 15
stamina += 1
elif event.key == pygame.K_3 and coins < 15:
print("You need more coins")
# PLAYER PART WHERE I NEED HELP
if event.key == pygame.K_a:
playerX_change -= 3
else:
playerX_change -= 0
if event.key == pygame.K_d:
playerX_change += 3
else:
playerX_change -= 0
if event.key == pygame.K_s:
playerY_change += 3
else:
playerY_change -= 0
if event.key == pygame.K_w:
playerY_change -= 3
else:
playerY_change -= 0
playerX += playerX_change
playerY += playerY_change
# MOUSE BUTTON DOWN
if event.type == pygame.MOUSEBUTTONDOWN:
pressed_keys = pygame.mouse.get_pressed()
if pressed_keys[0]:
coins += 1
# SHOP
if stamina == 30 and not printed_s:
print("You maxed stamina")
printed_s = True
if speed == 30 and not printed_sp:
print("You maxed speed")
printed_sp = True
if strength == 30 and not printed_str:
print("You maxed strength")
printed_str = True
# DRAW
pygame.draw.line(screen, 'Green', (1100, 0), (1100, 200), 5)
pygame.draw.line(screen, 'Green', (1100, 200), (1400, 200), 5)
pygame.draw.line(screen, 'White', (200, 250), (200, 700), 5)
pygame.draw.line(screen, 'White', (200, 700), (1100, 700), 5)
pygame.draw.line(screen, 'White', (1100, 700), (1100, 250), 5)
pygame.draw.line(screen, 'White', (200, 250), (1100, 250), 5)
# END
if strength == 30 and speed == 30 and stamina == 30:
screen.blit(surface_one, (250, 250))
pygame.display.update()

Related

Why is my game just not starting? I just added a list and 2 more loops but now it just wont start up [duplicate]

This question already has an answer here:
How to get more enemies to pop up after the snake has ate a block
(1 answer)
Closed 8 months ago.
I have a snake game but what's different is enemies spawn every time the snake eats a block. I've looked over the code and the game just won't display, does anyone know why? Any help is appreciated.
import sys,pygame
import random
pygame.display.set_caption('Snake Game')
screen_width, screen_height = 500,400
screen = pygame.display.set_mode((screen_width, screen_height))
fps = pygame.time.Clock()
snake_speed = 20
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(255, 0, 0)
pygame.init()
snake_position = [100, 50]
snake_body = [ [150, 80],
[100, 50],
[100, 50],
[80, 50]
]
food_position = [random.randrange(1, (screen_width//10)) * 10,
random.randrange(1, (screen_height//10)) * 10]
food_spawn = True
enemy_position = [random.randrange(1, (screen_width//10)) * 10,
random.randrange(1, (screen_height//10)) * 10]
enemy_spawn = True
This was the first thing I added. (The list)
enemy_list = [random.randrange(1, (screen_width//10)) * 10,
random.randrange(1, (screen_height//10)) * 10]
direction = 'RIGHT'
score = 0
def show_score(choice, color, font, size):
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Score : ' + str(score), True, color)
score_rect = score_surface.get_rect()
screen.blit(score_surface, score_rect)
blue = pygame.Color(0, 0, 255)
def game_over():
my_font = pygame.font.SysFont('comic sans', 50)
game_over_surface = my_font.render('Your Score is : ' + str(score), True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (screen_width/2, screen_height/4)
screen.blit(game_over_surface, game_over_rect)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
while True:
change_to = direction
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
change_to = 'UP'
if event.key == pygame.K_DOWN:
change_to = 'DOWN'
if event.key == pygame.K_LEFT:
change_to = 'LEFT'
if event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
if direction == 'UP':
snake_position[1] -= 10
if direction == 'DOWN':
snake_position[1] += 10
if direction == 'LEFT':
snake_position[0] -= 10
if direction == 'RIGHT':
snake_position[0] += 10
Then I added this loop and inserted the list
while True:
for enemy_position in enemy_list:
pygame.draw.rect(screen, red, pygame.Rect(
enemy_position[0], enemy_position[1], 10, 10))
for enemy_position in enemy_list:
if snake_position[0] == enemy_position[0] and snake_position[1] == enemy_position[1]:
game_over()
Then my another loop I put in. (and the list)
while True:
snake_body.insert(0, list(snake_position))
if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
score += 1
food_spawn = False
enemy_list.append(
[random.randrange(1, (screen_width//10)) * 10,
random.randrange(1, (screen_height//10)) * 10]
)
else:
snake_body.pop()
if not food_spawn:
food_position = [random.randrange(1, (screen_width//10)) * 10,
random.randrange(1, (screen_height//10)) * 10]
food_spawn = True
screen.fill(black)
for pos in snake_body:
pygame.draw.rect(screen, blue, pygame.Rect(
pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, green, pygame.Rect(
food_position[0], food_position[1], 10, 10))
if snake_position[0] < 0 or snake_position[0] > screen_width-10:
game_over()
if snake_position[1] < 0 or snake_position[1] > screen_height-10:
game_over()
for block in snake_body[1:]:
if snake_position[0] == block[0] and snake_position[1] == block[1]:
game_over()
show_score(1, white, 'comic sans', 20)
show_score(1, white, 'comic sans', 20)
pygame.display.update()
fps.tick(snake_speed)
From what I understand, you have written three separate while True methods. The first to take in controls, the second to do state control, and the third for actually drawing the game.
However, if you want all of these to run at once, they must be inside the same loop. At the moment, your first while True loop is running over and over again. Thus, your second and third loops, which actually draw the game out, are never running.

How do I update the text in python pygame when a certain command is true?

I'm trying to build a space invader-like game for fun.
It's mostly done, but when I shoot the enemy I want the text on the screen with his health to decrease.
Here is my code stripped only to the health updating part:
import pygame
from sys import exit
enemy_health = 10
pygame.init()
win = pygame.display.set_mode((1000, 1000))
pygame.display.set_caption("Fighter Pilot Go!")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
enemy_health_text -= 1
win.blit(enemy_health_text, (350, 60)
That's not all of the game, but it's the basic idea.
The score doesn't update in the game till a laser hits the enemy.
Here is the whole game, if the code helps you understand my issue:
import pygame
from sys import exit
import random
speed = 5
laser_speed = 7
bullets = []
score = 0
max_num_of_bullet = 3
background_speed = 3
enemy_health = 10
direction = True
enemy_speed = 7
pygame.init()
win = pygame.display.set_mode((1000, 1000))
pygame.display.set_caption("Fighter Pilot Go!")
clock = pygame.time.Clock()
background1 = pygame.image.load('assets/background.gif')
background2 = pygame.image.load('assets/background.gif')
background1_rect = background1.get_rect(topleft=(0, 0))
background2_rect = background2.get_rect(topleft=(0, -1000))
player = pygame.image.load('assets/player.gif')
player_rect = player.get_rect(midtop=(500, 750))
enemy = pygame.image.load('assets/enemy.gif')
enemy_rect = enemy.get_rect(center=(500, 350))
laser = pygame.image.load('assets/laser.gif')
# laser_rect = laser.get_rect(midtop=(500, 800))
font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
def is_collided_with(a, b):
return abs(a[0] - b.centerx) < 51 and abs(a[1] - b.centery) < 51
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if len(bullets) <= max_num_of_bullet - 1:
bullets.append([player_rect.x + 49, player_rect.y - 60])
elif len(bullets) > max_num_of_bullet - 1:
continue
else:
print("Something Weird is Happening!")
key = pygame.key.get_pressed()
if key[pygame.K_a]:
player_rect.x -= speed
if key[pygame.K_d]:
player_rect.x += speed
win.blit(background1, background1_rect)
win.blit(background2, background2_rect)
win.blit(player, player_rect)
win.blit(enemy, enemy_rect)
background1_rect.y += background_speed
background2_rect.y += background_speed
if direction:
enemy_rect.x -= enemy_speed
elif not direction:
enemy_rect.x += enemy_speed
if enemy_rect.x <= 0:
direction = False
elif enemy_rect.x >= 900:
direction = True
if player_rect.x < -20:
player_rect.x = 1020
if player_rect.x > 1020:
player_rect.x = -20
for bullet in bullets:
win.blit(laser, bullet)
for bullet in bullets:
bullet[1] -= laser_speed
win.blit(enemy_health_text, (350, 60))
for bullet in bullets:
if is_collided_with(bullet, enemy_rect):
bullets.remove(bullet)
enemy_health -= 1
for bullet in bullets:
if bullet[1] < 0:
bullets.remove(bullet)
if background1_rect.y >= 1000:
background1_rect.topleft = (0, -1000)
if background2_rect.y >= 1000:
background2_rect.topleft = (0, -1000)
if enemy_health <= 0:
pass
pygame.display.update()
clock.tick(60)
Any help would be appreciated. :) Thanks!
The text is rendered in the enemy_health_text Surface with the value of enemy_health. You have to change enemy_health and render the text again:
font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
enemy_health -= 1
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
win.fill(0)
win.blit(enemy_health_text, (350, 60)
pygame.display.flip()

Starting a game when countdown is over pygame

So I have this code that's my main game:
def game():
running = True
import pygame, sys
import random
import math as m
mainClock = pygame.time.Clock()
pygame.init()
pygame.font.init
pygame.display.set_caption('Ping Pong')
SCREEN = width, height = 900,600
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0,0,0)
speed = [4,4]
font = pygame.font.Font('freesansbold.ttf', 32)
score = 0
score = str(score)
font.size(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen = pygame.display.set_mode(SCREEN, 0,32)
height1 = height/4
score = int(score)
ball = pygame.Rect(width/2, height/2, 50,50)
player = pygame.Rect(0,(height/2),25,height1)
player_1 = pygame.Rect(width - 25,(height/2),25,height1)
font1 = pygame.font.Font('freesansbold.ttf', 32)
score1 = 0
score1 = str(score)
font1.size(score1)
font1.set_bold(True)
text1 = font1.render(score1, True, white)
score1 = int(score1)
textRect1 = text1.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
up = False
down = False
up_1 = False
down_1 = False
RED = (255,0,0)
particles = []
while running:
color = (192,192,192)
# clear display #
screen.fill((0,0,0))
screen.blit(text, textRect)
screen.blit(text1, textRect1)
bx = ball.centerx
by = ball.centery
particles.append([[bx, by],[random.randint(0,20) / 10 - 1, -1], random.randint(4,6)])
for particle in particles:
particle[0][0] += particle[1][0]
particle[0][1] += particle[1][1]
particle[2] -= 0.1
particle[1][1] += 0.1
pygame.draw.circle(screen, color, [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
if particle[2] <= 0:
particles.remove(particle)
if up == True:
player.y -= 5
if down == True:
player.y += 5
if up_1 == True:
player_1.y -= 5
if down_1 == True:
player_1.y += 5
if player.top < 0 :
player.y = 0
if player.bottom > height:
player.bottom = height
if player_1.top < 0 :
player_1.y = 0
if player_1.bottom > height :
player_1.bottom = height
for i in range(-90,(height + 130), 120):
rectangle = pygame.Rect((width/2), i, 13, 60)
pygame.draw.rect(screen, (255,255,255), rectangle)
pygame.draw.rect(screen,(191, 224, 255),player)
pygame.draw.rect(screen,(191, 224, 255),player_1)
color = (192,192,192)
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
pygame.draw.rect(screen,color,ball, 3)
import time
ball.x += speed[0]
ball.y += speed[1]
if ball.top < 0 or ball.bottom > height:
speed[1] = -speed[1]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
pygame.draw.circle(screen, (r,b,g), [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
dab = random.randint(0,1)
if ball.left < 0 :
font = pygame.font.Font('freesansbold.ttf', 32)
score1 = int(score1)
score1 += 1
score1 = str(score1)
font.set_bold(True)
text1 = font.render(score1, True, white)
textRect1 = text.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
screen.blit(text1, textRect1)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
if ball.right > width:
font = pygame.font.Font('freesansbold.ttf', 32)
score = int(score)
score += 1
score = str(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen.blit(text, textRect)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
# event handling #
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_s:
down = True
if event.key == K_w:
up = True
if event.key == K_UP:
up_1 =True
if event.key == K_ESCAPE:
running = False
if event.key == K_DOWN:
down_1 = True
if event.type == KEYUP:
if event.key == K_s:
down = False
if event.key == K_w:
up = False
if event.key == K_UP:
up_1 = False
if event.key == K_DOWN:
down_1 = False
if ball.colliderect(player_1):
dab = random.randint(0,1)
if dab == 1:
speed[1] = -speed[1]
speed[0] = -speed[0]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
if ball.colliderect(player):
speed[0] = -speed[0]
speed[0] = random.randint(4,6)
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
# update display #
pygame.display.update()
mainClock.tick(60)
and I have a menu screen that displays some options. Only button_1 works.:
def main_menu():
while True:
white = (255,255,255)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
screen.fill((0,0,0))
button_1 = pygame.Rect(width/2, (height/2), width/2, 50)
button_1.centerx = width/2
button_2 = pygame.Rect(width/2, height/1.5, width/2, 50)
button_2.centerx = width/2
pygame.draw.rect(screen, (255, 0, 0), button_1)
pygame.draw.rect(screen, (255, 0, 0), button_2)
#draw_text('Start!', font, (255, 255, 255), screen, button_1.centerx, button_1.centery)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
text1 = font.render('Start!', True, white)
textRect1 = text1.get_rect()
textRect1.center = (button_1.centerx, button_1.centery)
screen.blit(text1, textRect1)
mx, my = pygame.mouse.get_pos()
if button_1.collidepoint((mx, my)):
if click:
game()
if button_2.collidepoint((mx, my)):
if click:
options()
click = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
clock.tick(60)
How do I make it so that after button_1 is pressed, there's a 3,2,1 countdown on the screen, and then the game starts?
In order to do the countdown, you import the time module:
import time
...then you need a for loop, with a step -1, counting down from 3 to 1. Inside the for loop, print the numbers and sleep one second, using the time module:
for a in range(3,0,-1):
print(a)
time.sleep(1)
After this for loop, you put the rest of your code.

isCollision function in pygame

I recently started programming in pygame and I've been wondering why doesn't my isCollision function work. You don't really have to run the code, because you will need to download the pictures to make it execute. If you can, just tell my why the isCollision function doesn't work. In the mainloop where there is a for i in range(num_of_obstacles) loop there is the if iscollision statement. If you want to see what the program does, here are all the essential files:
Btw don't rewrite the entire code pls.]2[]3
Don't mind the comments cause theyre in polish.
Here is my code:
import pygame
import math
import random
#inicjowanie pygame (to trzeba zawsze dać)
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Kosmiczna Przygoda')
playericon = pygame.image.load('rocket.png')
player2icon = pygame.image.load('rocket.png')
backgroundImg = pygame.image.load('1083.jpg')
num_of_obstacles = 10
obstacleImg = []
obsX = [random.randint(0, 400) for i in range(num_of_obstacles // 2)]
obs2X = [random.randint(400, 800) for i in range(num_of_obstacles // 2)]
for i in obs2X:
obsX.append(i)
obsY = []
for i in range(num_of_obstacles):
obstacleImg.append(pygame.image.load('rectangle.png'))
for i in range(num_of_obstacles):
obsY.append(random.randint(50, 300))
# pierwsze koordynaty
PlayerX, PlayerY = 200, 480
Player2X, Player2Y = 500, 480
PlayerY_change, PlayerX_change = 1, 1
Player2Y_change, Player2X_change = 1, 1
def player(x,y,x2,y2):
screen.blit(playericon, (x, y))
screen.blit(player2icon, (x2, y2))
winFont = pygame.font.Font('freesansbold.ttf', 64)
won1, won2 = False, False
def player1Wins():
win_text = winFont.render('PLAYER 1 WON!',True,(255,255,255))
screen.blit(win_text,(30,30))
def player2Wins():
win_text = winFont.render('PLAYER 2 WON!',True,(255,255,255))
screen.blit(win_text,(150,30))
# wzór matematyczny na odległość koordynatów dwóch punktów (sprawdzabnie czy się dotykają)
def isCollision(obsX,obsY,pX,pY):
distance = math.sqrt(math.pow(obsX - pX, 2) + math.pow(obsY - pY, 2))
if distance >= 27:
return True
else:
return False
running = True
won = False
while running:
# tło (blit to rysowanie)
screen.blit(backgroundImg, (0, 0))
# event to wydarzenie zarejestrowane przez program
# jeżeli klikne krzyzyk w prawym gornym rogu to program sie zamknie
# jeżeli nacisne np strzalke w prawo to rakieta przesuwa się na ukos w prawo
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
PlayerX_change = -1
if event.key == pygame.K_d:
PlayerX_change = 1
if event.key == pygame.K_LEFT:
Player2X_change = -1
if event.key == pygame.K_RIGHT:
Player2X_change = 1
if event.key == pygame.K_w:
PlayerY_change = 2
if event.key == pygame.K_UP:
Player2Y_change = 2
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
PlayerY2_change = 0.75
if event.key == pygame.K_w:
PlayerY_change = 0.75
for enemy in range(num_of_obstacles):
if won:
screen.blit(obstacleImg[enemy], (2000, 2000))
else:
#if isCollision(obsX[enemy], obsY[enemy],PlayerX,PlayerY):
#player2Wins()
screen.blit(obstacleImg[enemy], (obsX[enemy], obsY[enemy]))
# Granice Ekranu
if PlayerX <= 0:
PlayerX = 0
elif PlayerX >= 736:
PlayerX = 736
if PlayerY <= 0:
won, won1 = True, True
PlayerY, Player2Y = 480, 480
PlayerX, Player2X = 200, 500
if Player2X <= 0:
Player2X = 0
elif Player2X >= 736:
Player2X = 736
if Player2Y <= 0:
won, won2 = True, True
PlayerY, Player2Y = 480, 480
PlayerX, Player2X = 200, 500
if won1:
player1Wins()
PlayerX_change, PlayerY_change = 0, 0
Player2X_change, Player2Y_change = 0, 0
if won2:
player2Wins()
PlayerX_change, PlayerY_change = 0, 0
Player2X_change, Player2Y_change = 0, 0
# Zmiana kordynatów rakiety
PlayerX += PlayerX_change
PlayerY -= PlayerY_change
Player2X += Player2X_change
Player2Y -= Player2Y_change
player(PlayerX, PlayerY, Player2X, Player2Y)
pygame.display.update()
Should you be checking if the distance is <= 27 rather than >= 27?
def isCollision(obsX, obsY, pX, pY):
distance = math.sqrt(math.pow(obsX - pX, 2) + math.pow(obsY - pY, 2))
return distance <= 27

Variables and Surface won't Update in Python/Pygame

I am trying to make my game have special abilities for the player, but am having some issues. For some reason user_health_active and user_health_display_active do not update after reaching round 10. I can't figure out why this is and have been attempting to for about two hours. By the seems of it, not only does the surface not update, but the actual background function doesn't either. If anyone can provide me some insight on why this isn't working, please let me know. Here is my code.
"""
Game Developer: Austin H.
Game Owner: Austin H.
Licensed Through: theoiestinapps
Build: 2
Version: 1.0.1
"""
import os
import pygame as pygame
import random
import sys
import time
pygame.init()
left = False
right = False
playerDead = False
devMode = False
game_completed = False
game_level_score = (0)
game_display_score = (0)
enemy_speed = (5)
user_teleport_active = False
user_health_active = False
user_teleport_display_active = ("False")
user_health_display_active = ("False")
display_width = 800
display_height = 600
customBlue = (17, 126, 194)
black = (0, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
red = (255, 0, 0)
white = (255, 255, 255)
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Space Dodge")
clock = pygame.time.Clock()
backgroundMusic = pygame.mixer.music.load('C:/Program Files/Space Dodge/game_background_music.mp3')
enemyImg = pygame.image.load('C:/Program Files/Space Dodge/enemy_image.png')
backgroundImg = pygame.image.load('C:/Program Files/Space Dodge/background_image.png')
rocketImg = pygame.image.load('C:/Program Files/Space Dodge/player_image.png')
injuredSound = pygame.mixer.Sound('C:/Program Files/Space Dodge/player_hurt_sound.wav')
def teleport_powerup(user_teleport_display_active):
font = pygame.font.SysFont(None, 25)
text = font.render("Teleport Powerup: " + str(user_teleport_display_active), True, red)
gameDisplay.blit(text, (display_width - 205, 5))
def ehealth_powerup(user_health_display_active):
font = pygame.font.SysFont(None, 25)
text = font.render("Ehealth Powerup: " + str(user_health_display_active), True, red)
gameDisplay.blit(text, (display_width - 205, 25))
def enemies_dodged(enemy_objects_dodged):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodge Asteroids: " + str(enemy_objects_dodged), True, green)
gameDisplay.blit(text, (5, 5))
def game_level(game_display_score):
font = pygame.font.SysFont(None, 25)
game_display_score = game_level_score + 1
text = font.render("Game Level: " + str(game_display_score), True, green)
gameDisplay.blit(text, (5, 25))
def enemies(enemyx, enemyy, enemyw, enemyh, color):
pygame.draw.rect(gameDisplay, color, [enemyx, enemyy, enemyw, enemyh])
def rocket(x, y):
gameDisplay.blit(rocketImg, (x, y))
def background(cen1, cen2):
gameDisplay.blit(backgroundImg, (cen1, cen2))
def text_objects(text, font):
textSurface = font.render(text, True, blue)
return textSurface, textSurface.get_rect()
def message_display(text):
global game_completed
largeText = pygame.font.Font('freesansbold.ttf', 70)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
if game_completed == True:
time.sleep(300)
else:
time.sleep(5)
if game_level_score > 0:
pass
else:
pygame.mixer.music.play()
game_loop()
def crash():
injuredSound.play()
message_display("You Died. Game Over!")
def game_loop():
global left
global right
global playerDead
global game_level_score
global enemy_speed
global game_completed
global user_teleport_active
global user_teleport_display_active
global user_health_active
global user_health_display_active
x = (display_width * 0.43)
y = (display_height * 0.74)
cen1 = (0)
cen2 = (0)
x_change = 0
rocket_width = (86)
game_score = (0)
enemy_objects_dodged = (0)
enemy_startx = random.randrange(0, display_width)
enemy_starty = -600
enemy_width = 100
enemy_height = 100
while not playerDead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.mixer.music.stop()
playerDead = True
if devMode == True:
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
left = True
if event.key == pygame.K_d:
right = True
if event.key == pygame.K_LEFT:
left = True
if event.key == pygame.K_RIGHT:
right = True
if event.key == pygame.K_KP4:
left = True
if event.key == pygame.K_KP6:
right = True
if event.key == pygame.K_ESCAPE:
playerDead = True
if event.key == pygame.K_SPACE:
game_level_score += 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or pygame.K_d:
left = False
if event.key == pygame.K_d:
right = False
if event.key == pygame.K_LEFT:
left = False
if event.key == pygame.K_RIGHT:
right = False
if event.key == pygame.K_KP4:
left = False
if event.key == pygame.K_KP6:
right = False
if event.key == pygame.K_SPACE:
pass
if left and right:
x_change *= 1
elif left and x > -86:
x_change = -5
elif right and x < (display_width - 89):
x_change = 5
else:
x_change = 0
if game_score == 10:
enemy_speed += 0.5
game_level_score += 1
if game_level_score == 49:
game_completed = True
message_display('Game Complete!')
else:
message_display('Levels Completed: %s' % game_level_score)
if game_level_score > 4:
user_teleport_active = True
user_teleport_display_active = ("True")
elif game_level_score > 9:
user_health_active = True
user_health_display_active = ("True")
if user_teleport_active == True:
if x < -0:
x = 850
if enemy_starty > display_height:
enemy_starty = 0 - enemy_height
enemy_startx = random.randrange(0, display_width)
game_score += 1
enemy_objects_dodged += 1
if y < enemy_starty + enemy_height:
if x > enemy_startx and x < enemy_startx + enemy_width or x + rocket_width > enemy_startx and x + rocket_width < enemy_startx + enemy_width:
pygame.mixer.music.stop()
game_level_score = (0)
user_teleport_active = False
user_teleport_display_active = ("False")
crash()
x += x_change
background(cen1, cen2)
enemies(enemy_startx, enemy_starty, enemy_width, enemy_height, customBlue)
enemy_starty += enemy_speed
rocket(x, y)
enemies_dodged(enemy_objects_dodged)
game_level(game_display_score)
teleport_powerup(user_teleport_display_active)
ehealth_powerup(user_health_display_active)
pygame.display.update()
clock.tick(90)
pygame.mixer.music.set_volume(0.20)
pygame.mixer.music.play(-1)
game_loop()
pygame.quit()
quit()
The code that modifies the variables you mention will never be run. Here's the relevant bit:
if game_level_score > 4:
user_teleport_active = True
user_teleport_display_active = ("True")
elif game_level_score > 9:
user_health_active = True
user_health_display_active = ("True")
Because you're using an if and an elif, the condition for the second block is only ever tested if the first block's condition was false. Since any value greater than 9 is also going to be greater than 4, the second block will never run.
If you want the two conditions to be tested independently, you need to just use plain if statements for both conditions. If you only want one block to run , you either need to extend the first condition to 4 < game_level_score <= 9 or you need to change the order so that the > 9 test comes before the > 4 test.

Categories