python-3.x 为什么我的代码在有机会执行之前就退出了?[副本]

5ktev3wc  于 2023-06-07  发布在  Python
关注(0)|答案(1)|浏览(198)

此问题已在此处有答案

Why is my code exiting as soon as I start it?(1个答案)
8小时前关闭
我的pygame代码总是在完成我想要的任务之前退出

import pygame
import os
import random

# Initialize pygame starts 
pygame.init()

# Set the dimensions of the screen
screen_width = 1275
screen_height = 750

# Set the colors
white = (255, 255, 255)
black = (0, 0, 0)

# Set the font
font = pygame.font.SysFont('Arial', 20)

# Set the button properties
button_radius = 70
button_x_spacing = 400
button_y_spacing = 200

# Set the flower image
flower_image = pygame.image.load(os.path.join(os.path.expanduser("~"), "Documents", "flower.jpg"))
flower_rect = flower_image.get_rect()
flower_rect.center = (screen_width//2, screen_height//2)

# Set the button positions
button_positions = [
    (button_x_spacing, button_y_spacing),
    (button_x_spacing, button_y_spacing + 200),
    (button_x_spacing, button_y_spacing + 400)
]

# Initialize the screen
screen = pygame.display.set_mode((screen_width, screen_height))

# Set the caption
pygame.display.set_caption("Marmoset Buttons")

# Set the clock
clock = pygame.time.Clock()

# Set the loop variable
running = True

# Set the timer
timer = 0

# Generating sequence of numbers
sequence = [0,1,2,1,2,0,2,1,0,2]

for i in sequence:
    # Check for events
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            distance_button = pygame.math.Vector2(button_positions[i]) - pygame.math.Vector2(pygame.mouse.get_pos())
            flower_image = pygame.image.load(os.path.join(os.path.expanduser("~"), "Documents", f"flower{i}.jpg"))
            if distance_button.length() < button_radius:
                timer = pygame.time.get_ticks()

    screen.fill(black)
    pygame.draw.circle(screen, white, button_positions[i], button_radius)
    text_surface = font.render(f"Button {i}", True, black)
    text_rect = text_surface.get_rect(center=button_positions[i])
    screen.blit(text_surface, text_rect)
   
    # Check the timer
    if timer != 0:
        current_time = pygame.time.get_ticks()
        if current_time - timer < 3000:
            screen.blit(flower_image, flower_rect)
        else:
            timer = 0

    pygame.display.update()

# Quit pygame
pygame.quit()

我尝试修复缩进错误,但没有帮助。我希望它显示一个预定义的按钮位置(0,1,2)从序列写出来。我想一个按钮显示,然后被点击,然后在该序列中的下一个按钮显示。这将继续,直到序列完成。

flmtquvp

flmtquvp1#

它会按照需要提前退出,因为您只是在for循环中运行程序,该循环通过sequence。您可以尝试在while True循环中运行程序,然后在while True循环中运行for循环。

相关问题