作为一个新的Python(或任何语言)程序员,我的程序循环有问题。

2024-04-25 03:53:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想给我儿子写一个乘法游戏。当它运行时,它将显示一个索引卡,其中两个随机数相乘。你知道吗

当你点击卡片时,它会在索引卡片的“背面”显示答案。你知道吗

import pygame, sys, random

pygame.init()

black = (0,0,0)

# screen
(width, height) = (480, 320)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Math Flashcards")

#background color
background_color = ((black))
screen.fill(background_color)
print(background_color)

#Index Card Position (Center)
card_front = pygame.image.load('img/indexcard.png')
card_back = pygame.image.load('img/indexcard.png')
card_w = card_front.get_width()
card_h = card_front.get_height()
card_pos = (((width - card_w) / 2), (height - card_h) / 2)
print('Width =',card_w, "Height =",card_h)
print('Card Position' ,card_pos)

#Create Random Numbers 0-9
num_1 = str(random.randint(0, 9))
num_2 = str(random.randint(0, 9))
print('num_1 =',num_1)
print('num_2 =',num_2)

# calculate the answer and render font
ans = int(num_1)*int(num_2)
print('the answer is ',ans)

#Create font
blue = (0,0,255)
font_size = 75
myfont = pygame.font.SysFont("Courier", font_size)

# apply it to text on a label
l1 = myfont.render(num_1, 1, blue)
lX = myfont.render("x", 1, blue)
l2 = myfont.render(num_2, 1, blue)
lans = myfont.render(str(ans), 1, blue)

# put the label object on the screen at position
l1_pos = (((width/2)-(font_size *1)),(height/2)-(font_size/2))
print(l1_pos)
lX_pos = (((width/2)-(font_size *.38)),(height/2)-(font_size/2))
print(lX_pos)
l2_pos = (((width/2)-(font_size *-.20)),(height/2)-(font_size/2))
print(l2_pos)
lans_pos =(((width/2)-(font_size/2)),(height/2)-(font_size/2))
print(lans_pos)

screen.blit(card_front, card_pos)
screen.blit(l1, (l1_pos))
screen.blit(lX, (lX_pos))
screen.blit(l2, (l2_pos))

running = True
while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        elif event.type == pygame.MOUSEBUTTONDOWN:
            screen.blit(card_back, card_pos)
            screen.blit(lans, (lans_pos))
            pygame.display.flip()

        elif event.type == pygame.MOUSEBUTTONDOWN:
            running = False

    pygame.display.update()

只运行一次。我想它重置为一个新的乘法问题,当我点击索引卡第二次。这就是我需要帮助的地方。你知道吗

我这周刚开始用Python编程。我很惊讶我能走这么远。非常感谢您的帮助。谢谢!你知道吗


Tags: posl1sizebluerendercardwidthscreen
1条回答
网友
1楼 · 发布于 2024-04-25 03:53:04

正如爱德华L.在评论中指出的那样,你的第二个elif永远不会执行。每当程序到达第一个elif并且其计算结果为True时,它将运行该elif并跳过第二个elif。尝试以下操作:

for event in pygame.event.get():
    count = 0
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()

    elif event.type == pygame.MOUSEBUTTONDOWN and count == 0:
        screen.blit(card_back, card_pos)
        screen.blit(lans, (lans_pos))
        pygame.display.flip()
        count = 1

    elif event.type == pygame.MOUSEBUTTONDOWN and count == 1:
        running = False

相关问题 更多 >