Python和tkinter单词游戏

Python和tkinter单词游戏

数据字典文本文件,文件名为Dictionary.txt,保存编码格式为:utf-8。文本内容:每行一个 单词 ,单词和解释用空格分隔,如

a art.一(个);每一(个)

ability n.能力;能耐,本领

able a.有能力的;出色的

baby n.婴儿;孩子气的人

back ad.在后;回原处;回

background n.背景,后景,经历

cable n.缆,索;电缆;电报

cafe n.咖啡馆;小餐厅

good a.好的;有本事的

游戏规则:

每次随机从文本中选取一个英语单词,在界面上从左到右移动,随机选出三个单词的解释,和英语单词正确解释,随机放到四个按钮中,这四个按钮放到界面下方。

用户单击带有解释的按钮,界面上英语单词消失,再随机从文本中选取一个新英语单词,进入下一个猜单词过程;若英语单词移动出界面,用户未能单击有正确解释的按钮,表示失败,也将随机从文本中选取一个新英语单词,进入下一个猜单词过程。

有失败和成功计数。

使用Python和tkinter来实现这个单词游戏, 运行界面:

使用面向过程方式实现,游戏源码如下:

import tkinter as tk
import random

# 全局变量
root = None
word_label = None
option_buttons = []
score_label = None
dictionary = {}
current_word = ""
current_definition = ""
options = []
success_count = 0
fail_count = 0
word_x = -100

def load_dictionary(filename):
    global dictionary
    with open(filename, 'r', encoding='utf-8') as file:
        for line in file:
            parts = line.strip().split(' ', 1)
            if len(parts) == 2:
                dictionary[parts[0]] = parts[1]

def choose_new_word():
    global current_word, current_definition, options, word_x
    current_word = random.choice(list(dictionary.keys()))
    current_definition = dictionary[current_word]
    options = [current_definition]
    while len(options) < 4:
        random_def = random.choice(list(dictionary.values()))
        if random_def not in options:
            options.append(random_def)
    random.shuffle(options)

    word_label.config(text=current_word)
    for i, button in enumerate(option_buttons):
        button.config(text=options[i])
    
    word_x = -100  # 重置单词位置

def move_word():
    global word_x, fail_count
    if word_x > 400:
        fail_count += 1
        update_score()
        choose_new_word()
    else:
        word_x += 5
        word_label.place(x=word_x, y=50)
    root.after(50, move_word)

def check_answer(index):
    global success_count, fail_count
    if options[index] == current_definition:
        success_count += 1
    else:
        fail_count += 1
    update_score()
    choose_new_word()

def update_score():
    score_label.config(text=f"成功: {success_count} 失败: {fail_count}")

def setup_gui():
    global root, word_label, option_buttons, score_label
    root = tk.Tk()
    root.title("单词游戏")
    root.geometry("400x300")

    score_label = tk.Label(root, text="成功: 0 失败: 0", font=("Arial", 12))
    score_label.pack(anchor='ne', padx=10, pady=10)

    word_label = tk.Label(root, text="", font=("Arial", 24))
    word_label.place(x=-100, y=50)

    button_frame = tk.Frame(root)
    button_frame.pack(side='bottom', pady=20)

    for i in range(4):
        button = tk.Button(button_frame, text="", font=("Arial", 10), width=20, height=1, command=lambda i=i: check_answer(i))
        button.grid(row=i//2, column=i%2, padx=5, pady=5)
        option_buttons.append(button)

def main():
    load_dictionary("Dictionary.txt")
    setup_gui()
    choose_new_word()
    move_word()
    root.mainloop()

if __name__ == "__main__":
    main()

使用这个程序之前,请确保你有一个名为"Dictionary.txt"的文件,格式如你所描述的那样。将这个文件放在与Python脚本相同的目录下。

使用面向对象方式实现,游戏源码如下:

import tkinter as tk
import random

class WordGame:
    def __init__(self, dictionary_file):
        # 初始化游戏窗口
        self.root = tk.Tk()
        self.root.title("单词游戏")
        self.root.geometry("400x300")

        # 加载词典
        self.dictionary = self.load_dictionary(dictionary_file)
        self.current_word = ""
        self.current_definition = ""
        self.options = []
        self.success_count = 0
        self.fail_count = 0
        self.word_x = -100
        
        # 设置游戏界面
        self.setup_gui()

        # 选择新单词并开始移动单词
        self.choose_new_word()
        self.move_word()
    
    def load_dictionary(self, filename):
        # 从文件加载词典并返回一个字典对象
        dictionary = {}
        with open(filename, 'r', encoding='utf-8') as file:
            for line in file:
                parts = line.strip().split(' ', 1)
                if len(parts) == 2:
                    dictionary[parts[0]] = parts[1]
        return dictionary
    
    def choose_new_word(self):
        # 选择一个新的单词和定义,并更新选项按钮的文本
        self.current_word = random.choice(list(self.dictionary.keys()))
        self.current_definition = self.dictionary[self.current_word]
        self.options = [self.current_definition]
        while len(self.options) < 4:
            random_def = random.choice(list(self.dictionary.values()))
            if random_def not in self.options:
                self.options.append(random_def)
        random.shuffle(self.options)
        
        self.word_label.config(text=self.current_word)
        for i, button in enumerate(self.option_buttons):
            button.config(text=self.options[i])
        
        self.word_x = -100  # 重置单词位置到初始值
    
    def move_word(self):
        # 控制单词的移动,如果超出窗口范围则增加失败计数并选择新单词,否则更新单词位置
        if self.word_x > 400:
            self.fail_count += 1
            self.update_score()
            self.choose_new_word()
        else:
            self.word_x += 5
            self.word_label.place(x=self.word_x, y=50)
        self.root.after(50, self.move_word)
    
    def check_answer(self, index):
        # 检查用户选择的答案是否正确,并更新成功或失败计数
        if self.options[index] == self.current_definition:
            self.success_count += 1
        else:
            self.fail_count += 1
        self.update_score()
        self.choose_new_word()
    
    def update_score(self):
        # 更新显示的成功和失败计数
        self.score_label.config(text=f"成功: {self.success_count} 失败: {self.fail_count}")
    
    def setup_gui(self):
        # 设置游戏界面的标签和按钮
        self.score_label = tk.Label(self.root, text="成功: 0 失败: 0", font=("Arial", 12))
        self.score_label.pack(anchor='ne', padx=10, pady=10)

        self.word_label = tk.Label(self.root, text="", font=("Arial", 24))
        self.word_label.place(x=-100, y=50)

        button_frame = tk.Frame(self.root)
        button_frame.pack(side='bottom', pady=20)

        self.option_buttons = []
        for i in range(4):
            # 创建答案选项按钮,并绑定对应的回调函数
            button = tk.Button(button_frame, text="", font=("Arial", 10), width=20, height=1, command=lambda i=i: self.check_answer(i))
            button.grid(row=i//2, column=i%2, padx=5, pady=5)
            self.option_buttons.append(button)
    
    def run(self):
        # 启动游戏的主循环
        self.root.mainloop()

if __name__ == "__main__":
    # 创建WordGame对象并运行游戏
    game = WordGame("Dictionary.txt")
    game.run()

在这个面向对象的实现方式,创建一个WordGame类,该类封装了游戏UI(User Interface,用户界面)元素和主要逻辑功能,包括加载词典、选择新单词、移动单词、检查答案和更新分数。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学习&实践爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值