zooming in and out with pygame - python

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.

Related

How do I fix diagonal movement?

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
# [...]

Growing function in pygame - SnakeGame [duplicate]

This question already has an answer here:
How do I get the snake to grow and chain the movement of the snake's body?
(1 answer)
Closed 1 year ago.
Hi guys I started learning pygames, i started playing snake and came to an obstacle. I don't know how to make a function for my snake to grow when it eats an apple, I've looked at a lot of snake codes and I'm still not sure how to do it. I dont have idea how to do that, I realy hope you can give mi some advice to improve my game.
your help would do me good, thanks
import pygame
import random
import math
# Init
pygame.init()
# Screen
screen = pygame.display.set_mode((800, 600))
# Caption and Icon
pygame.display.set_caption("Snake Game")
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
# Background
background = pygame.image.load('background.jpg')
# Snake
snakeImg = pygame.image.load('snake.png')
snakeX = 300
snakeY = 300
snakeX_change = 0
snakeY_change = 0
# Apple
appleImg = pygame.image.load('apple.png')
appleX = random.randint(32, 768)
appleY = random.randint(32, 568)
def snake(x, y):
screen.blit(snakeImg, (x, y))
def apple(x, y):
screen.blit(appleImg, (x, y))
# Collision
def isCollision(appleX, appleY, snaketX, snakeY):
distance = distance = math.sqrt(math.pow(appleX - snakeX, 2) + (math.pow(appleY - snakeY, 2)))
if distance < 27:
return True
else:
return False
# Game Loop
score = 0
running = True
while running:
# Background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Snake Movment
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
snakeX_change = -0.1
snakeY_change = 0
if event.key == pygame.K_UP:
snakeY_change = -0.1
snakeX_change = 0
if event.key == pygame.K_RIGHT:
snakeX_change = 0.1
snakeY_change = 0
if event.key == pygame.K_DOWN:
snakeY_change = 0.1
snakeX_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
snakeX_change = -0.1
if event.key == pygame.K_RIGHT:
snakeX_change = 0.1
if event.key == pygame.K_DOWN:
snakeY_change = 0.1
if event.key == pygame.K_UP:
snakeY_change = -0.1
snakeX += snakeX_change
snakeY += snakeY_change
if snakeX <= 0:
snakeX = 0
elif snakeX >= 770:
snakeX = 770
if snakeY <= 0:
snakeY = 0
elif snakeY >= 570:
snakeY = 570
# Collision
collision = isCollision(appleX, appleY, snakeX, snakeY)
if collision:
score += 1
print(score)
appleX = random.randint(32, 768)
appleY = random.randint(32, 568)
snake(snakeX, snakeY)
apple(appleX, appleY)
pygame.display.flip()
When snake's head collide with the apple, add 1 element inside snake's body, you can interprete snake's body as a list of elements, containing tuples perhaps.

I do not know how to end game when specific block is touched in pygame

I want to make it so when my character touches the "v" block the game quits. What I tried was to find all blocks that are "v" and put them in the list. If player colliderect with any in list of "v" game will quit.
I think this should work although it does not seem to be working. Whenever I run it when I touch the "v" block nothing happens.
Here is my code
import pygame
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
WINDOW_SIZE = (600, 400)
pygame.display.set_caption("Game")
screen = pygame.display.set_mode(WINDOW_SIZE, 0, 32)
display = pygame.Surface((300, 200))
player_image = pygame.image.load("Jacques clone-1.png (1).png").convert()
player_image.set_colorkey((255,255,255))
location = [50, 50]
#boolean for movement
moving_right = False
moving_left = False
scroll = [0, 0]
Stay_right = True
game_map1 = """
-----------------------------------------------------
-----------------------------------------------------
-----------------------------------------------------
-----------------------------------------------------
-----------------------------------------------------
xx----------x----------------------------------------
----------vvvv---------------------xxx----------------
---------xooo----------------------------------------
xxxxxxxxxooooxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooo
""".splitlines()
game_map = [list(lst) for lst in game_map1]
tl = {}
tl["v"] = spike_img = pygame.image.load('dirt.png')
tl["o"] = dirt_img = pygame.image.load('grass.png')
tl["x"] = grass_img = pygame.image.load('grass.png')
player_rect = pygame.Rect(50, 50, 25, 25)
momentum = 0
air_timer = 0
#adding tiles list that are hit for movement
def collision_test(rect, tiles):
hit_list = []
for tile in tiles:
if rect.colliderect(tile):
hit_list.append(tile)
#print(hit_list)
return hit_list
def move(rect, movement, tiles):
collision_types = {'top': False, 'bottom': False, 'right': False, 'left': False}
rect.x += movement[0]
hit_list = collision_test(rect, tiles)
for tile in hit_list:
if movement[0] > 0:
rect.right = tile.left
collision_types['right'] = True
elif movement[0] < 0:
rect.left = tile.right
collision_types['left'] = True
rect.y += movement[1]
hit_list = collision_test(rect, tiles)
for tile in hit_list:
if movement[1] > 0:
rect.bottom = tile.top
collision_types['bottom'] = True
elif movement[1] < 0:
rect.top = tile.bottom
collision_types['top'] = True
return rect, collision_types
run = True
while run:
display.fill((146, 244, 255))
scroll[0] += (player_rect.x - scroll[0] - 130)
tile_rects = []
y = 0
for line_of_symbols in game_map:
x = 0
for symbol in line_of_symbols:
if symbol in tl:
display.blit(tl[symbol], (x * 16 - scroll[0], y * 16 - scroll[1]))
if symbol != "-":
tile_rects.append(pygame.Rect(x * 16, y * 16, 16, 16))
x += 1
y += 1
list_ofspike = []
y2 = 0
for lineofsymbols in game_map:
x2 = 0
for symbols in lineofsymbols:
if symbols == "v":
list_ofspike.append(pygame.Rect(x2 * 16, y2 * 16, 16, 16))
x2 += 1
y2 += 1
for spike in list_ofspike:
if player_rect.colliderect(spike):
pygame.quit()
player_movement = [0, 0]
if moving_right:
player_movement[0] += 2
if moving_left:
player_movement[0] -= 2
player_movement[1] += momentum
momentum += 0.3
if momentum > 3:
momentum = 3
player_rect, collisions = move(player_rect, player_movement, tile_rects)
if collisions['bottom']:
air_timer = 0
momentum = 0
else:
air_timer += 1
if Stay_right:
display.blit(player_image, (player_rect.x - scroll[0], player_rect.y - scroll[1]))
else:
display.blit(pygame.transform.flip(player_image, 1, 0 ),(player_rect.x - scroll[0], player_rect.y - scroll[1]))
for event in pygame.event.get():
if event.type == QUIT:
run = False
if event.type == KEYDOWN:
if event.key == K_RIGHT:
moving_right = True
Stay_right = True
if event.key == K_LEFT:
moving_left = True
Stay_right = False
if event.key == K_SPACE:
if air_timer < 6:
momentum = -5
if event.type == KEYUP:
if event.key == K_RIGHT:
moving_right = False
if event.key == K_LEFT:
moving_left = False
screen.blit(pygame.transform.scale(display, (WINDOW_SIZE)), (0, 0))
pygame.display.update()
clock.tick(60)
pygame.quit()
You do not detect a collision with the spikes, because your collision detection works too perfectly.
When you move the player then you ensure, that the player does not intersect any object, thus the player does not intersect a spike, too.
You have to test if the player touches a spike. Increase the player rectangle by 1 in direction and use the increased rectangle to do the collision test with the spikes:
while run:
# [...]
test_rect = pygame.Rect(player_rect.left-1, player_rect.top-1,
player_rect.width+2, player_rect.height+2)
for spike in list_ofspike:
if test_rect.colliderect(spike):
pygame.quit()
# [...]

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.

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