The apple spawn inside the snake - python
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
Related
How to make a wall tilemap?
i'm making a game but i want to make the game harder by adding walls. I found out it's called a tilemap. But it's for multiple colours, i just want one color, grey. I want it to be something like 1,1,1,1, 1,0,0,1, 1,0,0,1, 1,1,1,1 0 = nothing. 1 = grey rectangle. I also need it to be like WIDTH = 16 HEIGHT = 9 TILESIZE = dw/WIDTH but i can't find a way to implement it. i tried using a def code but it lagged out my game. And i tried using this site: http://usingpython.com/pygame-tilemaps/ 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 grey = (128,128,128) 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) def score(score): text = pygame.font.Font('Fonts/Kuiper_Belt.otf', 25).render("Score: "+str(score), True, black) screen.blit(text, [0,0]) def highscore(highscore): text = pygame.font.Font('Fonts/Kuiper_Belt.otf', 25).render("Highscore: "+str(highscore), True, black) screen.blit(text, [1100,0]) #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 text_objects(text,color,fontS): font = pygame.font.Font('Fonts/Kuiper_Belt.otf', fontS) textSurface = font.render(text, True, color) return textSurface, textSurface.get_rect() def mts(msg,color, y_displace=0, fs=35): textSurf, textRect = text_objects(msg,color,fs) textRect.center = (dw / 2), (dh / 2)+y_displace screen.blit(textSurf, textRect) 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 tilemap = [ [1,1,1,1], [1,0,0,1], [1,0,0,1], [1,1,1,1] ] WIDTH = 4 HEIGHT = 4 TILESIZE = dw/WIDTH 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: for row in range(HEIGHT): for column in range(WIDTH): if tilemap[row][column] == 1: pygame.draw.rect(screen, grey, (column*TILESIZE, row*TILESIZE, TILESIZE, TILESIZE)) 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() lead_x += lead_x_change lead_y += lead_y_change prev_x, prev_y = lead_x_change, lead_y_change 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 prev_x != bs: lead_x_change, lead_y_change = -bs, 0 elif event.key == pygame.K_RIGHT and prev_x != -bs: lead_x_change, lead_y_change = bs, 0 elif event.key == pygame.K_UP and prev_y != bs: lead_x_change, lead_y_change = 0, -bs elif event.key == pygame.K_DOWN and prev_y != -bs: lead_x_change, lead_y_change = 0, bs 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) elif event.key == pygame.K_a: sl += 1 if not pygame.Rect(0, 0, dw, dh).contains(lead_x, lead_y, bs, bs): gameOver = True 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 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 clock.tick(Speed) pygame.quit() sys.quit() I expect it to display a single color tile map, but i keep on getting crashes.
I don't understand why you have problem if you already have it in code and you have example in your link. tilemap = [ [1,1,1,1], [1,0,0,1], [1,0,0,1], [1,1,1,1] ] MAPHEIGHT = 4 MAPWIDTH = 4 TILESIZE = dw/MAPWIDTH GREY = (128,128,128) for row in range(MAPHEIGHT): for column in range(MAPWIDTH): if tilemap[row][column] == 1: pygame.draw.rect(screen, GREY, column*TILESIZE, row*TILESIZE, TILESIZE, TILESIZE)) EDIT: You have problem because you use it in wrong place. You have to draw between screen.fill (which clears buffer) and pygame.update (which sends buffer to video card and it displays it on screen) screen.fill(white) for row in range(HEIGHT): for column in range(WIDTH): if tilemap[row][column] == 1: pygame.draw.rect(screen, grey, (column*TILESIZE, row*TILESIZE, TILESIZE, TILESIZE)) # ... draw other things ... pygame.display.update() You have mess in code. You should have place where you update values, move object, crate/respaw object, load/save pickle, etc. but don't draw there. place where you use screen.fill, draw all elements, use pygame.display.update but don't update object and don't load/save pickle EDIT: My version (with better names of variables and functions) import pygame import os import sys import random import pickle # --- constants --- (UPPERCASE names) WHITE = ( 0, 0, 0) RED = (255, 0, 0) BLACK = (255, 255, 255) GREEN = (255, 0, 0) GREY = (128, 128, 128) DISPLAY_WIDTH = 1200 DISPLAY_HEIGHT = 800 APPDATA = os.getenv('APPDATA', '') PICKLE_PATH = os.path.join(APPDATA, 'Snake Universe', 'h.SNUN') WIDTH = 4 HEIGHT = 4 TILE_SIZE = DISPLAY_WIDTH/WIDTH BLOCK_SIZE = 20 # --- functions --- 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) def text_object(text, color=BLACK, font_size=25): font = pygame.font.SysFont(None, font_size) surface = font.render(text, True, color) rect = surface.get_rect() return surface, rect def draw_score(screen, score): surface, rect = text_object("Score: " + str(score)) screen.blit(surface, (0, 0)) def draw_highscore(screen, highscore): surface, rect = text_object("Highscore: " + str(highscore)) screen.blit(surface, (1100, 0)) def rand_apple_pos(): x = random.randrange(0, DISPLAY_WIDTH - BLOCK_SIZE, BLOCK_SIZE) y = random.randrange(0, DISPLAY_HEIGHT - BLOCK_SIZE, BLOCK_SIZE) return x, y def draw_snake(screen, snake): for x, y in snake: pygame.draw.rect(screen, GREEN, (x, y, BLOCK_SIZE, BLOCK_SIZE)) def mts(msg, color, y_displace=0, fs=35): surface, rect = text_object(msg, color, fs) rect.center = (DISPLAY_WIDTH / 2), (DISPLAY_HEIGHT / 2) + y_displace screen.blit(surface, rect) def game_loop(screen): highscore = 0 #highscore = pickle.load(open(PICKLE_PATH, "rb" )) game_exit = False game_over = False game_hack = False speed = 10 lead_x = DISPLAY_WIDTH/2 lead_y = DISPLAY_HEIGHT/2 lead_x_change = 0 lead_y_change = 0 #pygame.mixer.music.load(os.pBLOCK_SIZEh.join(os.getcwd(), 'Sounds', 'music1.ogg')) #pygame.mixer.music.play(-1) snake = [(100, 100)] score = 0 apple_x, apple_y = rand_apple_pos() apple_rect = pygame.Rect(apple_x, apple_y, BLOCK_SIZE, BLOCK_SIZE) clock = pygame.time.Clock() while not game_exit: while game_over == 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: game_over = False game_exit = True pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_KP_ENTER or event.key==pygame.K_RETURN: #gameLoop() game_over = False if event.key == pygame.K_SPACE: game_exit = False game_over = False menu(1) while game_hack == 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: game_over = False game_exit = 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() lead_x += lead_x_change lead_y += lead_y_change prev_x, prev_y = lead_x_change, lead_y_change # --- events --- for event in pygame.event.get(): if event.type == pygame.QUIT: game_exit = True pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and prev_x != BLOCK_SIZE: lead_x_change, lead_y_change = -BLOCK_SIZE, 0 elif event.key == pygame.K_RIGHT and prev_x != -BLOCK_SIZE: lead_x_change, lead_y_change = BLOCK_SIZE, 0 elif event.key == pygame.K_UP and prev_y != BLOCK_SIZE: lead_x_change, lead_y_change = 0, -BLOCK_SIZE elif event.key == pygame.K_DOWN and prev_y != -BLOCK_SIZE: lead_x_change, lead_y_change = 0, BLOCK_SIZE 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) elif event.key == pygame.K_a: score += 1 # --- moves --- if not pygame.Rect(0, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT).contains(lead_x, lead_y, BLOCK_SIZE, BLOCK_SIZE): game_over = True if apple_rect.collidepoint(lead_x, lead_y): while True: apple_x, apple_y = rand_apple_pos() # update existing Rect without creating new Rect apple_rect.x = apple_x apple_rect.y = apple_x if not apple_rect.collidepoint(lead_x, lead_y) and \ not any(apple_rect.collidepoint(*pos) for pos in snake): break score += 1 # update snake snake.append( (lead_x, lead_y) ) if len(snake) > score: del snake[0] for segment in snake[:-1]: if segment == snake[-1]: game_over = True if score > highscore: #pickle.dump(score, open(PICKLE_PATH, "wb")) highscore = score if score > 2304: game_hack = True # --- draw --- screen.fill(WHITE) #draw_wall(screen) for row in range(HEIGHT): for column in range(WIDTH): if tilemap[row][column] == 1: pygame.draw.rect(screen, GREY, (column*TILE_SIZE, row*TILE_SIZE, TILE_SIZE, TILE_SIZE)) draw_snake(screen, snake) #draw the apple #draw_apple(screen, apple) pygame.draw.rect(screen, RED, apple_rect) draw_score(screen, score) draw_highscore(screen, highscore) pygame.display.update() clock.tick(speed) # --- end --- pygame.quit() sys.quit() # --- variables --- tilemap = [ [1,1,1,1,1,1,1,1,1,1,1,1], [1,0,0,1,1,0,0,1,1,0,0,1], [1,0,0,1,1,0,0,1,1,0,0,1], [1,0,0,1,1,0,0,1,1,0,0,1], [1,0,0,1,1,0,0,1,1,0,0,1], [1,0,0,1,1,0,0,1,1,0,0,1], [1,0,0,1,1,0,0,1,1,0,0,1], [1,1,1,1,1,1,1,1,1,1,1,1], ] HEIGHT = len(tilemap) WIDTH = len(tilemap[0]) # --- main --- pygame.mixer.pre_init() pygame.mixer.init(44100, 16, 2, 262144) pygame.init() screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_WIDTH)) game_loop(screen)
Pygame function error bug
I can't seem to the error in this code, the game simply quits right after launching it. If anybody could read through my code and answer me what I'm doing wrong, and I'd be very grateful. I've already read through all of it and couldn't figure it out. I don't know why the game quits right after launching it. (Meaning I can't even move my block). import pygame import time pygame.init() width = 800 height = 600 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) gameDisplay = pygame.display.set_mode((width, height)) pygame.display.set_caption("First snake game.") clock = pygame.time.Clock() block_size = 1 FPS = 100 def gameloop(): gameExit = False lead_x = width/2 lead_y = height/2 lead_x_change = 0 lead_y_change = 0 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_w: lead_y_change = -block_size lead_x_change = 0 if event.key == pygame.K_s: lead_y_change = block_size lead_x_change = 0 if event.key == pygame.K_d: lead_x_change = block_size lead_y_change = 0 if event.key == pygame.K_a: lead_x_change = -block_size lead_y_change = 0 if event.type == pygame.KEYUP: if event.key == pygame.K_a or event.key == pygame.K_d: lead_x_change = 0 if event.key == pygame.K_w or event.key == pygame.K_s: lead_y_change = 0 lead_x += lead_x_change lead_y += lead_y_change gameDisplay.fill(white) pygame.draw.rect(gameDisplay, black, [lead_x, lead_y, block_size, block_size]) pygame.display.update() time.sleep(2) pygame.quit() quit() clock.tick(FPS) gameloop() `
Not sure if I'm understanding the code correctly or not, but at the end of the gameloop() function you have pygame.quit() and quit() so comment that out and see what happens.
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()
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