Python

Игра на Python

 import pygame 
import random
import os

pygame.init()

BACKGROUND_COLOR = (255, 255, 255)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Нажми на стрелку")

images = [
pygame.image.load(os.path.join("textures", "arrow_up.png")),
pygame.image.load(os.path.join("textures", "arrow_down.png")),
pygame.image.load(os.path.join("textures", "arrow_left.png")),
pygame.image.load(os.path.join("textures", "arrow_right.png"))
]
def get_random_image():
return random.choice(images)
def display_image(image):
screen.fill(BACKGROUND_COLOR)
screen.blit(image, (SCREEN_WIDTH / 2 - image.get_width() / 2, SCREEN_HEIGHT / 2 - image.get_height() / 2))
pygame.display.flip()
def main():
running = True
image = get_random_image()
display_image(image)

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if images.index(image) == 3:
if event.key == pygame.K_RIGHT:
image = get_random_image()
display_image(image)
else: running = False
if images.index(image) == 2:
if event.key == pygame.K_LEFT:
image = get_random_image()
display_image(image)
else: running = False
if images.index(image) == 1:
if event.key == pygame.K_DOWN:
image = get_random_image()
display_image(image)
else: running = False
if images.index(image) == 0:
if event.key == pygame.K_UP:
image = get_random_image()
display_image(image)
else: running = False
if __name__ == '__main__':
main()
Здраствуйте, хотел сделать что бы при нажатии на неправильную кнопку игра завершалась, но она и так и так заканчивается. Совсем недавно начал извуть этот язык програмрования, не понимаю почему это не работает
Levani Odisharia
Levani Odisharia
96
Ошибка в коде заключается в том, что некоторые строки, начинающиеся с if, else, elif, должны иметь одинаковый отступ. В коде это правило нарушается, что приводит к ошибке IndentationError. Для исправления необходимо выровнять все строки с одинаковым уровнем вложенности.

Вот исправленный код с правильным выравниванием:

python
Copy code
import pygame
import random
import os

pygame.init()

BACKGROUND_COLOR = (255, 255, 255)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Нажми на стрелку")

images = [
pygame.image.load(os.path.join("textures", "arrow_up.png")),
pygame.image.load(os.path.join("textures", "arrow_down.png")),
pygame.image.load(os.path.join("textures", "arrow_left.png")),
pygame.image.load(os.path.join("textures", "arrow_right.png"))
]

def get_random_image():
return random.choice(images)

def display_image(image):
screen.fill(BACKGROUND_COLOR)
screen.blit(image, (SCREEN_WIDTH / 2 - image.get_width() / 2, SCREEN_HEIGHT / 2 - image.get_height() / 2))
pygame.display.flip()

def main():
running = True
image = get_random_image()
display_image(image)

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if images.index(image) == 3:
if event.key == pygame.K_RIGHT:
image = get_random_image()
display_image(image)
else:
running = False
elif images.index(image) == 2:
if event.key == pygame.K_LEFT:
image = get_random_image()
display_image(image)
else:
running = False
elif images.index(image) == 1:
if event.key == pygame.K_DOWN:
image = get_random_image()
display_image(image)
else:
running = False
elif images.index(image) == 0:
if event.key == pygame.K_UP:
image = get_random_image()
display_image(image)
else:
running = False

if __name__ == '__main__':
main()
Андре Занд
Андре Занд
343
Лучший ответ
Андрей Прокойченко а сам взяли вставил код без отступов, гениально)
Levani Odisharia Тут нету отступов, но сам смысл понятен
Для того, чтобы при нажатии на неправильную кнопку игра завершалась, нужно добавить соответствующий код в блоки else после каждого условия, которое проверяет правильность нажатой кнопки.

Например, вместо

vbnet
Copy code
if images.index(image) == 3:
if event.key == pygame.K_RIGHT:
image = get_random_image()
display_image(image)
else:
running = False
нужно написать

scss
Copy code
if images.index(image) == 3:
if event.key == pygame.K_RIGHT:
image = get_random_image()
display_image(image)
else:
running = False
pygame.quit()
sys.exit()
Мишаня Vmv
Мишаня Vmv
50 230