Pygame won't print text in certain circumstances - python

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

Related

The apple spawn inside the snake

i'm making a game and i found something that annoys me. The apple spawning inside a snake. i defined the snake head(sh) which is the only function that interact with the apple. Not the other parts of the snake. So, how do you make this not happen?
i tried using Pygame Snake - Apple spawning inside snake and edit it to make it work. And i tried making a if statement on the pygame rectangle collide code.
import pygame
import os
import sys
pygame.mixer.pre_init()
pygame.mixer.init(44100, 16, 2, 262144)
pygame.init()
from pygame.locals import*
import cv2
import time
import random
import pickle
import shutil
import OpenGL
dw = 1280
dh = 720
at = 40
bs = 20
screen = pygame.display.set_mode((dw, dh))
clock = pygame.time.Clock()
def pause():
paused = True
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
paused = False
elif event.key == pygame.K_SPACE:
menu(1)
screen.fill(white)
mts("Paused", black, -100, 100)
mts("Press esc to go back to the game or press space to go back to the menu", black, 25, 45)
pygame.display.update()
clock.tick(60)
#define the apple to spawn in a random place
def randAppleGen():
randAppleX = random.randrange(0, dw-at, bs)
randAppleY = random.randrange(0, dh-at, bs)
return randAppleX,randAppleY
def snake(bs, sl):
for XnY in sl:
pygame.draw.rect(screen, Dgreen, [XnY[0],XnY[1],bs,bs])
def gameLoop():
global at
global bs
hs = pickle.load( open( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN'), "rb" ) )
gameExit = False
gameOver = False
gameHack = False
Speed = 20
lead_x = dw/2
lead_y = dh/2
lead_x_change = 0
lead_y_change = 0
pygame.mixer.music.load(os.path.join(os.getcwd(), 'Sounds', 'music1.ogg'))
pygame.mixer.music.play(-1)
slist = []
sl = 0
if sl > 2304:
gameHack = True
randAppleX,randAppleY = randAppleGen()
while not gameExit:
while gameOver == True:
screen.fill(white)
mts("Game over", red, -50,100)
mts("Press enter to play again or press space to go back to the menu", black, 50,50)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameOver = False
gameExit = True
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER or event.key==pygame.K_RETURN:
gameLoop()
if event.key == pygame.K_SPACE:
gameExit = False
gameOver = False
menu(1)
while gameHack == True:
pygame.mixer.music.stop()
screen.fill(white)
mts("Hacked", red, -50,100)
mts("You hacked or exploit the game, press enter to quit the game", black, 50,50)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameOver = False
gameExit = True
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER or event.key==pygame.K_RETURN:
pygame.quit()
sys.exit()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and lead_x_change != bs:
lead_x_change = -bs
lead_y_change = 0
elif event.key == pygame.K_RIGHT and lead_x_change != -bs:
lead_x_change = bs
lead_y_change = 0
elif event.key == pygame.K_UP and lead_y_change != bs:
lead_y_change = -bs
lead_x_change = 0
elif event.key == pygame.K_DOWN and lead_y_change != -bs:
lead_y_change = bs
lead_x_change = 0
elif event.key == pygame.K_ESCAPE:
pause()
elif event.key == pygame.K_s and Speed >= 10 and Speed < 60:
Speed += 10
clock.tick(Speed)
elif event.key == pygame.K_d and Speed <= 60 and Speed > 10:
Speed -= 10
clock.tick(Speed)
if not pygame.Rect(0, 0, dw, dh).contains(lead_x, lead_y, bs, bs):
gameOver = True
lead_x += lead_x_change
lead_y += lead_y_change
screen.fill(white)
#draw the apple
apple = pygame.draw.rect(screen, red, [randAppleX,randAppleY,at,at])
sh = []
sh.append(lead_x)
sh.append(lead_y)
slist.append(sh)
snake(bs, slist)
if len(slist) > sl:
del slist[0]
for eachSegment in slist[:-1]:
if eachSegment == sh:
gameOver = True
score(sl)
highscore(hs)
if sl > hs:
hs += 1
os.remove( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN') )
pickle.dump( sl, open( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN'), "wb" ) )
hs = pickle.load( open( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN'), "rb" ) )
pygame.display.update()
#make the apple spawn
if lead_x > randAppleX and lead_x < randAppleX + at or lead_x + bs > randAppleX and lead_x + bs < randAppleX + at:
if lead_y > randAppleY and lead_y < randAppleY + at:
randAppleX,randAppleY = randAppleGen()
sl += 1
elif lead_y + bs > randAppleY and lead_y + bs < randAppleY + at:
randAppleX,randAppleY = randAppleGen()
sl += 1
clock.tick(Speed)
pygame.quit()
quit()
i expected it to not spawn in the snake, but it did.
The area which is covered by the apple is greater than an part of the snake.
You've to use pygame.Rect.collidepoint() th verify if the snake is in the area of the apple:
appleRect = pygame.Rect(randAppleX, randAppleY, at, at)
if appleRect.collidepoint(lead_x, lead_y):
# [...]
The snake consists of the head and a list of body part. If a new random position for an apple is generated, then you've to verify if the apple does not cover the head and not any part of the body:
if not appleRect.collidepoint(lead_x, lead_y) and \
not any(appleRect.collidepoint(*p) for p in slist):
# [...]
The code to spawn a new apple may look like this:
appleRect = pygame.Rect(randAppleX, randAppleY, at, at)
if appleRect.collidepoint(lead_x, lead_y):
while True:
randAppleX, randAppleY = randAppleGen()
appleRect = pygame.Rect(randAppleX, randAppleY, at, at)
if not appleRect.collidepoint(lead_x, lead_y) and \
not any(appleRect.collidepoint(*p) for p in slist):
break
sl += 1

Python Snake Tutorial, Tail/Speed

I am trying to add a tail to my snake (at the very end use a triangle image rather than a square fill). While I think I got the code to work for the most part, I was seeing that if I changed directions, the last few seconds the tail would "disconnect" from the body. (tail points right and body going down leaves a gap). I tried to fix this by upping my FPS which seemed to work; however I wanted the snake speed to be the same as before and since I doubled the FPS I would have to 1/2 the speed. When I did that however, my collision detection was out of sync and if I slowed it down my body would draw over my face, and if I sped up I would have my body getting disconnected (block, space, block). I have tried it a few different ways so any help would be appreciated.
Please note that block_speed = 10, and if I manually type 10 it works, but if I change to 5 or 20, or if I change to a variable with value of 5 or 20 (say speed for example), the code does not work.
Code:
import pygame, sys
from pygame.locals import*
import time
import random
import os
pygame.init()
#GUI Settings
display_Width = 800
display_Height = 600
gameDisplay = pygame.display.set_mode((display_Width,display_Height))
pygame.display.set_caption("Gluttonous Snake")
gameicon = pygame.image.load('icon.png')
potatoimg = pygame.image.load('potato.png')
pygame.display.set_icon(gameicon)
FPS = 15
direction = "up"
#set path to where to .py/.exe is
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
print(dname)
snakeheadimg = pygame.image.load('snakehead.png')
snaketailimg = pygame.image.load('snaketail.png')
appleimg = pygame.image.load('apple.png')
#define colors
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
yellow = (255,255,0)
eggwhite = (255,255,204)
lightgrey = (242,242,242)
#Game Variables
block_size = 10
clock = pygame.time.Clock()
def game_intro():
intro = True
x = 500
y = 400
x_dir = "left"
while intro:
gameDisplay.fill(eggwhite)
gameDisplay.blit(potatoimg, (50, 25))
message_to_screen("Potato Productions Presents...", black, -100, size=45)
message_to_screen("Gluttonous Snake", green, -25, size=75)
message_to_screen("A game made by a potato to run on a potato", black, 50, size=25)
message_to_screen("Press C to Start!", red, 75, size=25)
gameDisplay.blit(gameicon, (x, y))
if x_dir == "left":
if x > 0:
x -= 10
else:
x_dir = "right"
else:
if x < 500:
x += 10
else:
x_dir = "left"
if x < 125 or x > 375:
y -= 9.66
else:
y += 10
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
intro = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
if event.key == pygame.K_q:
pygame.quit()
quit()
def pickFont(name,size):
font = pygame.font.SysFont(name, size, bold=False)
return font
#font size = 25
#font = pygame.font.SysFont("comicsansms",size=25)
def snake(snakelist):
# faster GPU method is
# gameDisplay.fill(red, rect=[200,200,50,50])
if direction == "left":
head = pygame.transform.rotate(snakeheadimg,90)
if direction == "right":
head = pygame.transform.rotate(snakeheadimg,270)
if direction == "down":
head = pygame.transform.rotate(snakeheadimg,180)
if direction == "up":
head = pygame.transform.rotate(snakeheadimg,0)
gameDisplay.blit(head,(snakelist[-1][0],snakelist[-1][1]))
#-1 because we are drawing that above
# for XnY in snakelist[:-1]:
# #gameDisplay.fill(green, rect=[lead_x, lead_y, block_size, block_size])
# gameDisplay.fill(green, rect=[XnY[0], XnY[1], block_size, block_size])
# -1 because we are drawing that above
if len(snakelist) >= 2:
for XnY in snakelist[1:-1]:
gameDisplay.fill(green, rect=[XnY[0], XnY[1], block_size, block_size])
if direction == "up":
tail = pygame.transform.rotate(snaketailimg, 180)
if snakelist[1][0] > snakelist[0][0]:
tail = pygame.transform.rotate(snaketailimg, 90)
elif snakelist[1][0] < snakelist[0][0]:
tail = pygame.transform.rotate(snaketailimg, 270)
elif snakelist[1][1] > snakelist[0][1]:
tail = pygame.transform.rotate(snaketailimg, 0)
elif snakelist[1][1] < snakelist[0][1]:
tail = pygame.transform.rotate(snaketailimg, 180)
gameDisplay.blit(tail, (snakelist[-len(snakelist)][0], snakelist[-len(snakelist)][1]))
def text_objects(text, color,size):
font = pickFont("comicsansms", size)
textSurface = font.render(text,True,color,size)
return textSurface, textSurface.get_rect()
def message_to_screen(msg,color,y_displace=0, size=25):
#True is anti-aliasing
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (display_Width/2),(display_Height/2) + y_displace
gameDisplay.blit(textSurf,textRect)
def gameLoop():
# set up variables
global direction
gameExit = False
gameOver = False
lead_x = display_Width / 2
lead_y = display_Height / 2
coinflip = random.randint(0, 1)
if coinflip == 0:
coinflip = random.randint(0, 1)
if coinflip == 0:
lead_x_change = **10**
lead_y_change = 0
direction = "right"
else:
lead_x_change = -**10**
lead_y_change = 0
direction = "left"
else:
coinflip = random.randint(0, 1)
if coinflip == 0:
lead_x_change = 0
lead_y_change = **10**
direction = "down"
else:
lead_x_change = 0
lead_y_change = -**10**
direction = "up"
#lead_x_change = 0
#lead_y_change = 0
#the 10 is round to 10
randAppleX = random.randrange(0, display_Width - block_size, 10)
randAppleY = random.randrange(0, display_Height - block_size, 10)
snakelist = []
snakelength = 1
while not gameExit:
while gameOver == True:
gameDisplay.fill(white)
#message_to_screen("Game over \n Press C to play again or Q to quit", red)
message_to_screen("Game Over", red, y_displace=-50, size=75)
message_to_screen("Press C to play again or Q to quit",black,y_displace=50,size=25)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
#gameOver = False
for event in pygame.event.get():
#shows every mouse move and key pressed
#print(event)
if event.type == pygame.QUIT:
gameExit = True
gameOver = False
#check for single depress of keys
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
#lead_x -= 10
#this is so they can't back over themselves
if lead_x_change != **block_size**:
lead_x_change = - **block_size**
lead_y_change = 0
direction = "left"
#elif is only tested if the ifs and elifs above it are not true
elif event.key == pygame.K_RIGHT:
#lead_x += 10
if lead_x_change != -**block_size**:
lead_x_change = **block_size**
lead_y_change = 0
direction = "right"
elif event.key == pygame.K_UP:
if lead_y_change != **block_size**:
lead_x_change = 0
lead_y_change = -**block_size**
direction = "up"
elif event.key == pygame.K_DOWN:
if lead_y_change != -**block_size**:
lead_x_change = 0
lead_y_change = **block_size**
direction = "down"
# user releases key
# if event.type == pygame.KEYUP:
# if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
# lead_x_change = 0
#Ends the game once the square has left the window
if lead_x >= (display_Width - block_size) or lead_x <= 0 or lead_y >= (display_Height - block_size) or lead_y <= 0:
print("snake left at " + str(lead_x)+","+str(lead_y))
lead_x_change = 0
lead_y_change = 0
gameOver = True
lead_x += lead_x_change
lead_y += lead_y_change
gameDisplay.fill(lightgrey)
snakehead = []
snakehead.append(lead_x)
snakehead.append(lead_y)
snakelist.append(snakehead)
if len(snakelist) > snakelength:
del snakelist[0]
#-1 because last element is the head
for eachSegement in snakelist[:-1]:
if eachSegement == snakehead:
print("snake eats itself")
gameOver = True
#draw snake first so if apple spawns on it I can still see it
snake(snakelist)
#gameDisplay.fill(red, rect=[randAppleX, randAppleY, block_size, block_size])
gameDisplay.blit(appleimg,(randAppleX, randAppleY))
pygame.display.update()
#better collison detection as part of the snake can go over part of the apple
# if lead_x >= randAppleX and lead_x + block_size < randAppleX + block_size or lead_x + block_size >= randAppleX and lead_x + block_size < randAppleX + block_size:
# if lead_y >= randAppleY and lead_y < randAppleY + block_size or lead_y + block_size >= randAppleY and lead_y + block_size < randAppleY + block_size:
if lead_x >= randAppleX:
if lead_x + block_size <= randAppleX + block_size:
if lead_y >= randAppleY:
if lead_y + block_size <= randAppleY + block_size:
print("nom nom nom")
randAppleX = random.randrange(0, display_Width - block_size, 10)
randAppleY = random.randrange(0, display_Height - block_size, 10)
snakelength += 1
#used to make FPS
clock.tick(FPS)
pygame.quit()
quit()
game_intro()
gameLoop()
Reply to answer provided:
Great thanks I will look into this. Were you able to figure out why I can't adjust the speed though? Seems weird it would draw the body over the head if I slow down the speed, or it will leave gaps if I speed it up. The part were I was adjusting the speed was in bold
You can probably smooth things a bit (and make your code clearer) by doing the following:
1 - store the tail (head) rotated images:
tail_left = pygame.transform.rotate(snaketailimg, 180) # choose appropriate rotation
tail_right = ...
tail_up = ...
tail_down = ...
2 - determine which direction the snake goes, and look up the images from a dict (for instance)
tail_oriented_images = {'left': tail_left, 'right': tail_right, ...}
...
tail_direction = get_tail_direction() # to be extracted
3- then replace the if cascade in snake(snakelist) with:
tail = tail_oriented_images[tail_direction]
4- Do the same for the head direction

Python Snake Game Boundries not working

I'm new to python and I'm trying following along with a tutorial that uses PyGame to create a snake like game. For some reason my boundaries are not working. It may be something simple but I can't see any reason why it wouldn't work. I don't get any errors, the snake just goes past the boundaries and the game doesn't end.
import pygame
import time
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Slither')
clock = pygame.time.Clock()
block_size = 10
FPS = 30
font = pygame.font.SysFont(None, 25)
def message_to_screen(msg,color):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [display_width/2, display_height/2])
def gameLoop():
gameExit = False
gameOver = False
lead_x = display_width/2
lead_y = display_height/2
lead_x_change = 0
lead_y_change = 0
randAppleX = random.randrange (0, display_width-block_size)
randAppleY = random.randrange (0, display_height-block_size)
while not gameExit:
while gameOver == True:
gameDisplay.fill(white)
message_to_screen("Game over, press C to play again or Q to quit", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_X_change = 0
**if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:
gameOver == True #boundaries**
lead_x += lead_x_change
lead_y += lead_y_change
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, block_size, block_size])
pygame.draw.rect(gameDisplay, black, [lead_x , lead_y, block_size, block_size])
pygame.display.update()
clock.tick(FPS)
message_to_screen("You Lose", red)
pygame.display.update()
time.sleep(2)
pygame.quit()
quit()
gameLoop()
In your exit condition, you're using the equality comparison, not the assignment operator:
if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:
gameOver == True #boundaries
in the above,
gameOver == True
should be
gameOver = True

Pygame Help Trying to add apples in Snakegame

import pygame
import random
import time
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('slither')
white = (255, 255, 255)
black = (0,0,0)
red = (252,25,25)
blue = (20,20,250)
purple = (90,33,146)
movement_size = 10
block_size = 20
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 25)
def message_to_screen(msg,colour):
screen_text = font.render(msg, True, colour)
gameDisplay.blit(screen_text, [display_width/2, display_height/2])
def gameLoop():
gameExit = False
gameOver = False
lead_x = display_width/2.0
lead_y = display_height/2.0
lead_x_change = 0
lead_y_change = 0
randAppleX = random.randrange(0, display_width-block_size)
randAppleY = random.randrange(display_height-block_size, 0)
while not gameExit:
while gameOver == True:
gameDisplay.fill(purple)
message_to_screen("Game Over, Press 'C' to play again or 'Q' to Quit", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change -= movement_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change += movement_size
lead_y_change= 0
elif event.key == pygame.K_UP:
lead_y_change -= movement_size
lead_x_change= 0
elif event.key == pygame.K_DOWN:
lead_y_change += movement_size
lead_x_change= 0
if lead_x >= 782 or lead_x < 0 or lead_y >= 582 or lead_y < 0:
gameOver = True
lead_x += lead_x_change
lead_y += lead_y_change
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, block_size, block_size])
pygame.draw.rect(gameDisplay, black, [lead_x, lead_y, block_size, block_size])
pygame.display.update()
clock.tick(11)
pygame.quit()
quit()
gameLoop()
I was trying to add 'apples' in my snake game. However I was troubled in doing so. Any help debugging code would be very much appreciated! I'm getting some error on lines; 94,42 and 218 something has gone horribly wrong with the randrange stuff.
http://i63.tinypic.com/1h4ggj.png <----- To See
the error happens in
randAppleY = random.randrange(display_height-block_size, 0)
As the error stack trace indicates that randrange function got parameters start=580, stop=0. From inspecting the source file for this function shows that the default value for step is 1.
This is causing the problem as 0 is less than 580 and connot be reached by adding 1 (step parameter) any number of times.
What you can do to fix this is either pass step parameter as -1
randAppleY = random.randrange(display_height-block_size, 0, -1)
Or pass the smaller value as start and larger value as stop parameter
randAppleY = random.randrange(0, display_height-block_size)
import pygame
import random
import time
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('slither')
white = (255, 255, 255)
black = (0,0,0)
red = (252,25,25)
blue = (20,20,250)
purple = (90,33,146)
movement_size = 10
block_size = 20
clock = pygame.time.Clock()
gameExit = gameOver = False
font = pygame.font.SysFont(None, 25)
def message_to_screen(msg,colour):
screen_text = font.render(msg, True, colour)
gameDisplay.blit(screen_text, [display_width/2, display_height/2])
def gameLoop():
gameExit = False
gameOver = False
lead_x = display_width/2.0
lead_y = display_height/2.0
lead_x_change = 0
lead_y_change = 0
randAppleX = random.randint(0, display_width-block_size)
randAppleY = random.randint(0,display_height-block_size)
while not gameExit:
while gameOver:
gameDisplay.fill(purple)
message_to_screen("Game Over, Press 'C' to play again or 'Q' to Quit", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change -= movement_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change += movement_size
lead_y_change= 0
elif event.key == pygame.K_UP:
lead_y_change -= movement_size
lead_x_change= 0
elif event.key == pygame.K_DOWN:
lead_y_change += movement_size
lead_x_change= 0
if lead_x >= 782 or lead_x < 0 or lead_y >= 582 or lead_y < 0:
gameOver = True
lead_x += lead_x_change
lead_y += lead_y_change
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, block_size, block_size])
pygame.draw.rect(gameDisplay, black, [lead_x, lead_y, block_size, block_size])
pygame.display.update()
clock.tick(11)
pygame.quit()
quit()
gameLoop()

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

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.

Categories