Losing a "life" won't go down after an error? pygame - python

And I don't know why??? Everything else seems to be working just fine.. but when you click the wrong "button" in the game the error sounds works and it resets the pattern, but the lives that I have put up (which is 3) doesn't go down at all. Wondering if anyone could help me out with this please? (I won't be pasting my entire code, but this is where the command happens and all). Also if you couldn't tell, I'm creating a memory game. If anyone could lead me into the right direction then that could be a big help for me. Thanks in advance!
def main():
global FPSCLOCK, DISPLAYSURF, BASICFONT, BEEP1, BEEP2, BEEP3, BEEP4
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Simulate')
# font
BASICFONT = pygame.font.Font(None, 30)
# load the sound files
BEEP1 = pygame.mixer.Sound('beep1.wav')
BEEP2 = pygame.mixer.Sound('beep2.wav')
BEEP3 = pygame.mixer.Sound('beep3.wav')
BEEP4 = pygame.mixer.Sound('beep4.wav')
SOUNDTRACK = pygame.mixer.Sound('soundtrack.wav')
ERROR = pygame.mixer.Sound('error.wav')
# initialize some variables for a new game
pattern = [] # stores the pattern of colors
currentStep = 0 # the color the player must push next
lastClickTime = 0 # timestamp of the player's last button push
score = 0
# plays the soundtrack music
SOUNDTRACK.play(-1, 0, 1000)
# start-up screen
text = BASICFONT.render('Press enter to play!', 1, WHITE)
textRect = text.get_rect()
textRect.centerx = DISPLAYSURF.get_rect().centerx
textRect.y = 150
DISPLAYSURF.blit(text, textRect)
# update the screen
pygame.display.update()
# the "press enter" command
waiting = True
while waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
waiting = False
# when False, the pattern is playing. when True, waiting for the player to click a colored button:
waitingForInput = False
while True: # main game loop
clickedButton = None # button that was clicked (set to YELLOW, RED, GREEN, or BLUE)
DISPLAYSURF.fill(bgColor)
drawButtons()
# amount of lives
lives = 3
img = BASICFONT.render('I'*lives, 1, WHITE)
livesRect = img.get_rect()
livesRect.topleft = (10, 10)
DISPLAYSURF.blit(img, livesRect)
scoreSurf = BASICFONT.render('Score: ' + str(score), 1, WHITE)
scoreRect = scoreSurf.get_rect()
scoreRect.topleft = (WIDTH - 100, 10)
DISPLAYSURF.blit(scoreSurf, scoreRect)
checkForQuit()
for event in pygame.event.get(): # event handling loop
if event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
clickedButton = getButtonClicked(mousex, mousey)
if not waitingForInput:
# play the pattern
pygame.display.update()
pygame.time.wait(1000)
pattern.append(random.choice((YELLOW, BLUE, RED, GREEN)))
for button in pattern:
flashButtonAnimation(button)
pygame.time.wait(FLASHDELAY)
waitingForInput = True
else:
# wait for the player to enter buttons
if clickedButton and clickedButton == pattern[currentStep]:
# pushed the correct button
flashButtonAnimation(clickedButton)
currentStep += 1
lastClickTime = time.time()
if currentStep == len(pattern):
# pushed the last button in the pattern
score += 1
waitingForInput = False
currentStep = 0 # reset back to first step
elif (clickedButton and clickedButton != pattern[currentStep]) or (currentStep != 0 and time.time() - TIMEOUT > lastClickTime):
# pushed the incorrect button, or has timed out
pattern = []
currentStep = 0
waitingForInput = False
lives = lives - 1
SOUNDTRACK.stop()
ERROR.play()
pygame.time.wait(1000)
SOUNDTRACK.play(-1, 0, 1000)
pygame.display.update()
if lives < 1:
gameOverAnimation()
# reset the variables for a new game:
pattern = []
currentStep = 0
waitingForInput = False
score = 0
pygame.time.wait(1000)
pygame.display.update()
FPSCLOCK.tick(FPS)

You set lives = 3 inside your main loop, instead of before it.
This means that you reset it to 3 on every iteration of the loop.

Related

My pygame timer keeps resetting after I hit a target in my aim game

I am trying to make an aim game where a target pops up and once the player clicks on it, the target vanishes and a new one appears in a random location, I want it so that there is a 10 second timer but it keeps going back to 10 each time a target is "hit"
import pygame, random as r, time
FPS = 60
WIDTH = 900
HEIGHT = 500
WHITE = 255,255,255
BG = 26,26,26
RANGEXMIN = 20
RANGEXMAX = 840
RANGEYMIN = 20
RANGEYMAX = 440
window = pygame.display.set_mode((WIDTH, HEIGHT))
tick = pygame.USEREVENT
pygame.time.set_timer(tick,1000)
pygame.font.init()
FONT = pygame.font.Font('slkscr.ttf', 50)
def aim_train():
def new_target(countdown,text):
clock = pygame.time.Clock()
x = r.randint(RANGEXMIN, RANGEXMAX)
y = r.randint(RANGEYMIN, RANGEYMAX)
hit = False
while not hit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.USEREVENT:
if event.type == tick:
countdown= countdown - 1
text = str(countdown)
clock.tick(FPS)
window.fill(BG)
timer = FONT.render(text, False, WHITE)
window.blit(timer, (435, 20))
pygame.mouse.set_visible(False)
pos = pygame.mouse.get_pos()
pos_x = pos[0]
pos_y = pos[1]
target = pygame.draw.rect(window, WHITE, (x,y,50,50))
cursor_outline = pygame.draw.circle(window, BG, (pos_x,pos_y), 11)
cursor = pygame.draw.circle(window, WHITE,(pos_x,pos_y) ,10)
hit = (pygame.mouse.get_pressed()[0] and target.colliderect(cursor_outline))
pygame.display.update()
run = True
countdown = 10
text = str(countdown)
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(BG)
pygame.mouse.set_visible(False)
new_target(countdown,text)
pygame.quit()
aim_train()
The variable "counter" somehow gets reset back to 10 after ever successful hit on a target
The problem is that you use a seperate function, new_target, for each target.
The countdown variable is defined inside the scope of the function aim_train. Because the new_target function is defined inside the aim_train function, it is a nested function and it can use all the variables that are defined inside aim_train. However, the new_target function still has its own scope. It can make changes to any variables defined inside aim_train, but those changes remain in its own scope. When a call of new_target is ended, its scope is discarded and all changes to the variables of aim_target are undone. This causes the countdown variable to be reset every in new call of new_target and thus every time a new target is created.
You might also have noticed that you can't close your window. The window doesn't react to clicking the red cross. This is because the same applies to the run variable. When you click the red cross, the run variable is set to True inside new_target, but not in the scope of aim_train. As such, the main loop in aim_train is not quitted and the program continues.
As a solution to this problem, I would recommend to include all the code of new_target into the aim_train function. Then you only have one function, which makes that all changes to variables are in the same scope and no changes are discarded:
import pygame, random as r, time
pygame.init()
FPS = 60
WIDTH = 900
HEIGHT = 500
WHITE = 255,255,255
BG = 26,26,26
RANGEXMIN = 20
RANGEXMAX = 840
RANGEYMIN = 20
RANGEYMAX = 440
window = pygame.display.set_mode((WIDTH, HEIGHT))
tick = pygame.USEREVENT
pygame.time.set_timer(tick,1000)
pygame.font.init()
FONT = pygame.font.SysFont('arial', 50)
def aim_train():
run = True
hit = False
countdown = 10
text = str(countdown)
x = r.randint(RANGEXMIN, RANGEXMAX)
y = r.randint(RANGEYMIN, RANGEYMAX)
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)#switched
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == tick: #changed
countdown= countdown - 1
text = str(countdown)
window.fill(BG)
timer = FONT.render(text, False, WHITE)
window.blit(timer, (435, 20))
pos = pygame.mouse.get_pos()
pos_x = pos[0]
pos_y = pos[1]
target = pygame.draw.rect(window, WHITE, (x,y,50,50))
cursor_outline = pygame.draw.circle(window, BG, (pos_x,pos_y), 11)
cursor = pygame.draw.circle(window, WHITE,(pos_x,pos_y) ,10)
hit = (pygame.mouse.get_pressed()[0] and target.colliderect(cursor_outline))
if hit:
hit = False
x = r.randint(RANGEXMIN, RANGEXMAX)
y = r.randint(RANGEYMIN, RANGEYMAX)
pygame.display.update()
pygame.quit()
aim_train()
Apart from fixing the problem, I have also restructured your code a bit and did the following changes:
I have changed:
elif event.type == pygame.USEREVENT:
if event.type == tick:
into:
elif event.type == tick:
Outside of the aim_train function, you have stated that tick and pygame.USEREVENT are equal. As such, it is useless to compare to them two times, because if the first check is true, then the second one will certainly be.
I've placed pygame.mouse.set_visible(False) outside of the main loop.
Calling the function sets the mouse invisible untill another call changes sets the mouse back to visible. As such, it is useless to call it multiple times in the loop.
There are actually 2 countdown variables, one in the new_target function and one in the aim_train function. If you change the variable countdown in the new_target function, this will not change the variable countdown in the aim_train function. You must return the new value of countdown from the new_target function:
def aim_train():
def new_target(countdown):
# [...]
while not hit:
for event in pygame.event.get():
# [...]
elif event.type == pygame.USEREVENT:
if event.type == tick:
countdown= countdown - 1
# [...]
return countdown
run = True
countdown = 10
while run:
# [...]
countdown = new_target(countdown)
However, I suggest that you restructure your code. Do not use nested application loops. Also see Pygame mouse clicking detection:
import pygame, random as r
FPS = 60
WIDTH = 900
HEIGHT = 500
WHITE = 255,255,255
BG = 26,26,26
RANGEXMIN = 20
RANGEXMAX = 840
RANGEYMIN = 20
RANGEYMAX = 440
window = pygame.display.set_mode((WIDTH, HEIGHT))
tick = pygame.USEREVENT
pygame.time.set_timer(tick,1000)
pygame.font.init()
FONT = pygame.font.Font('slkscr.ttf', 50)
def new_target():
x = r.randint(RANGEXMIN, RANGEXMAX)
y = r.randint(RANGEYMIN, RANGEYMAX)
return x, y
def aim_train():
clock = pygame.time.Clock()
pygame.mouse.set_visible(False)
run = True
countdown = 10
hits = 0
countdownSurf = FONT.render(f'time {countdown}', False, WHITE)
hitsSurf = FONT.render(f'hits {hits}', False, WHITE)
target = pygame.Rect(0, 0, 50, 50)
target.center = new_target()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == tick:
countdown -= 1
countdownSurf = FONT.render(f'time {countdown}', False, WHITE)
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if target.collidepoint(event.pos):
target.center = new_target()
hits += 1
hitsSurf = FONT.render(f'hits {hits}', False, WHITE)
pos = pygame.mouse.get_pos()
window.fill(BG)
window.blit(countdownSurf, countdownSurf.get_rect(center = (300, 45)))
window.blit(hitsSurf, hitsSurf.get_rect(center = (600, 45)))
pygame.draw.rect(window, WHITE, target)
pygame.draw.circle(window, BG, pos, 11)
pygame.draw.circle(window, WHITE, pos, 10)
pygame.display.update()
pygame.quit()
aim_train()

Clicking recs in Pygame

I am currently starting on python3 in the past few days and started in developing minor projects, but i'm having some trouble, so sorry if i cant use top notch proffessional coders language.
How can I make a pygame.draw.rect rectangle become clickable?
I know about the pygame.mouse. ones, but there might be something wrong in the code.
I want it so that when i press the red rect it will decreese i health and will add a "burn" stat (its just text for now).
Here's the code:
import pygame
import random
import sys
pygame.init()
#Screen Size
screen_width = 600
screen_height = 600
#Screen Settings
screen = pygame.display.set_mode((screen_width, screen_height))
br_color = (0, 0, 0)
pygame.display.set_caption("Type Effect Beta 0.0.1")
#Game Over Bullian
game_over = False
#Other Defenitions
clock = pygame.time.Clock()
myFont = pygame.font.SysFont("arial", 20)
#Basic Recources
health = 50
score = 0
status = "none"
#Colors for the Text
white = (255, 255, 255)
red = (255, 0, 0)
#Mouse Things
mouse_location = pygame.mouse.get_pos()
print(mouse_location)
#Status Text Helpers
burning = "Burning"
#Cards
card_size_x = 45
card_size_y = 60
fire_car_color = (255, 0 ,0)
fire_card_posx = 300
fire_card_posy = 300
card_button_fire = pygame.Rect(fire_card_posx, fire_card_posy, card_size_x, card_size_y)
#Functions
def health_decrease_burn(health, status):
health -= 1
status = "burning"
return health and status
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if pygame.mouse.get_pressed()[0] and card_button_fire.collidepoint(mouse_location):
health_decrease_burn()
if health_decrease_burn(health, status) and health <= 0:
game_over = True
text = "Score:" + str(score)
lable = myFont.render(text, 1, white)
screen.blit(lable, (10, 10))
text = "Health:" + str(health)
lable = myFont.render(text, 1, red)
screen.blit(lable, (10, 30))
text = "Status:" + str(status)
lable = myFont.render(text, 1, white)
screen.blit(lable, (10, 50))
pygame.draw.rect(screen, fire_car_color, (fire_card_posx, fire_card_posy, card_size_x, card_size_y))
clock.tick(30)
pygame.display.update()
You need to grab the mouse_location every iteration of your main loop, as the mouse position/state is constantly changing. The current code is only fetching the mouse position once, on start.
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP: # if mouse button clicked
mouse_location = pygame.mouse.get_pos() # <-- HERE
if pygame.mouse.get_pressed()[0] and card_button_fire.collidepoint(mouse_location):
health_decrease_burn()
#[...etc ]

Trying to delay a specific function for spawning enemy after a certain amount of time

I am making a mole shooter game using pygame. I want my mole to spawn at a random position after every 1 second. I have tried using time.sleep(1.0) but that delays my whole code and thus the game doesn't function properly because of delayed responses. I am moving an aim using the mouse(which also gets affected because of time.sleep) to which i will be adding a click to shoot. I need help with delaying and spawning my mole. I would also like some opinions on how to organize my code to provide various levels of difficulty and a main menu later on.
import pygame
import random
import time
from threading import Timer
pygame.font.init()
win_width = 1000
win_height = 710
FPS = 60
screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("Mole Shooter")
white = (255,255,255)
red = (255, 0, 0)
counter, text = 30, 'Time Left: 30'.rjust(3)
pygame.time.set_timer(pygame.USEREVENT, 1000)
font = pygame.font.Font('freesansbold.ttf', 32)
run = True
clock = pygame.time.Clock()
background = pygame.transform.scale(pygame.image.load('back_land.png'), (win_width, win_height))
aim = pygame.image.load("aim.png")
mole = pygame.image.load("mole.png")
def mole_spawn_easy():
molex = random.randint(50, 950)
moley = random.randint(450, 682)
screen.blit(mole, (molex, moley))
while run:
screen.blit(background, [0,0])
ax, ay = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.USEREVENT:
counter -= 1
text = ("Time Left: " + str(counter)).rjust(3)
if counter > 0:
time.sleep(1.0);mole_spawn_easy()
else:
print("game over")
break
screen.blit(aim, ((ax - 32 ),(ay - 32)))
screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))
clock.tick(FPS)
pygame.display.flip()
In pygame exists a timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue.. The time has to be set in milliseconds:
pygame.time.set_timer(pygame.USEREVENT, 1000) # 1 second
Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case the value of pygame.USEREVENT is the event id for the timer event.
Receive the event in the event loop:
running = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.USEREVENT:
# [...]
The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer.
See also Spawning multiple instances of the same object concurrently in python.
Create a list of moles and add a random position to the list in mole_spawn_easy:
moles = []
def mole_spawn_easy():
molex = random.randint(50, 950)
moley = random.randint(450, 682)
moles.append((molex, moley))
Draw the moles in the main application loop:
while run:
# [...]
for pos in moles:
screen.blit(mole, pos)
See the example:
moles = []
def mole_spawn_easy():
molex = random.randint(50, 950)
moley = random.randint(450, 682)
moles.append((molex, moley))
pygame.time.set_timer(pygame.USEREVENT, 1000)
while run:
ax, ay = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.USEREVENT:
counter -= 1
text = ("Time Left: " + str(counter)).rjust(3)
if counter > 0:
mole_spawn_easy()
else:
print("game over")
screen.blit(background, [0,0])
for pos in moles:
screen.blit(mole, pos)
screen.blit(aim, ((ax - 32 ),(ay - 32)))
screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))
pygame.display.flip()
clock.tick(FPS)

Pygame Not Responding First Time

I'm just adding some finishing touches to my tank game, but there's this slight thing that's been bothering me. It's just that, at the menu screen, when the user presses a different set of keys to access different things such as the instruction screen, game screen, or custom username input screen, it takes two presses of the button to respond and not the desired one single press. Here's the little excerpt of code:
menu = True
instruct = False
run = False
name1 = False
name2 = False
while menu:
pygame.event.get()
theKey = pygame.key.get_pressed()
if theKey[pygame.K_RETURN]:
menu = False
run = False
instruct = True
name1 = False
if theKey[pygame.K_LSHIFT] or theKey[pygame.K_RSHIFT]:
menu = False
run = True
begin = time.time()
if theKey[pygame.K_BACKSPACE]:
menu = False
run = False
instruct = False
name1 = True
user_input = ''
menu_screen()
FONT = pygame.font.Font(None, 40) # A font object which allows you to render text.
BG_COLOR = pygame.Color('gray12')
BLUE = pygame.Color('dodgerblue1')
USEFONT = pygame.font.Font(None, 70)
yourText1 = "Player 1, Enter Your Name: "
yourText2 = "Player 2, Enter Your Name: "
userNamePrompt = USEFONT.render(yourText1, True, BLUE)
userNamePrompt2 = USEFONT.render(yourText2, True, BLUE)
while name1:
theKey = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
name1 = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
user_input = user_input[:-1]
elif event.key == pygame.K_RETURN:
name1 = False
name2 = True
user2_input = ''
else:
user_input += event.unicode
screen.fill(BG_COLOR)
# Create the text surface.
text = FONT.render(user_input, True, BLUE)
# And blit it onto the screen.
screen.blit(userNamePrompt, (20,20))
screen.blit(text, (20, 300))
pygame.display.flip()
clock.tick(30)
while name2:
theKey = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
name1 = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
user2_input = user2_input[:-1]
elif event.key == pygame.K_RETURN:
name2 = False
run = True
begin = time.time()
else:
user2_input += event.unicode
screen.fill(BG_COLOR)
# Create the text surface.
text = FONT.render(user2_input, True, BLUE)
# And blit it onto the screen.
screen.blit(userNamePrompt2, (20,20))
screen.blit(text, (20, 300))
pygame.display.flip()
clock.tick(30)
playName1 = user_input
playName2 = user2_input
while instruct:
pygame.event.get()
theKey = pygame.key.get_pressed()
if theKey[pygame.K_BACKSPACE]:
instruct = False
run = False
menu = True
if theKey[pygame.K_LSHIFT] or theKey[pygame.K_RSHIFT]:
instruct = False
run = True
begin = time.time()
instruct_screen()
In this case, the code takes two taps of the "return" or enter button to get the instruction screen and two taps of the shift key to show the game screen - and I've tried to fix it, but to no avail. Does anyone know why this may be occurring and what/how the code needs to be modified in order for it to work as desired?
It's because you're calling pygame.key.get_pressed() twice, once in the menu loop and once in the name1 loop. Each time you call it, it's popping the keypress event off the stack, so the second time it will wait for a second keypress. You should store the result the first time, and use that in the second loop.

Pygame - How to stop an image from leaving the edge of the screen?

A section of jetfighterx leaves the screen when the mouse hovers over the edge of the window, this causes tarantula to explode from time to time as soon as it respawns to the top of the window, how can I stop this from happening (without the use of classes)?
Code:
import pygame, sys, pygame.mixer
from pygame.locals import *
import random
pygame.init()
bif = "space.jpg"
jf = "spacefightersprite.png"
enemy = "TarantulaSpaceFighter.png"
laser = pygame.mixer.Sound("LaserBlast.wav")
explosionsound = pygame.mixer.Sound("Explosion.wav")
screen = pygame.display.set_mode((1000,900),0,32)
caption = pygame.display.set_caption("Jet Fighter X")
background = pygame.image.load(bif).convert()
jetfighterx = pygame.image.load(jf)
jetfighterx = pygame.transform.scale(jetfighterx, (400,400))
tarantula = pygame.image.load(enemy)
tarantula = pygame.transform.scale(tarantula, (100,100))
laserblast = pygame.image.load("C:\Python27\laser.png")
explosion=pygame.image.load("C:\Python27\explosion.png")
explosion=pygame.transform.scale(explosion, (150,150))
ex,ey = 450,0
movex,movey = 0,0
clock = pygame.time.Clock()
speed = 300
shoot_y = 0
laser_fired = False
collision = False
alive = True
explo_timer = 25
while True:
pygame.mouse.set_visible(False)
mx,my = pygame.mouse.get_pos()
jetfighterx_rect = jetfighterx.get_rect(center=(mx, my))
jetfighterx_rect = jetfighterx_rect.inflate(-200,-200)
tarantula_rect = tarantula.get_rect(center=(ex, ey))
tarantula_rect = tarantula_rect.inflate(-180,-200)
# Check for player inputs
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE or event.key == K_q:
sys.exit()
if event.type == MOUSEBUTTONDOWN:
laser_fired = True
laser.play()
shoot_y = my-200
shoot_x = mx-16
# Update Game
milli = clock.tick()
seconds = milli/1000.
dmy = seconds * speed
ey += dmy
if ey > 900:
explo_timer = 25
collision = False
alive = True
ey = 0
ex = random.randint(50,900)
if laser_fired:
shoot_y -= 10
if shoot_y < 0:
laser_fired = False
else:
laserblast_rect = laserblast.get_rect(center=(shoot_x, shoot_y))
if laserblast_rect.colliderect(tarantula_rect):
explosionsound.play()
collision = True
alive = False
if jetfighterx_rect.colliderect(tarantula_rect) and alive:
explosionsound.play()
collision = True
alive = False
# Draw on screen
screen.blit(background, (0,0))
screen.blit(jetfighterx,(mx-200,my-200))
if not collision:
screen.blit(tarantula, (ex, ey))
elif collision:
explo_timer-=2
if explo_timer > 0 and alive == False:
screen.blit(explosion, (ex, ey-50))
if laser_fired:
screen.blit(laserblast, (shoot_x, shoot_y))
pygame.display.update()
Just add a limit that does not allow the fighter to move within x pixels of the border.
Assuming that the x,y coordinates of the centre of your fighter are jetfighter_x, jetfighter_y (You will need to change the variable names to whatever your code has) then write something like this:
LBuffer = 16
RBuffer = 1000 - 16
TBuffer = 900 - 16
BBuffer = 16
if jetfighter_x > RBuffer:
jetfighter_x = RBuffer
if jetfighter_x < LBuffer:
jetfighter_x = LBuffer
if jetfighter_y > TBuffer:
jetfighter_y = TBuffer
if jetfighter_y < BBuffer:
jetfighter_y = BBuffer
This should prevent the center of the ship from getting closer than 16 pixels from the edge. Obviously you will need to tweak this to accommodate the size of your ship. (The buffer for the sides would be the width of the image/2 .Respectively the buffer for the top and bottom would be the height of the image/2).

Categories