Pygame restart function - python

I am doing a game where you control a snake and when he dies the game quits. I have tried adding a different function (on) so only while on is true the game will continue. However, this does not restart here is the code I have and could anyone put in a restart function?
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Happy Birthday Mum')
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
diff = 30
def gameOver():
gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if event.key == K_1:
diff = 10
if event.key == K_2:
diff = 20
if event.key == K_3:
diff = 30
if event.key == K_4:
diff = 40
if event.key == K_5:
diff = 50
if event.key == K_r:
restart()
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeSegments.insert(0,list(snakePosition))
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
playSurface.fill(blackColour)
for position in snakeSegments:
pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver()
if snakePosition[1] > 460 or snakePosition[1] < 0:
gameOver()
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
gameOver()
fpsClock.tick(diff)

You essentially want two while loops - one for when the overall game is running, and a smaller one while the snake is alive.
start pygame and set global variables;
while the program is running:
set all of the initial variables for the game (snake position, etc)
while the snake is alive:
handle input;
check to see if the snake is dead;
I've taken your python code and structured it this way. Pay attention to where I set the variable snake_is_alive to false. See how it makes the inner loop end, but makes the outer loop start over.
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Happy Birthday Mum')
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
game_is_running = True
while game_is_running:
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
diff = 30
snake_is_alive = True
while snake_is_alive:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if event.key == K_1:
diff = 10
if event.key == K_2:
diff = 20
if event.key == K_3:
diff = 30
if event.key == K_4:
diff = 40
if event.key == K_5:
diff = 50
if event.key == K_r:
snake_is_alive = False
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeSegments.insert(0,list(snakePosition))
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
playSurface.fill(blackColour)
for position in snakeSegments:
pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
snake_is_alive = False
if snakePosition[1] > 460 or snakePosition[1] < 0:
snake_is_alive = False
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
snake_is_alive = False
fpsClock.tick(diff)
gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
I got rid of the functions to make it easier to read, but even if you make functions, the overall structure (inner loop and outer loop) should remain the same.

You need to turn your game into a function just like you did with end game. Then in your end game loop instead of exiting just call playGame again. Make sure that you reset all your variables to there original state at the begging of the loop before the while. Something like this: (pseudo code)
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Happy Birthday Mum')
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
diff = 30
def gameOver():
gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
playGame();
def playGame():
RESET ALL GAME VARIABLES HERE
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if event.key == K_1:
diff = 10
if event.key == K_2:
diff = 20
if event.key == K_3:
diff = 30
if event.key == K_4:
diff = 40
if event.key == K_5:
diff = 50
if event.key == K_r:
restart()
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeSegments.insert(0,list(snakePosition))
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
playSurface.fill(blackColour)
for position in snakeSegments:
pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver()
if snakePosition[1] > 460 or snakePosition[1] < 0:
gameOver()
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
gameOver()
fpsClock.tick(diff)
playGame();

Related

I can't restart game after game over [duplicate]

I am doing a game where you control a snake and when he dies the game quits. I have tried adding a different function (on) so only while on is true the game will continue. However, this does not restart here is the code I have and could anyone put in a restart function?
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Happy Birthday Mum')
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
diff = 30
def gameOver():
gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if event.key == K_1:
diff = 10
if event.key == K_2:
diff = 20
if event.key == K_3:
diff = 30
if event.key == K_4:
diff = 40
if event.key == K_5:
diff = 50
if event.key == K_r:
restart()
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeSegments.insert(0,list(snakePosition))
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
playSurface.fill(blackColour)
for position in snakeSegments:
pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver()
if snakePosition[1] > 460 or snakePosition[1] < 0:
gameOver()
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
gameOver()
fpsClock.tick(diff)
You essentially want two while loops - one for when the overall game is running, and a smaller one while the snake is alive.
start pygame and set global variables;
while the program is running:
set all of the initial variables for the game (snake position, etc)
while the snake is alive:
handle input;
check to see if the snake is dead;
I've taken your python code and structured it this way. Pay attention to where I set the variable snake_is_alive to false. See how it makes the inner loop end, but makes the outer loop start over.
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Happy Birthday Mum')
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
game_is_running = True
while game_is_running:
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
diff = 30
snake_is_alive = True
while snake_is_alive:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if event.key == K_1:
diff = 10
if event.key == K_2:
diff = 20
if event.key == K_3:
diff = 30
if event.key == K_4:
diff = 40
if event.key == K_5:
diff = 50
if event.key == K_r:
snake_is_alive = False
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeSegments.insert(0,list(snakePosition))
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
playSurface.fill(blackColour)
for position in snakeSegments:
pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
snake_is_alive = False
if snakePosition[1] > 460 or snakePosition[1] < 0:
snake_is_alive = False
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
snake_is_alive = False
fpsClock.tick(diff)
gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
I got rid of the functions to make it easier to read, but even if you make functions, the overall structure (inner loop and outer loop) should remain the same.
You need to turn your game into a function just like you did with end game. Then in your end game loop instead of exiting just call playGame again. Make sure that you reset all your variables to there original state at the begging of the loop before the while. Something like this: (pseudo code)
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fpsClock = pygame.time.Clock()
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Happy Birthday Mum')
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)
snakePosition = [100,100]
snakeSegments = [[100,100],[80,100],[60,100]]
raspberryPosition = [300,300]
raspberrySpawned = 1
direction = 'right'
changeDirection = direction
diff = 30
def gameOver():
gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
playGame();
def playGame():
RESET ALL GAME VARIABLES HERE
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if event.key == K_1:
diff = 10
if event.key == K_2:
diff = 20
if event.key == K_3:
diff = 30
if event.key == K_4:
diff = 40
if event.key == K_5:
diff = 50
if event.key == K_r:
restart()
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
snakeSegments.insert(0,list(snakePosition))
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop()
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
playSurface.fill(blackColour)
for position in snakeSegments:
pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
pygame.display.flip()
if snakePosition[0] > 620 or snakePosition[0] < 0:
gameOver()
if snakePosition[1] > 460 or snakePosition[1] < 0:
gameOver()
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
gameOver()
fpsClock.tick(diff)
playGame();

Player1 control keys work, player2 keys don't work in pygame, any fixes?

There are zero errors that pop up although, the keys work for player1 yet they don't for player2. Class player1 and player2 were copy and pasted which is most likely the problem. Any fixes? The classes set up the movement and set up some variables, while in the function 'main' is where the problem most likely is in.
import math
import pygame as pg
from pygame.math import Vector2
class Player1(pg.sprite.Sprite):
def __init__(self, pos=(420, 420)):
super(Player1, self).__init__()
self.image = pg.Surface((70, 50), pg.SRCALPHA)
pg.draw.polygon(self.image, (50, 120, 180), ((0, 0), (0, 50), (70, 25)))
self.original_image = self.image
self.rect = self.image.get_rect(center=pos)
self.position = Vector2(pos)
self.direction = Vector2(1, 0)
self.speed = 2
self.angle_speed = 0
self.angle = 0
def update(self):
if self.angle_speed != 0:
self.direction.rotate_ip(self.angle_speed)
self.angle += self.angle_speed
self.image = pg.transform.rotate(self.original_image, -self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
self.position += self.direction * self.speed
self.rect.center = self.position
class Player2(pg.sprite.Sprite):
def __init__(self, pos=(420, 420)):
super(Player2, self).__init__()
self.image = pg.Surface((70, 50), pg.SRCALPHA)
pg.draw.polygon(self.image, (50, 120, 180), ((0, 0), (0, 50), (70, 25)))
self.original_image = self.image
self.rect = self.image.get_rect(center=pos)
self.position = Vector2(pos)
self.direction = Vector2(1, 0)
self.speed = 2
self.angle_speed = 0
self.angle = 0
def update(self):
if self.angle_speed != 0:
self.direction.rotate_ip(self.angle_speed)
self.angle += self.angle_speed
self.image = pg.transform.rotate(self.original_image, -self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
self.position += self.direction * self.speed
self.rect.center = self.position
def main():
pg.init()
screen = pg.display.set_mode((1280, 720))
player1 = Player1((420, 420))
player2 = Player2((1000, 100))
playersprite1 = pg.sprite.RenderPlain((player1))
playersprite2 = pg.sprite.RenderPlain((player2))
clock = pg.time.Clock()
done = False
while not done:
clock.tick(60)
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_UP:
player1.speed += 1
elif event.key == pg.K_DOWN:
player1.speed -= 1
elif event.key == pg.K_LEFT:
player1.angle_speed = -4
elif event.key == pg.K_RIGHT:
player1.angle_speed = 4
elif event.type == pg.KEYUP:
if event.key == pg.K_LEFT:
player1.angle_speed = 0
elif event.key == pg.K_RIGHT:
player1.angle_speed = 0
elif event.type == pg.KEYDOWN:
if event.key == pg.K_w:
player2.speed += 1
elif event.key == pg.K_s:
player2.speed -= 1
elif event.key == pg.K_a:
player2.angle_speed = -4
elif event.key == pg.K_d:
player2.angle_speed = 4
elif event.type == pg.KEYUP:
if event.key == pg.K_a:
player2.angle_speed = 0
elif event.key == pg.K_d:
player2.angle_speed = 0
playersprite1.update()
playersprite2.update()
screen.fill((30, 30, 30))
playersprite1.draw(screen)
playersprite2.draw(screen)
pg.display.flip()
if __name__ == '__main__':
main()
pg.quit()
You have constructed something like
if a:
# [...] code block 1
elif b:
# [...] code block 2
elif a:
# [...] code block 3
elif b:
# [...] code block 4
The "code block 3" and "code block 4" will never be executed.
Combine the key evaluation in a single elif event.type == pg.KEYDOWN and a single elif event.type == pg.KEYUP: block:
def main():
# [...]
done = False
while not done:
clock.tick(60)
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_UP:
player1.speed += 1
elif event.key == pg.K_DOWN:
player1.speed -= 1
elif event.key == pg.K_LEFT:
player1.angle_speed = -4
elif event.key == pg.K_RIGHT:
player1.angle_speed = 4
elif event.key == pg.K_w:
player2.speed += 1
elif event.key == pg.K_s:
player2.speed -= 1
elif event.key == pg.K_a:
player2.angle_speed = -4
elif event.key == pg.K_d:
player2.angle_speed = 4
elif event.type == pg.KEYUP:
if event.key == pg.K_LEFT:
player1.angle_speed = 0
elif event.key == pg.K_RIGHT:
player1.angle_speed = 0
elif event.key == pg.K_a:
player2.angle_speed = 0
elif event.key == pg.K_d:
player2.angle_speed = 0
However, you can greatly simplify the code by using pygame.key.get_pressed():
def main():
# [...]
done = False
while not done:
clock.tick(60)
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
keys = pygame.key.get_pressed()
player1.speed = keys[pg.K_UP] - keys[pg.KEYDOWN]
player1.angle_speed = (keys[pg.K_RIGHT] - keys[pg.K_LEFT]) * 4
player2.speed = keys[pg.K_w] - keys[pg.K_s]
player2.angle_speed = (keys[pg.K_d] - keys[pg.K_a]) * 4
# [...]

how to solve bug on snake wall teleportation

I'm doing a snake game and I got a bug I can't figure out how to solve, I want to make my snake teleport trough walls, when the snake colllides with a wall it teleports to another with the opposite speed and position, like the classic game, but with my code when the snake gets near the wall it duplicates to the opposite wall, but it was supposed to not even detect collision yet
important thing: in the grid the snake is on the side of the wall, like this
SSSS
WWWW
and not like this:
SSSS
NNNN
WWWW
when S represents the snake, W represents the wall and N represents nothing.
edit: whole code
import pygame, random, os, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1020, 585))
pygame.display.set_caption('2snakes!')
#files location
current_path = os.path.dirname(__file__)
data_path = os.path.join(current_path, 'data')
icon = pygame.image.load(os.path.join(data_path, 'icon.png'))
press_any = pygame.image.load(os.path.join(data_path, 'press_any.png'))
pygame.display.set_icon(icon)
#collission
def collision(c1,c2):
return (c1[0] == c2[0]) and (c1[1] == c2[1])
#game over
def gameOverBlue():
print("blue")
main()
def gameOverRed():
print("red")
main()
fps = 15
def main():
#variables
direction = 'RIGHT'
direction2 = 'RIGHT'
change_to = direction
change2_to = direction2
#snake
size = 15
s_posx = 60
s_posy = 60
snake = [(s_posx + size * 2, s_posy),(s_posx + size, s_posy),(s_posx, s_posy)]
s_skin = pygame.Surface((size, size))
s_skin.fill((82,128,208))
#snake2
size2 = 15
s2_posx = 390
s2_posy = 390
snake2 = [(s2_posx + size2 * 2, s2_posy),(s2_posx + size2, s2_posy),(s2_posx, s2_posy)]
s2_skin = pygame.Surface((size2, size2))
s2_skin.fill((208,128,82))
#apple
apple = pygame.Surface((size, size))
apple_pos = ((random.randint(0, 67)) * 15, (random.randint(0, 38)) * 15)
#endregion
while True:
pygame.time.Clock().tick(fps)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
#input
elif event.type == pygame.KEYDOWN:
#snake
if event.key == ord('w'):
change_to = 'UP'
if event.key == ord('s'):
change_to = 'DOWN'
if event.key == ord('a'):
change_to = 'LEFT'
if event.key == ord('d'):
change_to = 'RIGHT'
#snake2
if event.key == pygame.K_UP:
change2_to = 'UP'
if event.key == pygame.K_DOWN:
change2_to = 'DOWN'
if event.key == pygame.K_LEFT:
change2_to = 'LEFT'
if event.key == pygame.K_RIGHT:
change2_to = 'RIGHT'
#quit game
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.quit()
#smoot snake movement
#snake
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
#snake2
if change2_to == 'UP' and direction2 != 'DOWN':
direction2 = 'UP'
if change2_to == 'DOWN' and direction2 != 'UP':
direction2 = 'DOWN'
if change2_to == 'LEFT' and direction2 != 'RIGHT':
direction2 = 'LEFT'
if change2_to == 'RIGHT' and direction2 != 'LEFT':
direction2 = 'RIGHT'
#movement
#snake
new_pos = None
if direction == 'DOWN':
new_pos = (snake[0][0], snake[0][1] + size)
if direction == 'UP':
new_pos = (snake[0][0], snake[0][1] - size)
if direction == 'LEFT':
new_pos = (snake[0][0] - size, snake[0][1])
if direction == 'RIGHT':
new_pos = (snake[0][0] + size, snake[0][1])
if new_pos:
snake = [new_pos] + snake
del snake[-1]
#snake2
new_pos2 = None
if direction2 == 'DOWN':
new_pos2 = (snake2[0][0], snake2[0][1] + size2)
if direction2 == 'UP':
new_pos2 = (snake2[0][0], snake2[0][1] - size2)
if direction2 == 'LEFT':
new_pos2 = (snake2[0][0] - size2, snake2[0][1])
if direction2 == 'RIGHT':
new_pos2 = (snake2[0][0] + size2, snake2[0][1])
if new_pos2:
snake2 = [new_pos2] + snake2
del snake2[-1]
#apple collision
#snake
if collision(snake[0], apple_pos):
snake.append((-20,-20))
size = 15
s_skin = pygame.Surface((size, size))
s_skin.fill((82,128,208))
apple_pos = ((random.randint(0, 32)) * 15, (random.randint(0, 19)) * 15)
#snake2
if collision(snake2[0], apple_pos):
snake2.append((-20,-20))
apple_pos = ((random.randint(0, 67)) * 15, (random.randint(0, 38)) * 15)
#wall collisison
#snake
_pos = None
if snake[0][0] == 15:
_pos = (990, snake[0][1])
elif snake[0][1] == 15:
_pos = (snake[0][0], 555)
elif snake[0][0] == 990:
_pos = (15, snake[0][1])
elif snake[0][1] == 555:
_pos = (snake[0][0], 15)
if _pos:
snake = [_pos] + snake
del snake[-1]
#snake2
_pos2 = None
if snake2[0][0] == 15:
_pos2 = (1005, snake2[0][1])
elif snake2[0][1] == 0:
_pos2 = (snake2[0][0], 570)
elif snake2[0][0] == 1005:
_pos2 = (0, snake2[0][1])
elif snake2[0][1] == 570:
_pos2 = (snake2[0][0], 0)
if _pos2:
snake2 = [_pos2] + snake2
del snake2[-1]
#self collisison
#snake
if snake[0] in snake[1:]:
print("self collision")
gameOverBlue()
#snake2
if snake2[0] in snake2[1:]:
print("self collision")
gameOverRed()
#snakes colliding with each other
if snake2[0] == snake[0]:
print("head to head collisions")
if snake[0] in snake2:
gameOverRed()
if snake2[0] in snake:
gameOverBlue()
#rendering
apple.fill((255,0,0))
screen.fill((10,10,10))
screen.blit(apple,apple_pos)
for pos in snake:
screen.blit(s_skin,pos)
for pos2 in snake2:
screen.blit(s2_skin,pos2)
pygame.display.update()
while True:
pygame.time.Clock().tick(fps)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
#input
elif event.type == pygame.KEYDOWN:
main()
screen.blit(press_any, (0,0))
pygame.display.update()
edit: the red dot is the food/apple
You want to implement a teleporter. Therefore, once the snake is over the edge of the window, you will have to teleport to the other side. The size of your window is 1020x585. The snake is out of the window if x == -15, y == -15, x == 1020 or y == 585 Hence you have to do the following teleportations:
if x = 1020 teleport to x = 0
if x = -15 teleport to x = 1005
if y = 585 teleport to y = 0
if y = -15 teleport to y = 570
_pos = None
if snake[0][0] == -15:
_pos = (1005, snake[0][1])
elif snake[0][1] == -15:
_pos = (snake[0][0], 570)
elif snake[0][0] == 1020:
_pos = (0, snake[0][1])
elif snake[0][1] == 585:
_pos = (snake[0][0], 0)
if _pos:
snake = [_pos] + snake
del snake[-1]

Make Character Keep Moving While Key Held Down

I'm trying to make a quick animation where if a key is held down the character will keep moving, however my code doesn't seem to be doing that. I press the key and moves once but doesn't move any further. Any help to fix this. Any other suggestions are appreciated and keep in mind this isn't near final product form.
import pygame
import os
import sys
from pygame.locals import *
pygame.init()
WIN = pygame.display.set_mode(display)
pygame.display.set_caption('The Game')
width = 500
height = 500
display = (width, height)
WHITE = (255, 255, 255)
left = [
pygame.image.load(os.path.join('assets', 'main', 'left_walk1.png')),
pygame.image.load(os.path.join('assets', 'main', 'left_walk2.png'))
]
right = [
pygame.image.load(os.path.join('assets', 'main', 'right_walk1.png')),
pygame.image.load(os.path.join('assets', 'main', 'right_walk2.png'))
]
up = [
pygame.image.load(os.path.join('assets', 'main', 'up_walk1.png')),
pygame.image.load(os.path.join('assets', 'main', 'up_walk2.png'))
]
down = [
pygame.image.load(os.path.join('assets', 'main', 'down_walk1.png')),
pygame.image.load(os.path.join('assets', 'main', 'down_walk2.png'))
]
standing_left = (os.path.join('assets', 'main', 'down_walk2.png'))
standing_right = (os.path.join('assets', 'main', 'down_walk2.png'))
standing_up = (os.path.join('assets', 'main', 'down_walk2.png'))
standing_down = (os.path.join('assets', 'main', 'down_walk2.png'))
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
self.health = 100
self.inv = []
self.left = False
self.right = False
self.up = False
self.down = False
self.walking_count = 0
self.facing = 'down'
def draw_player(self, win):
if self.walking_count == 3:
self.walking_count = 1
if self.left:
WIN.blit(left[self.walking_count // 2], (self.x, self.y))
elif self.right:
WIN.blit(right[self.walking_count // 2], (self.x, self.y))
player = Player(100, 100)
FPS = 40
fpsClock = pygame.time.Clock()
while True:
fpsClock.tick(FPS)
WIN.fill(WHITE)
player.draw_player(WIN)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_UP and player.y <= 0:
player.up = True
elif event.key == K_DOWN:
player.down = True
elif event.key == K_LEFT:
player.left = True
elif event.key == K_RIGHT:
player.right = True
elif event.type == KEYUP:
if event.key == K_UP:
player.up = False
if event.key == K_DOWN:
player.down = False
if event.key == K_LEFT:
player.left = False
if event.key == K_RIGHT:
player.right = False
if player.left:
player.x -= 5
player.walking_count += 1
if player.right:
player.x += 5
player.walking_count += 1
if player.up:
player.y -= 5
player.walking_count += 1
if player.down:
player.y += 5
player.walking_count += 1
pygame.display.update()
It is a matter of Indentation. You've to apply the movement in the application loop rather than the event loop:
while True:
fpsClock.tick(FPS)
WIN.fill(WHITE)
player.draw_player(WIN)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_UP and player.y <= 0:
player.up = True
elif event.key == K_DOWN:
player.down = True
elif event.key == K_LEFT:
player.left = True
elif event.key == K_RIGHT:
player.right = True
elif event.type == KEYUP:
if event.key == K_UP:
player.up = False
if event.key == K_DOWN:
player.down = False
if event.key == K_LEFT:
player.left = False
if event.key == K_RIGHT:
player.right = False
#<--| INDENTATION
if player.left:
player.x -= 5
if player.right:
player.x += 5
if player.up:
player.y -= 5
if player.down:
player.y += 5
pygame.display.update()
Alternatively you can use pygame.key.get_pressed() rather than the KEYDOWN and KEYUP event:
while True:
fpsClock.tick(FPS)
WIN.fill(WHITE)
player.draw_player(WIN)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
keys = pygame.key.get_pressed()
player.left, player.right, player.up, player.down = False, False, False, False
if keys[K_LEFT]:
player.x -= 5
player.left = True
if keys[K_RIGHT]:
player.x += 5
player.right = True
if keys[K_UP]:
player.y -= 5
player.up = True
if keys[K_DOWN]:
player.y += 5
player.down = True
pygame.display.update()
To control the animation speed, add an attribute self.animation_frames = 10. This attributes controls how many frames each image of the animation is shown. Compute the image index dependent on the attribute.
walking_count has to be incremented in Player.draw_player rather than the application loop.
To ensure that the correct "standing" image is displayed, you have to add an attribute self.standing. Set the attribute dependent on the current direction in draw_player. If the player is not moving, the display the current standing image:
class Player:
def __init__(self, x, y):
# [...]
self.animation_frames = 10
self.standing = standing_left
def draw_player(self, win):
# get image list
if self.left:
image_list = left
self.standing = standing_left
else self.right:
image_list = right
self.standing = standing_right
else:
image_list = [self.standing]
# increment walk count and get image list
image_index = self.walking_count // self.animation_frames
if image_index >= len(image_list):
image_index = 0
self.walking_count = 0
self.walking_count += 1
WIN.blit(image_list[image_index], (self.x, self.y))

Pygame: Only a portion of the circle is eating things up

I'm trying to make a circle destroy something when it touches it. Then it will grow a little. Eventually at a certain size, I can notice that only a square area within the circle is actually eating it.
import pygame, sys, random
from pygame.locals import *
# set up pygame
pygame.init()
mainClock = pygame.time.Clock()
# set up the window
windowW = 800
windowH = 600
theSurface = pygame.display.set_mode((windowW, windowH), 0, 32)
pygame.display.set_caption('')
basicFont = pygame.font.SysFont('calibri', 36)
# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
size = 10
playercolor = BLACK
# set up the player and food data structure
foodCounter = 0
NEWFOOD = 35
FOODSIZE = 10
player = pygame.draw.circle(theSurface, playercolor, (60, 250), 40)
foods = []
for i in range(20):
foods.append(pygame.Rect(random.randint(0, windowW - FOODSIZE), random.randint(0, windowH - FOODSIZE), FOODSIZE, FOODSIZE))
# set up movement variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
MOVESPEED = 10.3
score = 0
# run the game loop
while True:
# check for events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
# change the keyboard variables
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.key == ord('x'):
player.top = random.randint(0, windowH - player.windowH)
player.left = random.randint(0, windowW - player.windowW)
if event.key == K_SPACE:
pygame.draw.circle(theSurface, playercolor,(player.centerx,player.centery),int(size/2))
pygame.draw.circle(theSurface, playercolor,(player.centerx+size,player.centery+size),int(size/2))
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT:
moveLeft = False
if event.key == K_RIGHT:
moveRight = False
if event.key == K_UP:
moveUp = False
if event.key == K_DOWN:
moveDown = False
if event.type == MOUSEBUTTONUP:
foods.append(pygame.Rect(event.pos[0], event.pos[1], FOODSIZE, FOODSIZE))
foodCounter += 1
if foodCounter >= NEWFOOD:
# add new food
foodCounter = 0
foods.append(pygame.Rect(random.randint(0, windowW - FOODSIZE), random.randint(0, windowH - FOODSIZE), FOODSIZE, FOODSIZE))
if 100>score>50:
MOVESPEED = 9
elif 150>score>100:
MOVESPEED = 8
elif 250>score>150:
MOVESPEED = 6
elif 400>score>250:
MOVESPEED = 5
elif 600>score>400:
MOVESPEED = 3
elif 800>score>600:
MOVESPEED = 2
elif score>800:
MOVESPEED = 1
# move the player
if moveDown and player.bottom < windowH:
player.top += MOVESPEED
if moveUp and player.top > 0:
player.top -= MOVESPEED
if moveLeft and player.left > 0:
player.left -= MOVESPEED
if moveRight and player.right < windowW:
player.right += MOVESPEED
theSurface.blit(bg, (0, 0))
# draw the player onto the surface
pygame.draw.circle(theSurface, playercolor, player.center, size)
# check if the player has intersected with any food squares.
for food in foods[:]:
if player.colliderect(food):
foods.remove(food)
size+=1
score+=1
# draw the food
for i in range(len(foods)):
pygame.draw.rect(theSurface, GREEN, foods[i])
pygame.display.update()
# draw the window onto the theSurface
pygame.display.update()
mainClock.tick(80)
How can I make it such that the whole circle is able to eat the stuff around it?
You set player at the beginning to the circle at its initial size, and then you never update it later. When you redraw the player, you're just drawing a new circle with a new size. You'll need to reassign the newly-drawn circle to the player variable. You may also need to copy some data from the old player to the new player, but I'm not super up on pygame so I'm not sure which (if any) of the various attributes on player (like center and left) are handled by pygame and which you're creating yourself.

Categories