我在创建游戏时遇到问题。想法:“创建一个游戏,让僵尸接近你,你需要在僵尸接近你之前解决一些数学问题”。 问题数为 5,当僵尸手经过 x=200(即“岩石”手的坐标)时,游戏结束。
我尝试了不同的方法来应用循环,使僵尸接近岩石,同时用户同时回答问题。当用户回答了 5 个问题或僵尸到达你身边时,数学问题会被收回,它会告诉你是赢了还是输了。
感谢您的帮助
# Function to check if the input is a natural number
def isNaturalNumber(input_str):
try:
number = int(input_str)
return number > 0
except ValueError:
return False
# Function to generate and check users' answer
def generate_question():
num1 = random.randint(1, 9)
num2 = random.randint(1, 9)
correct_answer = num1 + num2
# Display math problem
problem_text = Text(Point(400, 250), f"What is {num1} + {num2}?")
problem_text.setSize(20)
problem_text.draw(w)
# Get user's answer
entry_box = Entry(Point(400, 300), 5)
entry_box.setSize(20)
entry_box.draw(w)
while True:
key = w.checkKey()
if key == "Return":
break
# Checking answer
answer = entry_box.getText()
if isNaturalNumber(answer):
if int(answer) == correct_answer:
global zombie_health
zombie_health -= 1 # Decrease the zombie's health
zombie_health_text.setText(str(zombie_health)) # Update the health display
# Clear the math problem and user's answer
problem_text.undraw()
entry_box.undraw()
TheRock_parts = [TheRock_body, TheRock_head, TheRock_eye1, TheRock_eye2, TheRock_gun, TheRock_gun1, TheRock_hand2, TheRock_hand1, TheRock_leg1, TheRock_leg2]
zombie_parts = [zombie_body, zombie_head, zombie_eye1, zombie_eye2, zombie_hand1, zombie_hand2, zombie_leg1, zombie_leg2, zombie_health_text]
while :
for part in zombie_parts:
part.move(-0.5, 0)
start_game = Text(Point(400, 100), "Please press 'S' to start the game")
start_game.setSize(25)
start_game.draw(w)
# Wait for the user to press 'S'
while True:
key = w.checkKey()
if key == "s":
start_game.undraw() # Remove the start message
break # Exit the loop once 'S' is pressed
zombie_hand1_left = zombie_hand1.getP1().getX()
# Movement and question loop
k = ""
while zombie_hand1_left >= 200:
try:
generate_question()
except zombie_health <= 0:
you_win = Text(Point(400, 300), "You Win! The zombie is defeated!")
you_win.setSize(20)
you_win.draw(w)
break
except zombie_hand1_left >= 200:
game_over = Text(Point(400, 300), "Game Over! The zombie reached you!")
game_over.setSize(20)
game_over.draw(w)
break
# Wait for user to close the window
w.getMouse()
w.close()
我知道困难的部分是保持两者循环
for part in zombie_parts:
part.move(-0.5, 0)
和
generate_question()
同时,我尝试将两者放入 while 循环中,但也不起作用。我找不到让 2 个循环同时运行的教程
在Python中,不可能执行同时循环,因为它是单线程语言。我建议更改代码方法并使用单个循环来更新游戏状态并检查用户输入。