繁体   English   中英

Python 随机数学方程生成器程序

[英]Python Random Math Equation Generator program

我目前一直在创建一个数学方程生成器程序,它会问你随机乘法问题。 我一直在使用 if 语句时遇到问题,其中 ans == answer 将取决于用户的输入(正确答案)。 但是,尽管与打印 ans 和 answer 的示例值相同,但我的程序并不认为它相等,这表明它们是相同的值。 我不知道我是否做错了什么,我想知道解决我的问题的方法。

此外,当我尝试为生成方程创建 for 和 while 循环时,它会立即将它们全部打印出来,有没有办法也可以使循环不会打印新的随机方程,直到用户得到答案正确的?

from tkinter import *
from random import *
import random
import time
import tkinter as tk
import math
import operator
from tkinter import messagebox


#This is for creating the tkinter window and fixing the specified dimensions into place
root = tk.Tk()
root.geometry("900x600")

#This section creates the canvas and its specifications
canvas_width = 900
canvas_height = 500
c = Canvas(root, width=canvas_width, height=canvas_height, bg="pink")
c.pack()

def quitgame():
    root.destroy()
    
class Game_Images:
    #Background Image
    bg = PhotoImage(file="../Data/sidescroll background flip.gif")
    bg = bg.zoom(2)
    c.create_image(0,0, anchor=NW, image=bg)

    #Insert Image of Enemy
    enemy = PhotoImage(file="../Data/monke2.png")
    enemy1 = c.create_image(0,260, anchor=NW, image=enemy)

    #Insert image of playable character
    player = PhotoImage(file="../Data/monke2.png")
    player1 = c.create_image(0,325, anchor=NW, image=player)
g = Game_Images()


score = 0
x = 1

def game_start():
    global answer, question
    int_1 = random.randint(1, 12)
    int_2 = random.randint(1, 12)
    displayQuestion = "What is "+str(int_1)+ "*" + str(int_2)+"?"
    operator = ["*"]
    ops = random.choice(operator)
    c.create_rectangle(353,0,550,75, fill = "white")
    c.create_text(450, 50, font = ("Helvetica", 15), fill="pink", text = displayQuestion)
    question = str(int_1) + str(ops) + str(int_2)
    answer = int_1 * int_2

def generateQ():
    ans = e1.get()
    e1.delete(0, END)
    if ans == answer:
        score += 1
        x += 1
        print("correct")
        print(ans)
        print(answer)
    else:
        print("wrong")
        print(ans)
        print(answer)


#Buttons show up below the canvas to run commands when pressed
Button(root, text = "Commence Forth",width = 15, command = game_start).place(x=10, y=570)
Button(root, text = "Quit",width = 11, command = quitgame).place(x=800, y=570)
e1 = Entry(root)
e1.pack(padx=30, pady=30)
b=Button(root,text="Enter", width=5, font=("Helvetica", 12), command = generateQ)
b.place(x=550, y=534)

            
root.mainloop()

像这样改变函数generateQ() -

def generateQ():
    global score,x
    ans = e1.get()
    e1.delete(0, END)
    if int(ans) == int(answer):
        score += 1
        x += 1
        print("correct")
        print(ans)
        print(answer)
    else:
        print("wrong")
        print(ans)
        print(answer)

使用int()使它们具有相同的数据类型。 并使用global score,x因为它显示错误。 你也可以写scorex作为参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM