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
I'm trying to make a game, and I want to make the user be able to change color of their sprite when pressing backspace. As of now, nothing that I draw appears on screen, I have no idea why. Any detailed answer, explaining how and why you change the color of your sprite would be welcome:
This is my code:
import pygame
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
width = 800
height = 600
FPS = 100
font = pygame.font.SysFont(None, 25)
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Second snake game.")
clock = pygame.time.Clock()
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [width/2, height/2])
def gameloop():
exitGame = False
lead_x = width/2
lead_y = height/2
lead_x_change = 0
lead_y_change = 0
block_size = 10
velocity = 0.1
rectangle = pygame.draw.rect(gameDisplay, black, [lead_x, lead_y, block_size, block_size])
while not exitGame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
lead_y_change += -velocity
lead_x_change = 0
if event.key == pygame.K_s:
lead_y_change += velocity
lead_x_change = 0
if event.key == pygame.K_a:
lead_x_change += -velocity
lead_y_change = 0
if event.key == pygame.K_d:
lead_x_change += velocity
lead_y_change = 0
if event.key == pygame.K_BACKSPACE:
rectangle.rect(gameDisplay, black, [lead_x, lead_y, block_size, block_size])
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.display.update()
clock.tick(FPS)
gameloop()
First, put the rendering functions in an appropriate order and put them in your while loop:
gameDisplay.fill(white) # Display fill comes first
pygame.draw.rect(gameDisplay, black, rectangle) # Then draw your objects
pygame.display.flip() # Update the screen
Then, define the pygame.Rect object properly
rectangle = pygame.Rect(lead_x, lead_y, block_size, block_size)
This is what you are probably trying to find (with my few fixes):
import pygame
pygame.init()
# Constants
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
WIDTH = 800
HEIGHT = 600
FPS = 100
FONT = pygame.font.SysFont(None, 25)
BLOCK_SIZE = 10
VELOCITY = 10
gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Second snake game.")
clock = pygame.time.Clock()
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [width/2, height/2])
def gameloop():
exitGame = False
x = WIDTH / 2
y = HEIGHT / 2
rectangle = pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE)
rectangle_color = BLACK
while not exitGame:
clock.tick(FPS)
# Pygame events
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
pygame.quit()
quit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
y -= VELOCITY
if event.key == pygame.K_s:
y += VELOCITY
if event.key == pygame.K_a:
x -= VELOCITY
if event.key == pygame.K_d:
x += VELOCITY
if event.key == pygame.K_BACKSPACE:
rectangle_color = RED if rectangle_color == BLACK else BLACK
# Update rect coords
rectangle = pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE)
# Render everything
gameDisplay.fill(WHITE)
pygame.draw.rect(gameDisplay, rectangle_color, rectangle)
pygame.display.flip()
gameloop()
I am using python 2.7 an tried to make a simple game using the pygame module. In the program it makes a rectangle, and what I am having trouble doing is getting it to move upon keys being pressed. I believe the problem is with the 'player.move' part in my code, but the documentation was poor for it on pygames website. Any help is appreciated.
import pygame
import random
import time
pygame.init()
white = (255,255,255)
black = (0,0,0)
displayWidth = 800
displayHeight = 800
FPS = 30
clock = pygame.time.Clock()
blockWidth = 50
blockHeight = 50
pygame.display.set_caption('Test Game')
screen = pygame.display.set_mode([displayWidth, displayHeight])
background = pygame.Surface(screen.get_size())
background.fill((white))
background = background.convert()
screen.blit(background, (0,0))
global xStart, yStart
xStart = 400
yStart = 400
global player
player = pygame.draw.rect(screen, black, ([xStart,yStart,blockWidth,blockHeight]))
pygame.display.update()
def mainloop():
global x, y
x = xStart
y = yStart
mainloop = True
pygame.display.update()
while mainloop == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
if event.key == pygame.K_UP:
player.move(x, y + 10)
pygame.display.update()
if event.key == pygame.K_DOWN:
player.move(x, y - 10)
pygame.display.update()
if event.key == pygame.K_LEFT:
player.move(x - 10, y)
pygame.display.update()
if event.key == pygame.K_RIGHT:
player.move(x + 10, y)
pygame.display.update()
clock.tick(FPS)
pygame.display.flip()
mainloop()
pygame.quit()
Find tutorial (ie, Program Arcade Games With Python And Pygame) because you have many things to change.
PyGame is low-level library and you have to do everything on your own. In while loop you have to clear screen or draw background and draw player - again and again.
Here your code after modifications.
You have to learn pygame.Rect, pygame.Surface, (pygame.Sprite), events, etc.
import pygame
import random
import time
# --- constants --- (UPPER_CASE names)
WHITE = (255, 255, 255)
BLACK = (0 , 0, 0)
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 800
FPS = 30
BLOCK_WIDTH = 50
BLOCK_HEIGHT = 50
# --- functions --- (lower_case names)
def run():
mainloop = True
speed_x = 0
speed_y = 0
while mainloop:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
# - start moving -
elif event.key == pygame.K_UP:
speed_y = -10
elif event.key == pygame.K_DOWN:
speed_y = 10
elif event.key == pygame.K_LEFT:
speed_x = -10
elif event.key == pygame.K_RIGHT:
speed_x = 10
#elif event.type == pygame.KEYUP:
# # - stop moving -
# if event.key == pygame.K_UP:
# speed_y = 0
# elif event.key == pygame.K_DOWN:
# speed_y = 0
# elif event.key == pygame.K_LEFT:
# speed_x = 0
# elif event.key == pygame.K_RIGHT:
# speed_x = 0
# --- updates ---
player_rect.move_ip(speed_x, speed_y)
# --- draws ---
screen.blit(background, background_rect)
screen.blit(player, player_rect)
pygame.display.flip()
clock.tick(FPS)
# --- main ---
pygame.init()
pygame.display.set_caption('Test Game')
screen = pygame.display.set_mode( (DISPLAY_WIDTH, DISPLAY_HEIGHT) )
screen_rect = screen.get_rect()
background_rect = screen_rect
background = pygame.Surface(background_rect.size)
background.fill(WHITE)
background = background.convert()
player_rect = pygame.Rect(400, 400, BLOCK_WIDTH, BLOCK_HEIGHT)
player = pygame.Surface(player_rect.size)
player.fill(BLACK)
clock = pygame.time.Clock()
run()
pygame.quit()
My teacher checked my code and we have no idea what is giving me this error, the last thing I updated was the 'fireShell' definition. Game was working before I implemented that definition and when you press space the game crashes. It's a tank game and the random snake stuff is from old code we made.
import pygame
import time
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
purple = (200,0,200)
green = (0,155,0)
yellow = (255,255,0)
pink = (255,153,204)
light_green = (0,255,0)
orange = (255,165,0)
clock = pygame.time.Clock()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Tanks')
#icon = pygame.image.load('snakeHead.png')
#pygame.display.set_icon(icon)
#img = pygame.image.load('snakeHead.png')
#appleimg = pygame.image.load('apple.png')
FPS = 10
tankWidth = 40
tankHeight = 20
turretWidth = 5
wheelWidth = 5
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 40)
largefont = pygame.font.SysFont("comicsansms", 70)
def tank(x,y,turPos):
x = int(x)
y = int(y)
possibleTurrets = [(x-27, y-2),
(x-26, y-5),
(x-25, y-8),
(x-23, y-12),
(x-20, y-14),
(x-18, y-15),
(x-15, y-17),
(x-13, y-19),
(x-11, y-21),
]
pygame.draw.circle(gameDisplay, black, (x,y),10)
pygame.draw.rect(gameDisplay, black, (x-tankHeight, y, tankWidth, tankHeight))
pygame.draw.line(gameDisplay, black, (x,y,), possibleTurrets[turPos], turretWidth)
pygame.draw.circle(gameDisplay, black, (x-15, y+20), wheelWidth)
pygame.draw.circle(gameDisplay, black, (x-10, y+20), wheelWidth)
pygame.draw.circle(gameDisplay, black, (x-5, y+20), wheelWidth)
pygame.draw.circle(gameDisplay, black, (x, y+20), wheelWidth)
pygame.draw.circle(gameDisplay, black, (x+5, y+20), wheelWidth)
pygame.draw.circle(gameDisplay, black, (x+10, y+20), wheelWidth)
pygame.draw.circle(gameDisplay, black, (x+15, y+20), wheelWidth)
def introbutton():
cur = pygame.mouse.get_pos()
if 150+100> cur[0] > 150 and 500+50 > cur[1] > 500:
pygame.draw.rect(gameDisplay,light_green,(150,500,100,50))
else:
pygame.draw.rect(gameDisplay,green,(150,500,100,50))
if 350+100> cur[0] > 350 and 500+50 > cur[1] > 500:
pygame.draw.rect(gameDisplay,pink,(350,500,100,50))
else:
pygame.draw.rect(gameDisplay,yellow,(350,500,100,50))
if 550+100> cur [0] > 550 and 500+50 > cur[1] > 500:
pygame.draw.rect(gameDisplay,orange,(550,500,100,50))
else:
pygame.draw.rect(gameDisplay,red,(550,500,100,50))
def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx+(buttonwidth/2)), buttony+(buttonheight/2))
gameDisplay.blit(textSurf, textRect)
def controls():
controls = True
while controls:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Controls",
green,
-100,
"large")
message_to_screen("Fire: Spacebar",
black,
-30)
message_to_screen("Move Turret: W & S",
black,
10)
message_to_screen("Move Tank: A & D",
black,
50)
message_to_screen("Pause: P",
black,
90,)
introbutton()
button("play",
150,500,100,50,
green,
light_green,
action = "play")
button("menu",
350,500,100,50,
yellow,
pink,
action = "menu")
button("quit",
550,500,100,50,
red,
orange,
action = "quit")
pygame.display.update()
clock.tick(15)
def button(text, x, y, width, height, inactive_color, active_color, action = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x,y,width,height))
if click[0] == 1 and action != None:
if action == "quit":
pygame.quit()
quit()
if action == "play":
gameLoop()
if action == "controls":
controls()
if action == "menu":
game_intro()
else:
pygame.draw.rect(gameDisplay,inactive_color, (x,y,width,height))
text_to_button(text,black,x,y,width,height)
def pause():
paused = True
message_to_screen("Paused",
black,
-100,
"large")
message_to_screen("Press C to continue or Q to quit.",
black,
25)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()
clock.tick(5)
def score(score):
text = smallfont.render("score: "+str(score), True, black)
gameDisplay.blit(text, [0,0])
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
intro = False
if event.key == pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Welcome to Tanks",
green,
-100,
"large")
message_to_screen("The objective of the game is to shoot and destroy",
black,
-30)
message_to_screen("the enemy tank before they destroy you.",
black,
10)
message_to_screen("The more enemies you destroy the harder it gets.",
black,
50)
introbutton()
button("play",
150,500,100,50,
green,
light_green,
action = "play")
button("controls",
350,500,100,50,
yellow,
pink,
action = "controls")
button("quit",
550,500,100,50,
red,
orange,
action = "quit")
pygame.display.update()
clock.tick(15)
def text_objects(text, color, size):
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def message_to_screen(msg, color, y_displace=0, size = "small"):
textSurf, textRect = text_objects(msg,color, size)
textRect.center = (display_width/2), (display_height/2)+y_displace
gameDisplay.blit(textSurf, textRect)
def barrier(xlocation,randomHeight, barrier_width):
#xlocation = (display_width/2) + random.randint(-0.2*display_width, 0.2*display_width)
#randomHeight = random.randrange(display_height*0.1,display_height*0.6)
pygame.draw.rect(gameDisplay, black, [xlocation, display_height-randomHeight, 50, randomHeight])
def fireShell(xy,tankx,tanky,turPos):
fire = True
startingShell = list(xy)
print("FIRE",xy)
while fire:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
print(startingShell[0],startingShell[1])
pygame.draw.circle(gameDisplay, red, (startingShell[0],startingShell[1]),5)
startingShell[0] -= (12 - turPos)*2
startingShell[1] += int((((startingShell[0]-xy[0])*0.015)**2) - (turPos+turPos/(12-turPos)))
if startingShell[1] > display_height:
fire = False
pygame.display.update()
clock.tick(60)
def gameLoop():
gameExit = False
gameOver = False
mainTankX = display_width * 0.9
mainTankY = display_height * 0.7
tankMove = 0
currentTurPos = 0
changeTur = 0
barrier_width = 50
xlocation = (display_width/2) + random.randint(-0.2*display_width, 0.2*display_width)
randomHeight = random.randrange(display_height*0.1,display_height*0.6)
while not gameExit:
gameDisplay.fill(white)
gun = tank(mainTankX,mainTankY,currentTurPos)
if gameOver == True:
message_to_screen("Game Over",
purple,
-50,
"large")
message_to_screen("Press C to play again or Q to quit",
black,
50,
"medium")
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False
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:
tankMove = -5
elif event.key == pygame.K_RIGHT:
tankMove = 5
elif event.key == pygame.K_UP:
changeTur = 1
elif event.key == pygame.K_DOWN:
changeTur = -1
elif event.key == pygame.K_p:
pause()
elif event.key == pygame.K_SPACE:
fireShell(gun,mainTankX,mainTankY,currentTurPos)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
tankMove = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
changeTur = 0
#gameDisplay.fill(white)
mainTankX += tankMove
currentTurPos += changeTur
if currentTurPos > 8:
currentTurPos = 8
elif currentTurPos < 0:
currentTurPos = 0
if mainTankX - (tankWidth/2) < xlocation+barrier_width:
mainTankX += 5
#tank(mainTankX,mainTankY,currentTurPos)
##for x in range(1):
barrier(xlocation, randomHeight, barrier_width)
#score(snakeLength-1)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
game_intro()
gameLoop()
The first place that I'd check (with more prints, tests, etc) is
def fireShell(xy,tankx,tanky,turPos):
...
while fire:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
That's the only iteration within the new function. If pygame.event.get() returns None, I'd expect this error
In [235]: for i in None:print(i)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-235-5168590b751e> in <module>()
----> 1 for i in None:print(i)
TypeError: 'NoneType' object is not iterable
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()