Restarting a snake game after game over screen appears in pygame - python

in the game that I have found on github there is a game over screen that shows your score, now I want to make the game restart if you press space so that you don't need to close the program and open it again to play it again. The problem isn't how to make the game restart when you press space but to actually make it restart. Here is the code:
import pygame
import random
import sys
import time
# Difficulty settings
# Easy -> 10
# Medium -> 25
# Hard -> 40
# Harder -> 60
# Impossible-> 120
difficulty = 25
# Window size
frame_size_x = 720
frame_size_y = 480
# Checks for errors encountered
check_errors = pygame.init()
# pygame.init() example output -> (6, 0)
# second number in tuple gives number of errors
if check_errors[1] > 0:
print(f'[!] Had {check_errors[1]} errors when initialising game, exiting...')
sys.exit(-1)
else:
print('[+] Game successfully initialised')
# Initialise game window
pygame.display.set_caption('Snake Eater')
game_window = pygame.display.set_mode((frame_size_x, frame_size_y))
# Colors (R, G, B)
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# FPS (frames per second) controller
fps_controller = pygame.time.Clock()
# Game variables
snake_pos = [100, 50]
snake_body = [[100, 50], [100 - 10, 50], [100 - (2 * 10), 50]]
food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# Game Over
def game_over():
my_font = pygame.font.SysFont('times new roman', 90)
game_over_surface = my_font.render('YOU DIED', True, red)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (frame_size_x / 2, frame_size_y / 4)
game_window.fill(black)
game_window.blit(game_over_surface, game_over_rect)
show_score(0, red, 'times', 20)
pygame.display.update()
time.sleep(3)
pygame.quit()
sys.exit()
# Score
def show_score(choice, color, font, size):
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Score : ' + str(score), True, color)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.midtop = (frame_size_x - 100, 15)
else:
score_rect.midtop = (frame_size_x / 2, frame_size_y / 1.25)
game_window.blit(score_surface, score_rect)
# pygame.display.flip()
# Main logic
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
# W -> Up; S -> Down; A -> Left; D -> Right
if event.key == pygame.K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.key == pygame.K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == pygame.K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
# Esc -> Create event to quit the game
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Making sure the snake cannot move in the opposite direction instantaneously
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'
# Moving the snake
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop()
# Spawning food on the screen
if not food_spawn:
food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
food_spawn = True
# GFX
game_window.fill(black)
for pos in snake_body:
# Snake body
# .draw.rect(play_surface, color, xy-coordinate)
# xy-coordinate -> .Rect(x, y, size_x, size_y)
pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))
# Snake food
pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# Game Over conditions
# Getting out of bounds
if snake_pos[0] < 0 or snake_pos[0] > frame_size_x - 10:
game_over()
if snake_pos[1] < 0 or snake_pos[1] > frame_size_y - 10:
game_over()
# Touching the snake body
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
game_over()
show_score(1, white, 'consolas', 20)
# Refresh game screen
pygame.display.update()
# Refresh rate
fps_controller.tick(difficulty)

Implement a function that initializes all the global game states:
def init_game():
global snake_pos, snake_body
global food_pos, food_spawn
global direction, change_to, score
# Game variables
snake_pos = [100, 50]
snake_body = [[100, 50], [100 - 10, 50], [100 - (2 * 10), 50]]
food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
Invoke the function when SPACE is pressed:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
# [...]
if event.key == pygame.K_SPACE:
init_game()

Related

How do I flip this sprite in pygame?

EDIT: I've now flipped the sprite, but when the animation plays on the flipped sprite, it has a black background instead of blending in with the major background. Just updated my code to the current situation. (2/8/2021)
I'm trying to flip a sprite in pygame, for example, I don't want them running left but looking right, which is what is happening right now.
The part that is giving me issues is the second comment that says ISSUES.
Here is my code (spritesheet is a class that transforms the image into a surface):
import pygame
import os
import sys
import random
from pygame.locals import *
import spritesheet
import time
pygame.init()
clock = pygame.time.Clock()
FPS = 60
prev_time = time.time()
pygame.display.set_caption('Platformer')
BG_COLOR = (50, 50, 50)
BLACK = (0, 0, 0)
WIN_SIZE = [1920,1080]
WIN = pygame.display.set_mode((WIN_SIZE[0], WIN_SIZE[1]), 0, 32)
# CONFIGURING Animations
IDLE_INDEX = 0
RUN_INDEX = 0
moving_right = False
moving_left = False
lookingRight = True
speed = 4
animation_tick = 8
player_location = [50, 50]
player_y_momentum = 0
player_rect = pygame.Rect(player_location[0] + 155, player_location[1] + 140, 70, 133)
def retrieve_list(animType, image):
if animType == "idle":
IDLE_FRAMES = []
IDLE_STEPS = 9
sprite_sheet = spritesheet.SpriteSheet(image)
for step in range(IDLE_STEPS):
newFRAME = sprite_sheet.get_image(step, 120, 80, 3.5, BLACK)
IDLE_FRAMES.append(newFRAME)
return IDLE_FRAMES
if animType == "run":
RUN_FRAMES = []
RUN_STEPS = 9
sprite_sheet = spritesheet.SpriteSheet(image)
for step in range(RUN_STEPS):
newFRAME = sprite_sheet.get_image(step, 120, 80, 3.5, BLACK)
RUN_FRAMES.append(newFRAME)
return RUN_FRAMES
sprite_sheet_img_IDLE = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Idle.png')
sprite_sheet_img_RUN = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Run.png')
IDLE_FRAMES = retrieve_list("idle", sprite_sheet_img_IDLE)
RUN_FRAMES = retrieve_list("run", sprite_sheet_img_RUN)
currentANIMATION = "idle"
playingAnim = None
while True:
clock.tick(FPS)
now = time.time()
dt = now - prev_time
prev_time = now
WIN.fill(BG_COLOR)
if currentANIMATION == "idle":
if player_location[1] > WIN_SIZE[1] - IDLE_FRAMES[IDLE_INDEX].get_height():
player_y_momentum = -player_y_momentum
else:
player_y_momentum += 0.2
player_location[1] += player_y_momentum
elif currentANIMATION == "run":
if player_location[1] > WIN_SIZE[1] - RUN_FRAMES[RUN_INDEX].get_height():
player_y_momentum = -player_y_momentum
else:
player_y_momentum += 0.2
player_location[1] += player_y_momentum
if moving_right:
currentANIMATION = "run"
if not lookingRight:
lookingRight = True
WIN.fill(BG_COLOR)
playingAnim = WIN.blit(RUN_FRAMES[RUN_INDEX], (player_location[0], player_location[1]))
player_location[0] += speed
if moving_left:
currentANIMATION = "run"
if lookingRight:
lookingRight = False
leftFrame = pygame.transform.flip(RUN_FRAMES[RUN_INDEX], True, False)
WIN.fill(BG_COLOR)
playingAnim = WIN.blit(leftFrame, (player_location[0], player_location[1]))
player_location[0] -= speed
elif moving_right != True and moving_left != True:
currentANIMATION = "idle"
WIN.fill(BG_COLOR)
playingAnim = WIN.blit(IDLE_FRAMES[IDLE_INDEX], (player_location[0], player_location[1]))
player_rect.x = player_location[0] + 155
player_rect.y = player_location[1] + 140
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
moving_right = True
if event.key == K_LEFT or event.key == ord('a'):
moving_left = True
if event.type == KEYUP:
if event.key == K_RIGHT or event.key == ord('d'):
moving_right = False
if event.key == K_LEFT or event.key == ord('a'):
moving_left = False
pygame.display.update()
if animation_tick == 8: # change 20 to how ever many ticks in between animation frames
if currentANIMATION == "idle":
if IDLE_INDEX < 8:
IDLE_INDEX += 1
else:
IDLE_INDEX = 0
if currentANIMATION == "run":
if RUN_INDEX < 8:
RUN_INDEX += 1
else:
RUN_INDEX = 0
animation_tick = 0 # reset tick back to 0 after changing frame
else:
animation_tick += 1 # add 1 each iteration of the while loop
Here are the spritesheets if you want to replicate my situation:
running spritesheet:
idle spritesheet:
I've tried flipping the original surface, but then the image gets messed up with black around it, and it doesn't play the animation.
pygame.transform.flip does not flip the image in place, but returns a new image that is flipped:
flipped_image = pygame.transform.flip(image, True, False)
Forgot to add .convert_alpha() when I was flipping the image. Apparently when the image is flipped it recreates the black rectangle.

Pygame Snake - Apple spawning inside snake

i'm learning how to make a snake game in pygame from the thenewboston tutorials on youtube and make it my own.
There's a problem in the game where the 'apple' spawns behind the snake's position which is something that i don't want.
I'm sure i have to state that apple position can't be the same as the snake but can't figure it out how:
# Snake eating the apple
if snake_x_pos == apple_x and snake_y_pos == apple_y:
pygame.mixer.Sound.play(eat_apple_sound)
snakelength += 1
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
Full code:
import pygame
import random
pygame.init()
# Game Title
pygame.display.set_caption("Original Snake")
# Game display 4:3
screen_w = 640
screen_h = 480
surface = pygame.display.set_mode((screen_w, screen_h))
bg_color = (170, 204, 102)
box_color = (43, 51, 26)
box_size = screen_h / 24
# PLAYING FIELD
field_x = screen_w - (box_size*2)
field_y = screen_h - (box_size*2)
# Frames per Second
clock = pygame.time.Clock()
FPS = 8
# Font settings
kongtext = "C:\Windows\Fonts\kongtext.ttf"
verysmall = pygame.font.Font(kongtext, 12)
small = pygame.font.Font(kongtext, 15)
medium = pygame.font.Font(kongtext, 30)
large = pygame.font.Font(kongtext, 60)
verylarge = pygame.font.Font(kongtext, 80)
# sound settings
game_over_sound = pygame.mixer.Sound("sounds/game_over.wav")
eat_apple_sound = pygame.mixer.Sound("sounds/eat_apple.wav")
def snake(box_size, snakelist):
for XnY in snakelist:
pygame.draw.rect(surface, box_color, [XnY[0], XnY[1], box_size, box_size])
# Text Object
def text_objects(text, color, size):
if size == "small":
text_surface = small.render(text, True, color)
elif size == "verysmall":
text_surface = verysmall.render(text, True, color)
elif size == "medium":
text_surface = medium.render(text, True, color)
elif size == "large":
text_surface = large.render(text, True, color)
elif size == "verylarge":
text_surface = large.render(text, True, color)
return text_surface, text_surface.get_rect()
# Start screen
def start_screen():
intro = True
while intro:
# IF USER CLICKS ON THE X
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Start Game
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
intro = False
surface.fill(bg_color)
# SCREEN FIELD WITH BORDER 3
pygame.draw.rect(surface, box_color, [16, 16, screen_w-33, screen_h-33-box_size], 3)
# START SCREEN
message_to_screen("SNAKE", box_color, -25, size="verylarge")
message_to_screen("PRESS SPACE TO PLAY", box_color, 35, size="verysmall")
pygame.display.update()
clock.tick(15)
# Message to screen
def message_to_screen(msg, color, text_y_pos=0, size="small"):
text_surf, text_rect = text_objects(msg, color, size)
text_rect.center = (screen_w / 2), (screen_h / 2)+text_y_pos
surface.blit(text_surf, text_rect)
def score(score):
text = small.render("Score: "+str((score*10)-20), True, box_color)
surface.blit(text, [box_size, screen_h-box_size-7])
def game_loop():
direction = "right"
quit_game = False
game_over = False
# Box settings
box_color = (43, 51, 26)
# Defining snake position
snakelist = []
snakelength = 3
snake_x_pos = screen_w / 2
snake_y_pos= screen_h / 2
snake_x_chg = box_size
snake_y_chg = 0
# Randomizing the apple position
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
while not quit_game:
# Game Over
while game_over:
surface.fill(bg_color)
message_to_screen("GAME OVER", box_color, -10, size="large")
message_to_screen("PRESS SPACE TO PLAY AGAIN OR Q TO QUIT", box_color, 50, size="small")
# PLAYING FIELD
pygame.draw.rect(surface, box_color,
[16, 16, screen_w - 33, screen_h - 33 - box_size], 3)
# SCORE
score(snakelength - 1)
pygame.display.update()
# Closing Game Over screen with X
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit_game = True
game_over = False
# Closing Game Over screen with Q or Restart with space
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
quit_game = True
game_over = False
if event.key == pygame.K_SPACE:
direction = "right"
game_loop()
for event in pygame.event.get():
# Closing the game
if event.type == pygame.QUIT:
quit_game = True
game_over = False
# Controlling the snake
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_LEFT) and direction != "right":
snake_x_chg = -box_size
snake_y_chg = 0
direction = "left"
elif (event.key == pygame.K_RIGHT) and direction != "left":
snake_x_chg = box_size
snake_y_chg = 0
direction = "right"
elif (event.key == pygame.K_UP) and direction != "down":
snake_y_chg = -box_size
snake_x_chg = 0
direction = "up"
elif (event.key == pygame.K_DOWN) and direction != "up":
snake_y_chg = box_size
snake_x_chg = 0
direction = "down"
# Screen boundaries
if snake_x_pos > (field_x) or snake_x_pos < box_size or snake_y_pos > (field_y) or snake_y_pos < box_size:
pygame.mixer.Sound.play(game_over_sound)
game_over = True
# Snake new position
snake_x_pos += snake_x_chg
snake_y_pos += snake_y_chg
# Clear screen
surface.fill(bg_color)
# Draw and update
pygame.draw.rect(surface, box_color, [apple_x, apple_y, box_size, box_size])
snakehead = []
snakehead.append(snake_x_pos)
snakehead.append(snake_y_pos)
snakelist.append(snakehead)
if len(snakelist) > snakelength:
del snakelist[0]
for snaketail in snakelist[:-1]:
if snaketail == snakehead:
pygame.mixer.Sound.play(game_over_sound)
game_over = True
snake(box_size, snakelist)
# PLAYING FIELD
pygame.draw.rect(surface, box_color, [16, 16, screen_w-33, screen_h-33-box_size], 3)
# SCORE
score(snakelength-1)
pygame.display.update()
# Snake eating the apple
if snake_x_pos == apple_x and snake_y_pos == apple_y:
pygame.mixer.Sound.play(eat_apple_sound)
snakelength += 1
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
clock.tick(FPS)
pygame.quit()
quit()
start_screen()
game_loop()
Create a rectangle at the new random "apple" position:
apple_rect = pygame.Rect(apple_x, apple_y, box_size, box_size)
Check for each position (pos) in snakelist if the "apple" rectangle collides with the part of the snake by pygame.Rect.collidepoint:
apple_rect.collidepoint(*pos)
Use any() to check if the apple "collides" with any part of the snake:
any(apple_rect.collidepoint(*pos) for pos in snakelist)
If the apple "collides" with the snake the create a new random point and repeat the process:
# Snake eating the apple
if snake_x_pos == apple_x and snake_y_pos == apple_y:
pygame.mixer.Sound.play(eat_apple_sound)
snakelength += 1
while True:
apple_x, apple_y = (random.randrange(box_size, fs, box_size) for fs in (field_x, field_y))
apple_rect = pygame.Rect(apple_x, apple_y, box_size, box_size)
if not any(apple_rect.collidepoint(*pos) for pos in snakelist):
break
The snake seems to be a list of "boxes", held in the list snakelist. So to ensure the apple does not appear inside the parts of the snake, the generated random point needs to be created outside the snake's boxes.
A simple (but inefficient) way to do this is to keep generating random points, and testing them for collision.
collision = True
while collision == True:
# Randomizing the apple position
apple_x = random.randrange(box_size, field_x, box_size)
apple_y = random.randrange(box_size, field_y, box_size)
# Check apple not within snake
collision = False
for XnY in snakelist:
part = pygame.Rect( XnY[0], XnY[1], box_size, box_size )
# is the apple-point within the snake part?
if part.collidepoint( apple_x, apple_y ) == True:
collision = True
break # any collision is final, stop checking
It would be worth thinking of a more efficient way to move the point away from the snake instead of looping over-and-over. Picking a random point may simply pick the same point, or a near-by bad point again. Also the longer the snake gets, the worse this looping will be as there are less "non-snake" points on the screen. I guess there's some known safe-spots, like the space the snake just moved out of, but these are obviously not random.

pygame snake game, snake doesn't move when rapidly changing direction

I just wrote a snake game using pygame module.
After testing, I found that when I rapidly change the snake direction. E.g. pressing two arrow keys very fast to move snake body to next line or change to opposite direction, the snake doesn't respond accurately. Most of the time it will work, but there are few times snake doesn't move. I believe this is because of the low FPS, but if I increase it, the snake will move so fast.
Here is the code:
# snake game
import pygame, sys, random, time
# game initialization
check_errors = pygame.init()
if check_errors[1] > 0:
print('(!) Got {0} errors during initializing pygame \
exiting...'.format(check_errors[1]))
sys.exit(-1)
else:
print('(+) pygame successfully initialized.')
# game screen
screen_width = 750
screen_height = 495
game_screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Snake game')
# colors
red = pygame.Color(255, 0, 0) # game over
green = pygame.Color(0, 255, 0) # snake body
black = pygame.Color(0, 0, 0) # player score
white = pygame.Color(255, 255, 255) # game background
brown = pygame.Color(165, 42, 42) # food
# FPS controller
fps_controller = pygame.time.Clock()
# game variables
start_x = 300
start_y = 150
step = 15 # block width is 10
initial_body_length = 3
snake_head = [start_x, start_y] # snake start position [x, y]
# initialize snake body, index 0 contains the snake head
snake_body = [[start_x - i * step, start_y] for i in range(initial_body_length)]
score = 0
level = 1
food_pos = [random.randrange(2, screen_width / step - 1) * step, \
random.randrange(2, screen_height / step - 1) * step] # don't put food at the border of the screen
food_spawn = True
direction = 'RIGHT'
next_direction = direction # new direction after user hits keyboard
def draw_game_menu():
count = 3
my_font = pygame.font.SysFont('monaco', 60)
while True:
game_screen.fill(white)
start_surface = my_font.render('Start in {0} seconds.'.format(count), True, black)
start_rect = start_surface.get_rect()
start_rect.midtop = (screen_width / 2, 80)
game_screen.blit(start_surface, start_rect)
esc_surface = my_font.render('''Press Esc to exit during game.''', True, black)
esc_rect = esc_surface.get_rect()
esc_rect.midtop = (screen_width / 2, 150)
game_screen.blit(esc_surface, esc_rect)
pause_surface = my_font.render('''Press Space to pause the game.''', True, black)
pause_rect = pause_surface.get_rect()
pause_rect.midtop = (screen_width / 2, 220)
game_screen.blit(pause_surface, pause_rect)
pygame.display.flip() # update the game screen
time.sleep(1)
fps_controller.tick()
count -= 1
if count == 0: break
def draw_game_pause():
my_font = pygame.font.SysFont('monaco', 40)
while True:
pause_surface = my_font.render('Press Space to continue.', True, black)
pause_rect = pause_surface.get_rect()
pause_rect.midtop = (screen_width / 2, 150)
game_screen.blit(pause_surface, pause_rect)
pygame.display.flip()
fps_controller.tick()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: return
def show_score(game_over=False):
my_font = pygame.font.SysFont('monaco', 40)
score_surface = my_font.render('Score: {0}'.format(score), True, black)
score_rect = score_surface.get_rect()
if game_over == False:
score_rect.midtop = (75, 10)
else:
score_rect.midtop = (screen_width / 2, 130)
game_screen.blit(score_surface, score_rect)
# game over function
def draw_game_over():
my_font = pygame.font.SysFont('monaco', 60)
GO_surface = my_font.render('Game Over !', True, red)
GO_rect = GO_surface.get_rect()
GO_rect.midtop = (screen_width/2, 60)
game_screen.blit(GO_surface, GO_rect)
show_score(game_over=True)
pygame.display.flip() # update the game screen
time.sleep(4)
pygame.quit() # quit the game
sys.exit() # exit the console
def get_food(food_pos, snake_body):
for block in snake_body:
if block[0] == food_pos[0] and block[1] == food_pos[1]:
return True
return False
# game start menu
draw_game_menu()
# main logic of the game
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN: # if user press any button
if event.key == pygame.K_RIGHT or event.key == ord('d'):
next_direction = 'RIGHT'
elif event.key == pygame.K_LEFT or event.key == ord('a'):
next_direction = 'LEFT'
elif event.key == pygame.K_UP or event.key == ord('w'):
next_direction = 'UP'
elif event.key == pygame.K_DOWN or event.key == ord('s'):
next_direction = 'DOWN'
elif event.key == pygame.K_ESCAPE: # if user choose to quit the game
pygame.event.post(pygame.event.Event(pygame.QUIT))
elif event.key == pygame.K_SPACE:
draw_game_pause()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# validation of direction
if next_direction == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
elif next_direction == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif next_direction == 'DOWN' and direction != 'UP':
direction = 'DOWN'
elif next_direction == 'UP' and direction != 'DOWN':
direction = 'UP'
# move snake head
if direction == 'RIGHT':
snake_head[0] += step
elif direction == 'LEFT':
snake_head[0] -= step
elif direction == 'DOWN':
snake_head[1] += step
elif direction == 'UP':
snake_head[1] -= step
# move snake body mechanism
# 1. insert a new block at the beginning of the body
# 2. check if snake has reached a food
# 2.1 if yes, then keep the modified body
# 2.2 if not, then delete the end of the body
snake_body.insert(0, list(snake_head))
if snake_head[0] == food_pos[0] and snake_head[1] == food_pos[1]:
food_spawn = False
score += 1
else:
snake_body.pop()
while food_spawn == False:
food_pos = [random.randrange(2, screen_width / step - 1) * step,
random.randrange(2, screen_height / step - 1) * step]
if get_food(food_pos, snake_body) == True:
food_spawn = False
else:
food_spawn = True
# fill game background
game_screen.fill(white)
# draw snake body
for pos in snake_body:
pygame.draw.rect(game_screen, green, pygame.Rect(pos[0], pos[1], step, step))
# draw food
pygame.draw.rect(game_screen, brown, pygame.Rect(food_pos[0], food_pos[1], step, step))
# check if snake hits the border
if (snake_head[0] > screen_width - step) or (snake_head[0] < 0) or \
(snake_head[1] > screen_height - step) or (snake_head[1] < 0):
draw_game_over()
# check if snake hits itself
for block in snake_body[1:]:
if snake_head[0] == block[0] and snake_head[1] == block[1]:
draw_game_over()
level = score//5 + 1
if level > 3:
level = 3
show_score(game_over=False)
pygame.display.flip()
if level == 1:
fps_controller.tick(8)
elif level == 2:
fps_controller.tick(10)
elif level == 3:
fps_controller.tick(12)
Please help to see if there is a way to improve, thanks.
First of all, you should try to use a single main loop.
While you're rendering the start or end screen, you can't interact with the window because no event loop runs. It's very annoying that you can't move or close the window during that time. Maybe take a look here for an example of how to handle this.
Second, really use a higher framerate, and don't tie the speed of your game objects to the frame rate.
There are several ways to handle this, an example is to use an event that signals when the snake should move. Here's an example I wrote for another question.
Here's a simple implementation for your current code:
MOVE_SNAKE = pygame.USEREVENT
pygame.time.set_timer(MOVE_SNAKE, 300)
# main logic of the game
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN: # if user press any button
if event.key == pygame.K_RIGHT or event.key == ord('d'):
next_direction = 'RIGHT'
elif event.key == pygame.K_LEFT or event.key == ord('a'):
next_direction = 'LEFT'
elif event.key == pygame.K_UP or event.key == ord('w'):
next_direction = 'UP'
elif event.key == pygame.K_DOWN or event.key == ord('s'):
next_direction = 'DOWN'
elif event.key == pygame.K_ESCAPE: # if user choose to quit the game
pygame.event.post(pygame.event.Event(pygame.QUIT))
elif event.key == pygame.K_SPACE:
draw_game_pause()
elif event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == MOVE_SNAKE:
# move snake head
if direction == 'RIGHT':
snake_head[0] += step
elif direction == 'LEFT':
snake_head[0] -= step
elif direction == 'DOWN':
snake_head[1] += step
elif direction == 'UP':
snake_head[1] -= step
# move snake body mechanism
# 1. insert a new block at the beginning of the body
# 2. check if snake has reached a food
# 2.1 if yes, then keep the modified body
# 2.2 if not, then delete the end of the body
snake_body.insert(0, list(snake_head))
if snake_head[0] == food_pos[0] and snake_head[1] == food_pos[1]:
food_spawn = False
score += 1
else:
snake_body.pop()
# validation of direction
if next_direction == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
elif next_direction == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif next_direction == 'DOWN' and direction != 'UP':
direction = 'DOWN'
elif next_direction == 'UP' and direction != 'DOWN':
direction = 'UP'
while food_spawn == False:
food_pos = [random.randrange(2, screen_width / step - 1) * step,
random.randrange(2, screen_height / step - 1) * step]
if get_food(food_pos, snake_body) == True:
food_spawn = False
else:
food_spawn = True
# fill game background
game_screen.fill(white)
# draw snake body
for pos in snake_body:
pygame.draw.rect(game_screen, green, pygame.Rect(pos[0], pos[1], step, step))
# draw food
pygame.draw.rect(game_screen, brown, pygame.Rect(food_pos[0], food_pos[1], step, step))
# check if snake hits the border
if (snake_head[0] > screen_width - step) or (snake_head[0] < 0) or \
(snake_head[1] > screen_height - step) or (snake_head[1] < 0):
draw_game_over()
# check if snake hits itself
for block in snake_body[1:]:
if snake_head[0] == block[0] and snake_head[1] == block[1]:
draw_game_over()
new_level = score//5 + 1
if new_level != level:
pygame.time.set_timer(MOVE_SNAKE, 300 / new_level)
if new_level <= 3:
level = new_level
show_score(game_over=False)
pygame.display.flip()
fps_controller.tick(60)
See how easy it is now to control the speed of the snake: it moves now every 300ms.

adding boulders to pygame snake in python

i have a snake game i made in python and i want to add him boulders that will appear every 10 "apples" he gets, so can you help me please? this is the code right now
import pygame
import random
__author__ = 'Kfir_Kahanov'
init = pygame.init()
def quit_game():
"""
this function will quit the game
:return:
"""
pygame.quit()
quit()
# this will set a nice sound when the player gets an apple
BLOP = pygame.mixer.Sound("Blop.wav")
pygame.mixer.Sound.set_volume(BLOP, 1.0)
volume = pygame.mixer.Sound.get_volume(BLOP)
# making colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 155, 0)
BLUE = (0, 0, 255)
YELLOW = (217, 217, 0)
SNAKE_RED = (152, 2, 2)
def display_fill():
"""
this will fill the screen with a color of my choice
:return:
"""
game_display.fill(GREEN)
def mute():
"""
this will mute the game or unmute it
:return:
"""
if volume == 1.0:
pygame.mixer.Sound.set_volume(BLOP, 0.0)
else:
pygame.mixer.Sound.set_volume(BLOP, 10.0)
# all the pygame stuff for the display
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600
game_display = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption("The hungry Cobra")
ICON = pygame.image.load("apple_icon.png")
pygame.display.set_icon(ICON)
pygame.display.update()
# deciding on FPS, the size of the snake, apples, and making the fonts for the text
CLOCK = pygame.time.Clock()
BLOCK_SIZE = 20
APPLE_THICKNESS = 30
fps = 15
# BOULDER_THICKNESS = 30
direction = "right" # deciding the starting direction
tiny_font = pygame.font.SysFont("comicsansms", 10)
small_font = pygame.font.SysFont("comicsansms", 25)
med_font = pygame.font.SysFont("comicsansms", 50)
large_font = pygame.font.SysFont("comicsansms", 80)
def text_objects(text, color, size):
"""
defining the text
:param text:
:param color:
:param size:
:return:
"""
global text_surface
if size == "tiny":
text_surface = tiny_font.render(text, True, color)
if size == "small":
text_surface = small_font.render(text, True, color)
if size == "medium":
text_surface = med_font.render(text, True, color)
if size == "large":
text_surface = large_font.render(text, True, color)
return text_surface, text_surface.get_rect()
# loading apple and snake img
IMG = pygame.image.load("snake_head.png")
APPLE_IMG = pygame.image.load("apple_icon.png")
# BOULDER_IMG = pygame.image.load("boulder.png")
def rand_apple_gen():
"""
making apple function
:return:
"""
rand_apple_x = round(random.randrange(10, DISPLAY_WIDTH - APPLE_THICKNESS)) # / 10.0 * 10.0
rand_apple_y = round(random.randrange(10, DISPLAY_HEIGHT - APPLE_THICKNESS)) # / 10.0 * 10.0
return rand_apple_x, rand_apple_y
"""
def rand_boulder_gen():
making the boulder parameters
:return:
rand_boulder_x = round(random.randrange(10, DISPLAY_WIDTH - BOULDER_THICKNESS))
rand_boulder_y = round(random.randrange(10, DISPLAY_WIDTH - BOULDER_THICKNESS))
return rand_boulder_x, rand_boulder_y
"""
def message(msg, color, y_displace=0, size="small"):
"""
making a function for the making of the text
:param msg:
:param color:
:param y_displace:
:param size:
:return:
"""
text_surf, text_rect = text_objects(msg, color, size)
text_rect.center = ((DISPLAY_WIDTH / 2), (DISPLAY_HEIGHT / 2) + y_displace)
game_display.blit(text_surf, text_rect)
def intro_message():
"""
making the intro
:return:
"""
intro = True
while intro:
display_fill()
message("Welcome to ", BLACK, -200, "large")
message("The hungry Cobra!", BLACK, -100, "large")
message("Eat apples to grow, but be care full", BLACK)
message("if you run into yourself or outside the screen", BLACK, 30)
message("you gonna have a bad time", BLACK, 60)
message("Press S to start or E to exit", BLACK, 90)
message("Created by Kfir Kahanov", BLACK, 200, "tiny")
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
display_fill()
pygame.display.update()
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_s:
intro = False
if event.key == pygame.K_e:
display_fill()
pygame.display.update()
quit_game()
score_edit = 0
def score_f(score):
"""
making a score_f on the top left
:param score:
:return:
"""
text = small_font.render("Score:" + str(score + score_edit), True, YELLOW)
game_display.blit(text, [0, 0])
def pause_f():
"""
making a pause_f screen
:return:
"""
pause = True
if pause:
message("Paused", RED, -50, "large")
message("Press R to start over, E to exit or C to continue", BLACK)
pygame.display.update()
while pause:
for event in pygame.event.get():
if event.type == pygame.QUIT:
display_fill()
pygame.display.update()
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_c or pygame.K_ESCAPE or pygame.K_p:
pause = False
if event.key == pygame.K_r:
global score_edit, direction, cheat1, cheat4, cheat3, cheat2
direction = "right"
score_edit = 0
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16
game_loop()
if event.key == pygame.K_e:
display_fill()
pygame.display.update()
quit_game()
CLOCK.tick(5)
# making cheats
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16
def snake(snake_list):
"""
defining the snake head
:param snake_list:
:return:
"""
global head
if direction == "right":
head = pygame.transform.rotate(IMG, 270)
elif direction == "left":
head = pygame.transform.rotate(IMG, 90)
elif direction == "down":
head = pygame.transform.rotate(IMG, 180)
elif direction == "up":
head = IMG
game_display.blit(head, (snake_list[-1][0], snake_list[-1][1]))
for x_n_y in snake_list[:-1]:
pygame.draw.rect(game_display, SNAKE_RED, [x_n_y[0], x_n_y[1], BLOCK_SIZE, BLOCK_SIZE])
def game_loop():
"""
this will be the game itself
:return:
"""
global cheat1
global cheat2
global cheat3
global cheat4
global direction
global fps
game_exit = False
game_over = False
global score_edit
lead_x = DISPLAY_WIDTH / 2
lead_y = DISPLAY_HEIGHT / 2
# rand_boulder_x, rand_boulder_y = -50, -50
lead_x_change = 10
lead_y_change = 0
snake_list = []
snake_length = 1
rand_apple_x, rand_apple_y = rand_apple_gen()
while not game_exit:
if game_over:
message("Game over!", RED, -50, "large")
message("Press E to exit or R to retry.", BLACK, 20, "medium")
pygame.display.update()
while game_over:
fps = 15
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
game_over = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_e:
game_exit = True
game_over = False
if event.key == pygame.K_r:
direction = "right"
score_edit = 0
cheat1 = 16
cheat2 = 16
cheat3 = 16
cheat4 = 16
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
mute()
if event.key == pygame.K_LEFT and lead_x_change is not BLOCK_SIZE and direction is not "right":
lead_x_change = -BLOCK_SIZE
lead_y_change = 0
direction = "left"
elif event.key == pygame.K_RIGHT and lead_x_change is not -BLOCK_SIZE and direction is not "left":
lead_x_change = BLOCK_SIZE
lead_y_change = 0
direction = "right"
elif event.key == pygame.K_UP and lead_y_change is not BLOCK_SIZE and direction is not "down":
lead_y_change = -BLOCK_SIZE
lead_x_change = 0
direction = "up"
elif event.key == pygame.K_DOWN and lead_y_change is not -BLOCK_SIZE and direction is not "up":
lead_y_change = BLOCK_SIZE
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_p:
pause_f()
elif event.key == pygame.K_ESCAPE:
pause_f()
elif event.key == pygame.K_k: # the cheat
cheat1 = 0
elif event.key == pygame.K_f:
cheat2 = 4
elif event.key == pygame.K_i:
cheat3 = 0
elif event.key == pygame.K_r:
cheat4 = 3
elif cheat1 == 0 and cheat2 == 4 and cheat3 == 0 and cheat4 == 3:
score_edit = 10000
if lead_x >= DISPLAY_WIDTH or lead_x < 0 or lead_y >= DISPLAY_HEIGHT or lead_y < 0:
game_over = True
lead_x += lead_x_change
lead_y += lead_y_change
display_fill()
game_display.blit(APPLE_IMG, (rand_apple_x, rand_apple_y))
snake_head = [lead_x, lead_y]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for eachSegment in snake_list[:-1]:
if eachSegment == snake_head:
game_over = True
snake(snake_list)
score_f(snake_length * 10 - 10)
pygame.display.update()
if rand_apple_x < lead_x < rand_apple_x + APPLE_THICKNESS or rand_apple_x < lead_x + BLOCK_SIZE < rand_apple_x \
+ APPLE_THICKNESS:
if rand_apple_y < lead_y < rand_apple_y + APPLE_THICKNESS or rand_apple_y < lead_y + BLOCK_SIZE < \
rand_apple_y + APPLE_THICKNESS:
pygame.mixer.Sound.play(BLOP)
rand_apple_x, rand_apple_y = rand_apple_gen()
snake_length += 1
fps += 0.15
"""
if snake_length * 10 - 10 == 20:
rand_boulder_x, rand_boulder_y = rand_boulder_gen()
game_display.blit(BOULDER_IMG, (rand_boulder_x, rand_boulder_y))
elif rand_boulder_x < lead_x < rand_boulder_y + BOULDER_THICKNESS or rand_boulder_x < lead_x + BLOCK_SIZE < \
rand_boulder_x + BOULDER_THICKNESS:
if rand_boulder_x < lead_y < rand_boulder_y + BOULDER_THICKNESS or rand_boulder_y < lead_y + BLOCK_SIZE < \
rand_boulder_y + BOULDER_THICKNESS:
game_over = True
"""
CLOCK.tick(fps)
display_fill()
pygame.display.update()
quit_game()
intro_message()
game_loop()
Maybe try explaining what you have tried and why it isn't working. You would get better help that way.
From what I can see from your code though....
You seem to be on the right track in your commented out code. Evaluating the snake length or score variable during your game loop, then generating a random boulder to the screen. The next step is just handling the collision logic for all the boulders, which I see two ways of doing. First way is creating a lists of the boulder attributes like the x,y positions, similar to how you did the snake list. The second way would be to create a class for boulders, then when the score, or snake length, reaches 10, create a new boulder object. Using a class may make the collision logic much easier to handle.

Pygame Arrow Control

I am wondering why is it that when I execute the file,
the arrow control and movement of the left rectangle will not continuously move up or down, even though I am holding down on the arrow keys for a long time.
import pygame
black = ( 0, 0, 0)
white = ( 255, 255, 255)
green = ( 0, 255, 0)
red = ( 255, 0, 0)
pygame.init()
size = [700,500]
screen = pygame.display.set_mode(size)
fonto = pygame.font.SysFont("algerian", 100)
font = pygame.font.SysFont("algerian", 12)
text = fonto.render("Game Over", True, (0, 128, 10))
pygame.display.set_caption("Vasanths First Legit Game")
done = False
pygame.mouse.set_visible(0)
clock = pygame.time.Clock()
score = 1
rect_x = 50
rect_y = 50
rect_xp = 10
rect_yp = 10
rect_change_x = 10
rect_change_y = 10
rect_change_xp = 10
rect_change_yp = 3
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
rect_yp = rect_change_yp+rect_yp
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
rect_yp = 0+rect_yp
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
rect_yp=-3+rect_yp
if event.key == pygame.K_RIGHT:
rect_yp=3+rect_yp
if event.key == pygame.K_UP:
rect_yp=-3+rect_yp
if event.key == pygame.K_DOWN:
rect_yp=3+rect_yp
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
rect_yp=0+rect_yp
if event.key == pygame.K_RIGHT:
rect_yp=0+rect_yp
if event.key == pygame.K_UP:
rect_yp=0+rect_yp
if event.key == pygame.K_DOWN:
rect_yp=0+rect_yp
pos = pygame.mouse.get_pos()
x = pos[0]
y = pos[1]
screen.fill(black)
pygame.draw.rect(screen,white,[rect_x,rect_y,10,10])
pygame.draw.rect(screen,green,[x,490,50,10])
pygame.draw.rect(screen,green,[10,rect_yp,10,50])
# Move the rectangle starting point
rect_x += rect_change_x
rect_y += rect_change_y
if rect_y == 0:
rect_change_x=rect_change_x*1
rect_change_y=rect_change_y*-1
if rect_y == 490:
if rect_x < x + 50 :
scoref = font.render(score, True, (0, 128, 0))
screen.blit(scoref,
(20 - scoref.get_width() // 10, 20 - scoref.get_height() // 10))
rect_change_x=rect_change_x*1
rect_change_y=rect_change_y*-1
if rect_x < x:
rect_change_y = 0
rect_change_x = 0
#dont do this , it will go bizzonkes
score = str(score)
score = int(score)
if rect_y == 490:
if rect_x < x + 50 :
if rect_change_x !=0:
if rect_change_y !=0:
score=int(score)
score = score + 1
score=str(score)
if rect_change_x == 0:
if rect_change_y == 0:
screen.blit(text,
(320 - text.get_width() // 2, 240 - text.get_height() // 2))
if rect_x == 700:
rect_change_x = rect_change_x*-1
rect_change_y = rect_change_y*1
if rect_x == 0:
rect_change_x = rect_change_x*0
rect_change_y = rect_change_y*0
if rect_y == 500:
rect_change_y = 0
rect_change_x = 0
screen.blit(text,
(320 - text.get_width() // 2, 240 - text.get_height() // 2))
score=str(score)
print(score)
score = str(score)
scoref = font.render(score, True, (0, 128, 0))
screen.blit(scoref,
(20 - scoref.get_width() // 10, 20 - scoref.get_height() // 10))
clock.tick(30)
pygame.display.flip()
pygame.quit ()
In pygame the input is handled in a event loop. There is a event queue, the system sends input from the keyboard, and by calling pygame.event.get() you get the first event in the queue. There are many types of events, the most popular being KEYUP and KEYDOWN.
The mistake that most beginner people make, is that they believe that when a button is pressed, a KEYDOWN event is sent the whole time. That is not needed, since if you press a button, it is pressed until you release it. So you need to have certain flags to see if a button is pressed.
The most popular way of doing this is by using a d = v*t equation. Since the speed is constant, we need to introduce a direction. So our equation would look like this:
distance_changed = direction * speed * time_change
In your event loop, you then change the direction:
1 if KEYDOWN-RIGHT
-1 if KEYDOWN-LEFT
0 if KEYUP-LEFTorRIGHT.
Now the question might pop up, why use time_change? Since, we cannot predict on which machines the program will work, the amount of times the loop will repeat will not be known.
If you take an old machine, the game will work much slower. So we measure the time taken from the last movement, so that it will not changed on different machines.
I have see that you use pygame.tick(30), which waits so that the time it took for the loop to finish was constant. The problem arises, when you run this at an older machine. The loop cannot speed up.
As a suggestion, you should divide you game into functions. It's much more readable, and you can use you code in different places. Also, your event loop, has to many ifs. Use elif since there is no point to check if RIGTH key was pressed if LEFT was already pressed.
This is how I handle it in one of my own Pygame projects:
class Inputs:
def __init__(self):
self.bindings = {"up": pygame.K_UP,
"down": pygame.K_DOWN,
"left": pygame.K_LEFT,
"right": pygame.K_RIGHT,
"lp": pygame.K_a,
"mp": pygame.K_s,
"hp": pygame.K_d,
"lk": pygame.K_z,
"mk": pygame.K_x,
"hk": pygame.K_c,
"pause": pygame.K_RETURN}
self.inputState = {"up": False,
"down": False,
"right": False,
"left": False,
"lp": False,
"mp": False,
"hp": False,
"lk": False,
"mk": False,
"hk": False,
"pause": False}
self.buffer = InputBuffer()
def lookupBinding(self, keyEntered):
for binding, keyBound in self.bindings.items():
if keyEntered == keyBound:
return binding
return "not found"
def getInputState(self, events):
for event in events:
if event.type == pygame.KEYDOWN:
binding = self.lookupBinding(event.key)
if binding != "not found":
newInput = Input()
newInput.inputName = binding
newInput.timeSinceInput = 0
self.buffer.push(newInput)
self.inputState[binding] = True
if event.type == pygame.KEYUP:
binding = self.lookupBinding(event.key)
if binding != "not found":
self.inputState[binding] = False
return self.inputState
I keep two dictionaries, one of in-game "commands", such as directions, to the pygame key, then another of those commands to a boolean representing the command's on/off state. By watching for KEYDOWN and KEYUP events, I can determine which mapped inputs are on and which are off.
EDIT: A benefit of this way method that I should mention is that it makes it very easy to change the key mapping later on, or even allow custom key-mappings. Your game logic only needs to rely on the basic inputs, such as a jump or move input, and won't need to change if the key-mappings change.
I would use pygame.key.get_pressed(), but you are also forgetting pygame.key.set_repeat(). The first argument is the # of milliseconds it takes to start repeating, and the second is the interval at which the key repeats.
This is an example which uses both:
x = 400
y = 300
import pygame, sys
bkg = (255, 211, 0)
clr = (0, 0, 0)
squ = (8, 11, 134)
pygame.init()
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bloxy")
pygame.key.set_repeat(1, 1)
font = pygame.font.SysFont("Stencil", 20)
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT]:
x -= 5
if keys_pressed[pygame.K_RIGHT]:
x += 5
if keys_pressed[pygame.K_UP]:
y -= 5
if keys_pressed[pygame.K_DOWN]:
y += 5
if x > 800:
x = 0
if x < 0:
x = 800
if y > 600:
y = 0
if y < 0:
y = 600
screen.fill(bkg)
text = font.render('(' + str(x) + ',' + str(y) + ')', True, clr)
screen.blit(text, [10, 10])
pygame.draw.rect(screen, squ, [x - 10, y - 10, 20, 20])
pygame.display.flip()
clock.tick(60)

Categories

Resources