how to stop movement if the object hits the boundary in pygame - python

import pygame
import random
pygame.init()
black = (0,0,0)
red = (255,0,0)
display_width = 800
display_height = 600
FPS = 20
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("The Space Jumpers")
img = pygame.image.load('starship2.png')
spritesize = 50
boundlimit = 200
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 25)
def gameLoop():
gameExit = False
gameOver = False
lead_x = display_width / 2
lead_y = display_height / 2
xchange = 0
ychange = 0
randBlockX = random.randrange(0,boundlimit+1)
randBlockY = random.randrange(0,575)
while not gameExit:
gameDisplay.blit(img, [lead_x,lead_y])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xchange = -spritesize / 2
ychange = 0
if event.key == pygame.K_RIGHT:
xchange = spritesize / 2
ychange = 0
if event.key == pygame.K_UP:
ychange = -spritesize / 2
xchange = 0
if event.key == pygame.K_DOWN:
ychange = spritesize / 2
xchange = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xchange = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
ychange = 0
lead_x += xchange
lead_y += ychange
gameDisplay.fill(black)
pygame.draw.rect(gameDisplay,red, [randBlockX, randBlockY, 600, 25])
if (lead_x+spritesize < randBlockX and randBlockY<lead_y<randBlockY+25) :
randBlockX = random.randrange(0,boundlimit+1)
randBlockY = random.randrange(0,575)
elif (lead_x+spritesize < randBlockX and randBlockY<lead_y<randBlockY+25 ):
randBlockX = random.randrange(0,boundlimit+1)
randBlockY = random.randrange(0,575)
elif (lead_x > randBlockX+600 and randBlockY<lead_y<randBlockY+25):
randBlockX = random.randrange(0,boundlimit+1)
randBlockY = random.randrange(0,575)
elif (lead_x > randBlockX+600 and randBlockY<lead_y<randBlockY+25):
randBlockX = random.randrange(0,boundlimit+1)
randBlockY = random.randrange(0,575)
clock.tick(FPS)
pygame.quit()
quit()
gameLoop()
This is my current code and in this code when the object(sprite) hits the boundary, it keeps on moving but what I want to do is, I want to stop the movement of the object when it hits the boundary, for example when the object hits the left boundary it shouldnt move left anymore. You kind of get the idea, its a simple game

Instead of using two variables (lead_x, lead_y) to store the position of the object, use a Rect. It's as simple as
gameDisplay = pygame.display.set_mode((display_width,display_height))
gameDisplay_rect = gameDisplay.get_rect()
img = pygame.image.load('starship2.png')
img_rect = img.get_rect(center=gameDisplay_rect.center)
To draw you object, simply do:
gameDisplay.blit(img, img_rect)
Now, to move your object, instead of
lead_x += xchange
lead_y += ychange
you can do
img_rect.move_ip(lead_x, lead_y)
img_rect.clamp_ip(gameDisplay_rect)
clamp_ip will then prevent your object from leaving the screen.

I think this will work:
try changing your if statement(if pygame.key == pygame.K_LEFT:) to(if pygame.key == pygame.K_LEFT and x > 0:)
i have been struggling with the same thing for a school project and have gotten it so that it stops the sprite if you touch the border, but if you spam that button you can get through. I currently have an if statement saying(If x < 0: x_change = 0), but i have not tried the one i suggested. i hope it works.

sloth's method is for sure better in many ways, but if you still want to keep your old lead_x, lead_y structure you could just add a separate statements outside of the event loop:
if lead_x <= 0:
lead_x += 10 # just use any small distance to push you back to place every frame
elif lead_x >= display_width:
lead_x -= 10
and so on for every direction.

Related

Behind the scenes PyGame game works but image won't move

I am trying to make my own own game. Before, the car image would move really well but then and put my loop in a "def" thing so that the game could restart when the car crash in the wall and when you win. Now, everything works only the game doesn't seem to update to the screen because the car won't move. The game still seems to work behind the screen because when I make the car crash without seeing it move it plays the crash segment. PyGame doesn't say day is an error. this is kind of new to me and I really don,t understand what the problem.
here is part of my code:
#Setting and variables
display_width = 1570
display_height = 450
car_width = 98
car_height = 66
clock = pygame.time.Clock()
wn = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('My own game')
finish_line = pygame.image.load('myOwnFinishreal.png')
carImg = pygame.image.load('myOwnRGame.png')
carY = 192
carX = 10
Xchange = 0
Ychange = 0
Xfin = 1480
Yfin = 0
carY = 192
carX = 10
#racecar
def car(x,y):
wn.blit(carImg, (carX, carY))
#finish line
def finish():
wn.blit(finish_line, (Xfin, Yfin))
#Crashing
def textObjects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def displayMessage(text):
textFont1 = pygame.font.Font('freesansbold.ttf', 32)
textSurf, textRect = textObjects(text, textFont1)
textRect.center = ((display_width/2),(display_height/2))
while True:
wn.blit(textSurf, textRect)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.quit()
if event.key == pygame.K_SPACE:
gameLoop()
pygame.display.update()
def crash():
displayMessage('You crashed!Press X to quit, _SPACE_ to restart!')
def win():
displayMessage('Bravo! You are the best car runner! Press X to quit _SPACE_ to restart.')
#Game loop
def gameLoop():
carY = 192
carX = 10
Xchange = 0
Ychange = 0
alive = True
losing = True
while alive and losing:
carX += Xchange
carY += Ychange
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.quit()
if event.key == pygame.K_UP:
Xchange = 0
Ychange = 0
Xchange = 2.5
elif event.key == pygame.K_LEFT:
Xchange = 0
Ychange = 0
time.sleep(0.85)
Ychange = -3
elif event.key == pygame.K_RIGHT:
Xchange = 0
Ychange = 0
time.sleep(0.85)
Ychange = 3
elif event.key == pygame.K_DOWN:
Xchange = 0
Ychange = 0
time.sleep(0.85)
Xchange = -3
if carY <= -15 or carY >= display_height - 15:
Xchange = 0
Ychange = 0
crash()
if carX >= display_width:
Xchange = 0
Ychange = 0
win()
if carX <= 0:
carX = 10
#350 250 120 30
wn.fill(grey)
finish()
carX += Xchange
carY += Ychange
car(carX, carY)
pygame.display.update()
clock.tick(60)
pygame.quit()
gameLoop()
Looking forward for your help and bid thanks!
You have to use the arguments x and y rather than carX and carY in the function car:
def car(x,y):
wn.blit(carImg, (x, y))

Can you make the game display appear in the centre of your screen once the run is pressed. If yes how?

#enable pygame mode
import pygame
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
def player(x, y):
screen.blit(player_icon, (x, y))
surface.blit(image,((1920/2)-(image.get_width()/2),(1080/2)-
(image.get_height()/2)))
#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 wether 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:
player_changeX = -1
if playerX <= 0:
player_changeX = 1
if playerY <= 0:
player_changeY = 1
if playerY >= 550:
player_changeY = -1
#Player change in coordinates
playerX += player_changeX
playerY += player_changeY
player(playerX, playerY)
pygame.display.update()
I am creating a simple game as i just got into programing and I was wondering if you could make the game screen appear in the centre of your own screen as when I run it it keeps appearing on the bottom of my screen and I then have to manually move it into the centre. If you can please tell me how. Hope my question was formated good enough. Thank you for any help.
It depends; if it's a image you can do:
surface.blit(image,((screenwidth/2)-(image.get_width()/2),(screenheight/2)-(image.get_height()/2)))
Please tell me it it's different

Can't figure out why my image wont move in pygame

I'm just messing around with Pygame and I can't see what I'm doing incorrectly to make the red circle move with the arrow keys. I can't tell if it's in my main loop. I also haven't been able to find very many tutorials on sprite or looping animations with Pygame. If I for example wanted to make a square oscillate for example like a moving platform how would I do that?
import pygame
import time
## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250
## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")
# player
def player():
pygame.draw.circle(game_screen,red,(x,y),15)
# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
### main loop
dead = False
while dead != True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x = -1
elif event.key == pygame.K_RIGHT:
player_x = +1
if event.key == pygame.K_UP:
player_y = +1
elif event.key == pygame.K_DOWN:
player_y = -1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or pygame.K_RIGHT:
player_x = 0
if event.key == pygame.K_UP or pygame.K_DOWN:
player_y = 0
game_screen.fill(black)
player()
pygame.display.update()
x -= player_x
y -= player_y
pygame.quit()
quit()
Your indendation is all messed up.
Your code won't do anything unless the event is QUIT... which then makes it quit.
Your boolean logic is wrong.
This is not proper syntax event.key == pygame.K_UP or pygame.K_DOWN. The order of precedence here is as follows (event.key == pygame.K_UP) or (K_DOWN). Since K_DOWN is truthy, it is always true and thus this entire statement is always true.
I think you mean: event.key == pygame.K_UP or event.key == pygame.K_DOWN
Lastly, it wont' keep moving as you say you want.
It will only move when there is an event in the queue. You can make it keep moving by generating events. Perhaps with an event timer.
Here is a fixed version, hope this helps:
import pygame
import time
## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250
## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")
# player
def player(game_screen, red, point): # Use parameters not globals
pygame.draw.circle(game_screen, red, point, 15)
# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
### main loop
pygame.time.set_timer(pygame.USEREVENT, 1) # 1 per second
dead = False
while not dead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead = True
elif event.type == pygame.USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 1) # Set another timer for another 1 second
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x = +10
elif event.key == pygame.K_RIGHT:
player_x = -10
elif event.key == pygame.K_UP:
player_y = +10
elif event.key == pygame.K_DOWN:
player_y = -10
elif event.type == pygame.KEYUP:
if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
player_x = 0
elif event.key in [pygame.K_UP, pygame.K_DOWN]:
player_y = 0
game_screen.fill(black)
player(game_screen,red,(x,y))
pygame.display.update()
x -= player_x
y -= player_y
pygame.quit()

Pygame won't print text in certain circumstances

So I'm trying to print "you lose" to the screen when the user moves a box off the playable screen, however this doesn't seem to work unless I call it from outside my main while loop. I have defined a function to handle the creation of the text, the rendering and 'blit'ing of it, although this has no effect when it is called from inside the while loop however it does when it is called from outside it at the bottom. I have checked and the function is executed from both locations, though it only seems to work from one.
import pygame
import time
pygame.init()
red = (255,0,0)
black = (0,0,0)
white = (255,255,255)
gamewidth = 900
gameheight = 900
snakecolour = black
gameDisplay = pygame.display.set_mode((gamewidth,gameheight))
pygame.display.set_caption("Snake")
gameExit = False
boxDimensions = 10
lead_x = (gamewidth // 2) - ((gamewidth // 2) % 20)
lead_y = (gameheight // 2) - ((gameheight // 2) % 20)
lead_x_change = 0
lead_y_change = 0
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 25)
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [gamewidth//2, gameheight//2])
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if not (lead_x_change == boxDimensions):
lead_x_change = -boxDimensions
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
if not (lead_x_change == -boxDimensions):
lead_x_change = boxDimensions
lead_y_change = 0
elif event.key == pygame.K_UP:
if not (lead_y_change == boxDimensions):
lead_y_change = -boxDimensions
lead_x_change = 0
elif event.key == pygame.K_DOWN:
if not (lead_y_change == -boxDimensions):
lead_y_change = boxDimensions
lead_x_change = 0
lead_x += lead_x_change
lead_y += lead_y_change
if lead_x > gamewidth or lead_x < 0 or lead_y > gameheight or lead_y < 0:
snakecolour = red
gameExit = True
message_to_screen("You Lose!", red)
pygame.display.update()
#message_to_screen("You Lose!", red) WONT WORK HERE
if lead_x > gamewidth:
lead_x = gamewidth - boxDimensions
lead_x_change = 0
elif lead_x < 0:
lead_x = 0
lead_x_change = 0
elif lead_y > gameheight:
lead_y = gameheight - boxDimensions
elif lead_y < 0:
lead_y = 0
lead_y_change = 0
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, snakecolour, [lead_x,lead_y,boxDimensions,boxDimensions])
pygame.display.update()
clock.tick(15)
#message_to_screen("You Lose!", red) DOES WORK HERE
#pygame.display.update()
time.sleep(3)
pygame.quit()
message_to_screen("YOU LOSE!",(255,0,0))
pygame.display.update()
sleep(3)
From AirThomas comment, this is working. Outside of the while loop, put this statement.
For score board:
text = pygame.font.SysFont("None", 30)
score=0
text1=text.render("{}".format(score), True,(255,255,255))
while running:
screen.fill((0, 0, 0))
#codes
#codes
#codes
if sneakeatssomething:
score += 1
text1=text.render("{}".format(score), True,(255,255,255)) #rendering the score again
#codes
#codes
screen.blit(text1,(275,6))#showing the score
pygame.display.flip()
clock.tick(150)
This is updating the score when sneak eats and printing it to the pygame screen

How can I make the movement smoother?

I'm developing a very basic engine, basing myself on tutorials from Pygame, and I'm having a little problem with "smoothness". How do I make my player walk "smoother"?
My event handler is pretty basic, pretty standard, nothing new, and I even figured out how to make a "boost" (run) for test. But the thing is, at the pygame.KEYUP, those lots of zeros destroy the "smoothness" of my little player, and I don't want that, but I don't want it to walk ad infinitum.
import pygame
import gfx
# Main Class
class Setup:
background = gfx.Images.background
player = gfx.Images.player
pygame.init()
# Configuration Variables:
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
red = (255,0,0)
title = "Ericson's Game"
# Setup:
size = [700,700]
screen = pygame.display.set_mode(size)
pygame.display.set_caption(title)
done = False
clock = pygame.time.Clock()
# Logic Variables
x_speed = 0
y_speed = 0
x_speed_boost = 0
y_speed_boost = 0
x_coord = 350
y_coord = 350
screen.fill(white)
# Main Loop:
while done == False:
screen.blit(background,[0,0])
screen.blit(player,[x_coord,y_coord])
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
if event.key == pygame.K_a:
x_speed = -6
x_speed_boost = 1
if event.key == pygame.K_d:
x_speed = 6
x_speed_boost = 2
if event.key == pygame.K_w:
y_speed = -6
y_speed_boost = 1
if event.key == pygame.K_s:
y_speed = 6
y_speed_boost = 2
if event.key == pygame.K_LSHIFT:
if x_speed_boost == 1:
x_speed = -10
if x_speed_boost == 2:
x_speed = 10
if y_speed_boost == 1:
y_speed = -10
if y_speed_boost == 2:
y_speed = 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
x_speed = 0
x_speed_boost = 0
if event.key == pygame.K_d:
x_speed = 0
x_speed_boost = 0
if event.key == pygame.K_w:
y_speed = 0
y_speed_boost = 0
if event.key == pygame.K_s:
y_speed = 0
y_speed_boost = 0
x_coord = x_coord + x_speed
y_coord = y_coord + y_speed
pygame.display.flip()
pygame.display.update()
clock.tick(20)
pygame.quit()
Code will be simpler/clearer using keystate polling for your use. If other parts of the game use 'on press' logic, you can use event handling. So your movement would be:
If you are calling pygame.display.flip() then you don't use pygame.display.update(). Infact it will probably slow it down to use both.
I used your x_coord variable. But it would simplify things to use a tuple or vector for player location. You can use a float, for smoother precision for movement. Then it blits as an int to screen.
while not done:
for event in pygame.event.get():
# any other key event input
if event.type == QUIT:
done = True
elif event.type == KEYDOWN:
if event.key == K_ESC:
done = True
vel_x = 0
vel_y = 0
speed = 1
if pygame.key.get_mods() & KMOD_SHIFT
speed = 2
# get key current state
keys = pygame.key.get_pressed()
if keys[K_A]:
vel_x = -1
if keys[K_D]:
vel_x = 1
if keys[K_W]:
vel_y = -1
if keys[K_S]:
vel_y = 1
x_coord += vel_x * speed
y_coord += vel_y * speed
You are ticking the clock at a rate of 20 frames per second. This is probably causing the choppiness. Change it to something bigger like 70:
clock.tick(70)

Categories