Я на 99% закончил программирование моей самой первой игры. Я очень доволен тем, как это работает, есть только одна вещь, которую я хочу изменить, но я не знаю, как ...
Это мой код:
"""Program based on
https://www.youtube.com/watch?v=-8n91btt5d8&list=PLNAPMEWWbHeegjsyN7_pSwXbYPrbyiYhh&index=2&t=1849s"""
import pygame
import sys
import time
import random
pygame.init()
width = 1400
height = 800
green = (0, 51, 0)
black = (0, 0, 0)
yellow = (255, 255, 0)
white = (255, 255, 255)
player_location = [width - 1350, height - 200]
player_size = [100, 200]
obsticle_size = [101, 101]
obsticle_location = [width - 100, height - 100]
obsticle_list = [obsticle_location]
screen = pygame.display.set_mode((width, height))
speed = 10
score = 0
clock = pygame.time.Clock()
FPS = 60
myFont = pygame.font.SysFont("monospace", 35)
run = True
def set_speed(score, speed): #speed up game as score gets higher
if score < 5:
speed = 10
elif score < 10:
speed = 15
elif score < 20:
speed = 20
elif score < 35:
speed = 25
elif score < 50:
speed = 30
elif score < 75:
speed = 35
elif score < 100:
speed = 40
else:
speed = 50
return speed
def spawn_obsticle(obsticle_list): #spawn obsticle on floor, max 3 on screen
delay = random.random()
if len(obsticle_list) < 3 and delay < 0.0085:
x_pos = width - 100
y_pos = height - 100
obsticle_list.append([x_pos, y_pos])
def spawn_obsticle_2(obsticle_list): #spawn obsticle in air, max 3 on screen
delay = random.random()
if len(obsticle_list) < 3 and delay < 0.0085:
x_pos = width - 100
y_pos = height - 300
obsticle_list.append([x_pos, y_pos])
def draw_obsticle(obsticle_list): #create obsticle
for obsticle_location in obsticle_list:
pygame.draw.rect(screen, white, (obsticle_location[0], obsticle_location[1], obsticle_size[0], obsticle_size[1]))
def update_obsticle_positions(obsticle_list, score): #making obsticles move from right to left
for idx, obsticle_location in enumerate(obsticle_list):
if obsticle_location[0] >= 0 and obsticle_location[0] < width:
obsticle_location[0] -= speed
else:
obsticle_list.pop(idx) #drop obsticles off screen, score +1 everytime this happenes
score += 1
return score
def collision_check(obsticle_list, player_location): #detect collision between player and obsticle, part 1
for obsticle_location in obsticle_list:
if detect_collision(obsticle_location, player_location):
return True
return False
def detect_collision(player_location, obsticle_location): #detect collision between player and obsticle, part 2
p_x = player_location[0]
p_y = player_location[1]
p_width = player_size[0]
p_height = player_size[1]
o_x = obsticle_location[0]
o_y = obsticle_location[1]
o_width = obsticle_size[0]
o_height = obsticle_size[1]
if (o_x >= p_x and o_x < (p_x + p_width)) or (p_x >= o_x and p_x < (o_x + o_width)):
if (o_y >= p_y and o_y < (p_y + p_height)) or (p_y >= o_y and p_y < (o_y + o_height)):
return True
return False
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
sys.exit
if event.type == pygame.KEYDOWN:
x = player_location[0] #x location of player
y = player_location[1] #y location of player
p_width = player_size[0] #starting player width
p_height = player_size[1] #starting player height
if event.key == pygame.K_UP: #jump up by changing y location
y -= 200
player_location = [x,y]
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE or event.key == pygame.K_UP: #back to starting size and location when releasing key
player_size = [100, 200]
player_location = [50, 600]
keys = pygame.key.get_pressed() #stooping by switching width and heigt of player
if keys[pygame.K_SPACE]:
p_width = player_size[1]
p_height = player_size[0]
y = 700
player_size = [p_width,p_height]
player_location = [x,y]
screen.fill(black)
spawn_obsticle(obsticle_list)
spawn_obsticle_2(obsticle_list)
score = update_obsticle_positions(obsticle_list, score)
speed = set_speed(score, speed)
text = "Score:" + str(score) #making score appear on screen
label = myFont.render(text, 1, yellow)
screen.blit(label, (600, 250))
if collision_check(obsticle_list, player_location): #ending game when there is contact between player and obsticle
run = False
draw_obsticle(obsticle_list)
pygame.draw.rect(screen, green, (player_location[0], player_location[1], player_size[0], player_size[1]))
pygame.display.update()
Игра очень проста: вы зеленый блок и вам нужно избегать белых блоков. За каждый блок, который вы избегаете, вы получаете очко. Чем выше ваш счет, тем быстрее движутся препятствия.
Моя проблема в том, что иногда летающий блок и блок на полу появляются (почти) точно друг над другом, делая невозможным уклонение. (может не случиться в первый раз, когда вы запустите его, но если вы запустите его несколько раз, вы обязательно столкнетесь с ним)
Как я могу сделать так, чтобы они ВСЕГДА появлялись на некотором расстоянии друг от друга?
Я просто не могу понять это, и это закончило бы sh мою первую игру. Заранее благодарен (извините за плохого английского sh в некоторых местах. Английский sh не мой родной язык)