How do I fix diagonal movement? - python

I have been learning pygame from a youtuber called dafluffypotatoe and I have written my own code for player movement I was wondeirng if it would be possible to fix the diagonal movement? Because it goes twice as fast when I go diagonal.
also I am new to stack over flow.
Here is my paste bin for the code I used
import pygame, sys
from pygame.locals import *
# init pygame
pygame.init()
# clock
clock = pygame.time.Clock()
WINDOW_SIZE = 1024, 512
# screen and display
screen = pygame.display.set_mode(WINDOW_SIZE)
display = pygame.Surface((512, 256))
FPS = 60
moving_left = False
moving_right = False
moving_up = False
moving_down = False
player_x_loc = 50
player_y_loc = 50
def load_map(path):
f = open(path + '.txt', 'r')
data = f.read()
f.close()
data = data.split('\n')
game_map = []
for row in data:
game_map.append(list(row))
return game_map
game_map = load_map('map')
# player
player_img = pygame.image.load('player.png')
# blocks
block_basic = pygame.image.load('blocck.png')
# game loop
while True:
# colour screen
display.fill((33, 15, 15))
# load tiles
tile_rects = []
y = 0
for row in game_map:
x = 0
for tile in row:
if tile == '1':
display.blit(block_basic, (x * 32, y * 32))
if tile == '0':
tile_rects.append(pygame.Rect(x * 32, y * 32, 32, 32))
x += 1
y += 1
# basic speed x
if moving_left == True:
player_x_loc -= 4
if moving_right == True:
player_x_loc += 4
else:
player_x_loc == 0
# basic speed y
if moving_up == True:
player_y_loc -= 4
if moving_down == True:
player_y_loc += 4
else:
player_y_loc == 0
display.blit(player_img, (player_x_loc, player_y_loc))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# keydown
if event.type == KEYDOWN:
if event.key == K_a:
moving_left = True
if event.key == K_d:
moving_right = True
if event.key == K_w:
moving_up = True
if event.key == K_s:
moving_down = True
# keyup
if event.type == KEYUP:
if event.key == K_a:
moving_left = False
if event.key == K_d:
moving_right = False
if event.key == K_w:
moving_up = False
if event.key == K_s:
moving_down = False
screen.blit(pygame.transform.scale(display, WINDOW_SIZE), (0, 0))
pygame.display.update()
clock.tick(FPS)

You must move the player with a normalized directional vector and a constant speed. The simplest method is to use pygame.math.Vector2.scale_to_length:
while True:
# [...]
move_vec = pygame.math.Vector2(
moving_right - moving_left,
moving_down - moving_up)
if move_vec.x != 0 or move_vec.y != 0:
move_vec.scale_to_length(4)
player_x_loc += move_vec.x
player_y_loc += move_vec.y
# [...]

Related

Does anyone know how i can get up movement on my sprite in pygame

I know how to get left and right movement but does anyone know how to get up and down in pygame
i am using pygame locals, pygame, sys, glob. Any help would be greatly appreceated, most of the code is based of: https://pythonprogramming.altervista.org/platform-game-in-detail-part-1/?doing_wp_cron=1603309265.4902870655059814453125
from pygame.locals import *
import pygame
import sys
import glob
map1 = """wwwwwwwwwwwwwwwwwwwwwwwwwwwww
w w
w w
w w
w w
w
w d
w p
w
w w
w w
w w
w w
w w
w w
wwwwwwwwwwwwwwwwwwwwwwwwwwwww"""
pygame.display.set_icon(pygame.image.load("C:/Users/cuerv/Downloads/flappy-bird-assets-master/flappy-bird-assets-master/favicon.ico"))
pygame.display.set_caption("Knock Knight")
screen = pygame.display.set_mode((480, 250))
moving_right = False
moving_left = False
moving_up = False
moving_down = False
player_location = [50,50]#remember its a fucking list
#-----------------------------
door = pygame.image.load("C:/Users/cuerv/Downloads/Door.png")
door_rect = door.get_rect(center=(100, 250))
tile = pygame.image.load("C:/Users/cuerv/Downloads/Wall.png")
tile_rect = tile.get_rect(center=(100, 256))
player = pygame.image.load("C:/Users/cuerv/Downloads/Player.png").convert()
player_rect = player.get_rect(center=(100, 256))
def init_display():
global screen, tile, door, player
def tiles(map1):
global tile, door, player
for y, line in enumerate(map1):
#counts lines
for x, c in enumerate(line):
#counts caracters
if c == "w":
#caracter is w
screen.blit(tile, (x * 16.18, y * 15))
if c == "d":
screen.blit(door, (x * 16.2, y * 15))
if c == "p":
screen.blit(player, player_location)
map1 = map1.splitlines()
pygame.init()
init_display()
clock = pygame.time.Clock()
while True:
tiles(map1)
if moving_right == True:
player_location[0] += 4
if moving_left == True:
player_location[0] -= 4
if moving_up == True:
player_location[0] +=8
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == KEYDOWN:
if event.key == K_RIGHT:
moving_right = True
if event.key == K_LEFT:
moving_left = True
if event.key == K_UP:
moving_up = True
if event.key == K_DOWN:
moving_down = True
if event.type == KEYUP:
if event.key == K_RIGHT:
moving_right = False
if event.key == K_LEFT:
moving_left = False
if event.key == K_UP:
moving_up = False
if event.key == K_DOWN:
moving_down = False
pygame.display.update()
clock.tick(60)
The position of the player is defined by 2 coordinates (x, y). For the up and down movement you have to change the 2nd (y) coordinate (e.g. player_location[1] -= 4):
while True:
tiles(map1)
if moving_right == True:
player_location[0] += 4
if moving_left == True:
player_location[0] -= 4
if moving_up == True:
player_location[1] -= 4
if moving_down == True:
player_location[1] += 4

zooming in and out with pygame

I'm attempting to make it so that you can zoom in and zoom out in my pygame project. It is working fine except when I zoom in, the screen seems to be zooming towards the top left and then readjusting itself after (making it so that the player is on the center of the screen). When I zoom out, it simply does the same with the opposite corner, can someone explain me why is it doing so? Here is my code:
import pygame
import random
import sys
from pygame.locals import *
WINDOW_SIZE = (600, 400)
FPS = 60
# Initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(WINDOW_SIZE)
zoom = 2
display = pygame.Surface((int(WINDOW_SIZE[0] / zoom), int(WINDOW_SIZE[1] / zoom)))
pygame.display.set_caption('Game')
clock = pygame.time.Clock()
player_img = pygame.image.load('player.png').convert()
player_img.set_colorkey((255, 255, 255))
player_rect = pygame.Rect(0, 0, 5, 16)
grass_img = pygame.image.load('grass.png').convert()
dirt_img = pygame.image.load('dirt.png').convert()
# 0 = Air
# 1 = Grass
# 2 = Dirt
game_map =[['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','1','1','1','1','1','1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['1','1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1','1','0','0','0','0','0','0','0','0','0'],
['2','2','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1','2','2','0','0','0','1','1','1','1','1','0'],
['2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','2','0','0','0','2','2','2','2','2','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','2','2','2','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','2','2','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','2','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0']]
def collision_test(rect,tiles):
collisions = []
for tile in tiles:
if rect.colliderect(tile):
collisions.append(tile)
return collisions
def move(rect, movement, tiles):
collision_direction = {'up': False, 'down': False, 'right': False, 'left' : False}
rect.x += movement[0]
collisions = collision_test(rect, tiles)
for tile in collisions:
if movement[0] > 0:
rect.right = tile.left
collision_direction['right'] = True
if movement[0] < 0:
rect.left = tile.right
collision_direction['left'] = True
rect.y += round(movement[1])
collisions = collision_test(rect, tiles)
for tile in collisions:
if movement[1] > 0:
rect.bottom = tile.top
collision_direction['down'] = True
if movement[1] < 0:
rect.top = tile.bottom
collision_direction['up'] = True
return rect, collision_direction
mouvement_speed = 2
moving_right = False
moving_left = False
moving_up = False
moving_down = False
ctrl_pressed = False
equals_pressed = False
minus_pressed = False
zero_pressed = False
player_y_momentum = 0
air_timer = 0
scroll = [0, 0]
running = True
# Game loop
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == K_d:
moving_right = True
if event.key == K_LEFT or event.key == K_a:
moving_left = True
if event.key == K_UP or event.key == K_w:
if air_timer < 3:
player_y_momentum = -4
if event.key == K_DOWN or event.key == K_s:
moving_down = True
if event.key == K_RCTRL or event.key == K_LCTRL:
ctrl_pressed = True
if event.key == K_EQUALS:
equals_pressed = True
if event.key == K_MINUS:
minus_pressed = True
if event.key == K_0:
zero_pressed = True
if event.type == KEYUP:
if event.key == K_RIGHT or event.key == K_d:
moving_right = False
if event.key == K_LEFT or event.key == K_a:
moving_left = False
if event.key == K_UP or event.key == K_w:
moving_up = False
if event.key == K_DOWN or event.key == K_s:
moving_down = False
if event.key == K_EQUALS:
equals_pressed = False
if event.key == K_MINUS:
minus_pressed = False
if event.key == K_0:
zero_pressed = False
if event.key == K_RCTRL or event.key == K_LCTRL:
ctrl_pressed = False
if equals_pressed and ctrl_pressed:
zoom += 0.2
print('ZOOMING IN')
if minus_pressed and ctrl_pressed:
zoom -= 0.2
print('ZOOMING OUT')
if zero_pressed and ctrl_pressed:
zoom = 2
print('RESET')
try:
display = pygame.Surface((int(WINDOW_SIZE[0] / zoom), int(WINDOW_SIZE[1] / zoom)))
except:
zoom = 0.4
display.fill((5, 195, 225))
tile_rect = []
y = 0
for layer in game_map:
x = 0
for tile in layer:
if tile == '1':
display.blit(grass_img, (x * 16 - scroll[0], y * 16 - scroll[1]))
if tile == '2':
display.blit(dirt_img, (x * 16 - scroll[0], y * 16 - scroll[1]))
if tile != '0':
tile_rect.append(pygame.Rect(x * 16, y * 16, 16, 16))
x += 1
y += 1
scroll[0] += ((player_rect.x - int(WINDOW_SIZE[0]/ (zoom * 2)) + 2) - scroll[0]) / 12
scroll[1] += ((player_rect.y - int(WINDOW_SIZE[1]/ (zoom * 2)) + 5) - scroll[1]) / 12
player_mouvement = [0, 0]
if moving_right:
player_mouvement[0] += mouvement_speed
if moving_left:
player_mouvement[0] -= mouvement_speed
if moving_down:
player_mouvement[1] += 5
player_y_momentum += 0.2
if player_y_momentum > 5:
player_y_momentum = 5
player_mouvement[1] += player_y_momentum
player_rect, collision_direction = move(player_rect, player_mouvement, tile_rect)
if collision_direction['down']:
air_timer = 0
player_y_momentum = 0
else:
air_timer += 1
if collision_direction['up']:
player_y_momentum = 0
display.blit(player_img, (player_rect.x - scroll[0], player_rect.y - scroll[1]))
#pygame.draw.rect(display,(255, 255, 255),player_rect)
#print(air_timer)
screen.blit(pygame.transform.scale(display,WINDOW_SIZE),(0,0))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
sys.exit()
All that you need to do is lock the scroll towards the player by using
scroll[0] = player_rect.x - int(WINDOW_SIZE[0]/ (zoom * 2)) + 2
scroll[1] = player_rect.y - int(WINDOW_SIZE[1]/ (zoom * 2)) + 5
Your scroll calculation is a bit confusing and I am not quite sure what the calculation is exactly doing (and there are no comments to explain it). Clearly the intent is to scroll it to track the player and so adjust where the game_map gets drawn onto the display and where the player gets drawn onto it. You then scale() that to the screen to get your zoom effect
Though I cannot comment on exactly what the issue is with the scroll I could suggest a different and I believe simpler way to go about this. Draw your display without doing the scroll stuff. Then use subsurface() to grab a section of display centered on your player with the desired size to achieve the zoom effect you want. Then scale that subsurface and blit() it onto screen.
Although above I just said centered on your player for simplicity, you would have to adjust that if the player was too close to the edges of display at the desired zoom level.
This should simplify all the creation of the display and the only effort is in deciding where and how big the subsurface is within display to get the location and zoom factor that you want.

"if cond1 or cond2" statement not running second condition in Python

I am making a game in Python that looks like this so far:
import pygame, sys, time, random, threading
from threading import Timer
from pygame.locals import *
pygame.init()
WINDOWHEIGHT = 720
WINDOWWIDTH = 1280
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Hitman Grandma')
plorp = 'true'
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
green = (0,255,0)
blue = (0,0,255)
cyan = (0,255,255)
windowSurface.fill(white)
pygame.display.update()
mainClock = pygame.time.Clock()
hgleft = False
hgright = False
hgup = False
speed = 4
hgair = True
hgjumpallowed = False
level = 0
def stop() :
hgbox.move_ip(0,0)
return
hgbox = pygame.Rect(0 ,13 ,36 ,72)
hitmangrandma = pygame.image.load('hgrd1copy.jpg')
hg = pygame.transform.scale(hitmangrandma, (36,72))
landbox1 = pygame.Rect(0,400,200,50)
li = pygame.image.load('hgland1.png')
land1 = pygame.transform.scale(li,(200,50))
landbox2 = pygame.Rect(230,400,200,50)
land2 = pygame.transform.scale(li,(200,50))
land = landbox1,landbox2
while True:
windowSurface.fill(white)
windowSurface.blit(land1,landbox1)
windowSurface.blit(land2,landbox2)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == K_a:
hgright = False
hgleft = True
if event.key == K_RIGHT or event.key == K_d:
hgleft = False
hgright = True
if event.key == K_UP or event.key == K_w:
hgair = True
hgup = True
hgupkey = True
if event.type == KEYUP:
if event.key == K_ESCAPE or K_q and pygame.key.get_mods() & pygame.KMOD_CTRL:
pygame.quit()
sys.exit()
exit
if event.key == K_LEFT or K_a:
hgleft = False
if event.key == K_RIGHT or K_d:
hgright = False
if hgup and hgbox.top > 0 and hgupkey == True and hgair == True and hgjumpallowed == True:
hgbox.top -= 100
hgair = True
if hgleft and hgbox.left > 0:
hgbox.left -= speed
if hgright and hgbox.right < WINDOWWIDTH:
hgbox.right += speed
if not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2) and hgair == True:
hgair = False
hgbox.top += speed
hgjumpallowed = False
if hgbox.colliderect(landbox1) or hgbox.colliderect(landbox2):
hgjumpallowed = True
stop()
windowSurface.blit(hg, hgbox)
pygame.display.update()
mainClock.tick(40)
However, when I run my script, hgbox doesn't detect collision with landbox2, and just keeps falling. I think this problem is due to it only running the first part of the if statement, and not checking the other parts. What should I do to make it detect other parts of the if statement?
With an mcve I meant something like this (a minimal but complete example that we can copy, paste and run):
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
def stop() :
hgbox.move_ip(0, 0)
hgbox = pygame.Rect(0 ,13 ,36 ,72)
landbox1 = pygame.Rect(0,400,200,50)
landbox2 = pygame.Rect(230,400,200,50)
hgair = True
hgjumpallowed = False
hgup = False
hgupkey = False
speed = 9
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
hgup = True
hgbox.x += 50
hgbox.y -= 90
if hgup and hgbox.top > 0 and hgupkey == True and hgair == True and hgjumpallowed == True:
hgbox.top -= 100
hgair = True
if not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2) and hgair == True:
hgair = False
hgbox.top += speed
hgjumpallowed = False
if hgbox.colliderect(landbox1) or hgbox.colliderect(landbox2):
hgjumpallowed = True
stop()
screen.fill(pygame.Color('gray12'))
pygame.draw.rect(screen, (120, 70, 70), landbox1)
pygame.draw.rect(screen, (120, 70, 70), landbox2)
pygame.draw.rect(screen, (50, 70, 170), hgbox)
pygame.display.flip()
clock.tick(30)
pygame.quit()
sys.exit()
The problem is caused by this line:
if not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2) and hgair == True:
It's evaluated as
if (not hgbox.colliderect(landbox1)) or (not hgbox.colliderect(landbox2) and hgair == True):
The second part would be always False in the example above. The hgbox always falls unless the first part of the condition is False as well (not hgbox.colliderect(landbox1)), that means it can only stand on the left platform.
Try to change it to:
if not hgbox.colliderect(landbox1) and not hgbox.colliderect(landbox2):
# Move downwards.
Edit: Here's a complete example to show you how I would write the movement and jump code. Use x_speed and y_speed to move the player every frame (also accelerate the y_speed) and in the event loop just set the speeds to the desired values. If the player touches a platform set him to the .top of the platform rect and hgjumpallowed to True.
import pygame, sys
from pygame.locals import *
from pygame.color import THECOLORS
pygame.init()
windowSurface = pygame.display.set_mode((1280, 720), 0, 32)
pygame.display.update()
mainClock = pygame.time.Clock()
hitmangrandma = pygame.Surface((36, 72))
hitmangrandma.fill((250, 160, 50))
hgbox = hitmangrandma.get_rect(topleft=(10, 10))
y_speed = 0
x_speed = 0
hgjumpallowed = False
land_img = pygame.Surface((200, 50))
land_img.fill((50, 100, 250))
land = pygame.Rect(0,400,200,50), pygame.Rect(230,400,200,50)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT: # Quit game by pressing on the "x" button.
done = True
if event.type == KEYDOWN:
if event.key in (K_LEFT, K_a):
# Just set the x_speed and then move
# the rect in the while loop each frame.
x_speed = -4
if event.key in (K_RIGHT, K_d):
x_speed = 4
if (event.key == K_UP or event.key == K_w) and hgjumpallowed:
y_speed = -17
hgjumpallowed = False
if event.type == KEYUP:
if event.key == K_ESCAPE or K_q and pygame.key.get_mods() & pygame.KMOD_CTRL:
done = True
if event.key in (K_LEFT, K_a):
x_speed = 0
if event.key in (K_RIGHT, K_d):
x_speed = 0
y_speed += 1 # Accelerate downwards.
# Move the player.
hgbox.x += x_speed
hgbox.y += y_speed
# Check if player is on ground and can jump.
hgjumpallowed = False
for box in land:
if hgbox.colliderect(box): # If player touches ground.
hgjumpallowed = True
hgbox.bottom = box.top
y_speed = 0
windowSurface.fill(THECOLORS['white'])
for box in land:
windowSurface.blit(land_img, box)
windowSurface.blit(hitmangrandma, hgbox)
pygame.display.update()
mainClock.tick(40)
pygame.quit()
sys.exit()
There also was a mistake in the event loop: event.key == K_RIGHT or K_d is always True, because it's evaluated as (event.key == K_RIGHT) or (K_d) and K_d is a truthy value.
To ensure that Python evaluates the logical operators in the right order, add ().
if (not hgbox.colliderect(landbox1) or not hgbox.colliderect(landbox2)) and hgair == True:
This evaluates to True when there is no collision with either landbox1 or with landbox2, and when hgair == True.

Why wont this blit on my screen?

I know this is going to be (hopefully) an easy fix, but I cannot get the gameover screen to blit on my screen. I have thought through this for the past two hours, and none of my tweaks are working. Any help would be greatly appreciated!
This file contains the main file loop as while as sprite group
updates and general updates/renders for the program
import pygame, sys
import player
import random
import math
from constants import *
from bullet import *
from block import *
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Open")
clock = pygame.time.Clock()
def main():
moveX = 0
moveY = 0
sprite_list = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
block_list = pygame.sprite.Group()
main_player = player.Player()
sprite_list.add(main_player)
main_player.rect.x = 400
main_player.rect.y = 550
for i in range(1,10):
blocks = Block()
blocks.center_x = random.randrange(760)
blocks.center_y = random.randrange(400)
blocks.radius = random.randrange(10,200)
blocks.angle = random.random() * 4 * math.pi
blocks.speed = 0.04
block_list.add(blocks)
sprite_list.add(blocks)
font = pygame.font.Font(None, 36)
game_over = False
score = 0
level = 1
gameLoop = True
while gameLoop:
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_RIGHT:
moveX = 5
if event.key == pygame.K_LEFT:
moveX = -5
if event.key == pygame.K_DOWN:
moveY = 5
if event.key == pygame.K_UP:
moveY = -5
if event.key == pygame.K_SPACE:
bullets = Bullet()
bullets.rect.x = main_player.rect.x + 16
bullets.rect.y = main_player.rect.y + 16
sprite_list.add(bullets)
bullet_list.add(bullets)
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT and moveX >= 0:
moveX = 0
if event.key == pygame.K_LEFT and moveX <= 0:
moveX = 0
if event.key == pygame.K_DOWN and moveY >= 0:
moveY = 0
if event.key == pygame.K_UP and moveY <= 0:
moveY = 0
for bullets in bullet_list:
block_hit_list = pygame.sprite.spritecollide(bullets, block_list, True)
for block in block_hit_list:
score += 1
bullet_list.remove(bullets)
sprite_list.remove(bullets)
if bullets.rect.y < 0:
bullet_list.remove(bullets)
sprite_list.remove(bullets)
if pygame.sprite.spritecollide(main_player, block_list, True):
gameLoop = False
game_over = True
sprite_list.update()
screen.fill(BLACK)
sprite_list.draw(screen)
main_player.rect.x += moveX
main_player.rect.y += moveY
score_text = font.render("Score: "+str(score), True, WHITE)
screen.blit(score_text,[10,10])
level_text = font.render("Level: "+str(level), True, WHITE)
screen.blit(level_text,[115,10])
if game_over == True:
you_lose_text = font.render("YOU SUCK", True, RED)
screen.blit(you_lose_text, [300,300])
pygame.time.wait(1000)
break
clock.tick(60)
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
main()
HERE IS MY ISSUE:
if game_over == True:
you_lose_text = font.render("YOU SUCK", True, RED)
screen.blit(you_lose_text, [300,300])
pygame.time.wait(1000)
break
I am getting no error, and the pygame.time.wait function is working correctly? Why is it just skipping over displaying the text?
Maybe it is not the best solution but your code doesn't need better.
blit draws in buffer. You have to use update before wait to send data from buffer to screen.
if game_over == True:
you_lose_text = font.render("YOU SUCK", True, RED)
screen.blit(you_lose_text, [300,300])
pygame.display.update() # send on screen
pygame.time.wait(1000)
break
clock.tick(60)
pygame.display.update()
pygame.quit()

Pygame: Bigger the cell, slower the speed

I am currently making a dumbed down version of this game.
In the game, the bigger your cell, the slower you should be.
This should be proportionate. In my code however, you can see I just set a bunch of ranges to make the cell go at certain speeds. Is there a way to implement the proportionate speed/size instead of set ranges?
Here is my code.
import pygame, sys, random
from pygame.locals import *
# set up pygame
pygame.init()
mainClock = pygame.time.Clock()
# set up the window
windowwidth = 800
windowheight = 600
thesurface = pygame.display.set_mode((windowwidth, windowheight), 0, 32)
pygame.display.set_caption('')
#bg = pygame.image.load("bg.png")
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 cell and food data structure
foodCounter = 0
NEWFOOD = 35
FOODSIZE = 10
cell = pygame.draw.circle(thesurface, playercolor, (60, 250), 40)
foods = []
for i in range(20):
foods.append(pygame.Rect(random.randint(0, windowwidth - FOODSIZE), random.randint(0, windowheight - FOODSIZE), FOODSIZE, FOODSIZE))
# set up movement variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
MOVESPEED = 10
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'):
cell.top = random.randint(0, windowheight - cell.windowheight)
cell.left = random.randint(0, windowwidth - cell.windowwidth)
# split the cell
if event.key == K_SPACE:
pygame.draw.circle(thesurface, playercolor,(cell.centerx,cell.centery),int(size/2))
pygame.draw.circle(thesurface, playercolor,(cell.centerx+size,cell.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, windowwidth - FOODSIZE), random.randint(0, windowheight - FOODSIZE), FOODSIZE, FOODSIZE))
# The bigger the cell, the slower it should go.
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 cell
if moveDown and cell.bottom < windowheight:
cell.top += MOVESPEED
if moveUp and cell.top > 0:
cell.top -= MOVESPEED
if moveLeft and cell.left > 0:
cell.left -= MOVESPEED
if moveRight and cell.right < windowwidth:
cell.right += MOVESPEED
# display background
thesurface.blit(bg, (0, 0))
# draw the cell onto the surface
cell = pygame.draw.circle(thesurface, playercolor, cell.center, size)
# check if the cell has intersected with any food squares.
for food in foods[:]:
if cell.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])
# show the score
printscore = basicFont.render("Score: %d" % score, True, (0,0,0))
thesurface.blit(printscore, (10, 550))
# draw the window onto the thesurface
pygame.display.update()
mainClock.tick(80)
Help is appreciated!
How about a range of values for scores and use divmod to calculate an appropriate index into this lsit?
Example:
>>> speeds = range(50, 800, 50)
>>> MOVESPEED, _ = divmod(130, 50)
>>> MOVESPEED
2
>>> MOVESPEED, remainder = divmod(150, 50)
>>> MOVESPEED
3

Categories