如何使用 guizero 在 python 中知道 Tic Tac Toe 中谁是获胜者

2023-12-30

我创建了一个名为 Tic Tac Toe 的游戏。有 2 位玩家,其中一位是 X,其中一位是 O,您所要做的就是将您的符号 3 连成一排,而其他人不会阻挡您。

游戏的 GUI 如下所示:

Code:

from guizero import App, TextBox, PushButton, Text, info

empty = '   '
player = "X"
def clicked(z):
    button = buttonlist[int(z)] # Finds out which button was pressed
    global empty, player
    if button.text != empty:
        pass # If button already pushed do nothing
    else:
        # Marks button with user's go
        button.text = player
        # Switches players
        if player == "X":
            player = "O"
        else:
            player = "X"
    return

def instructions():
    info("Instructions","There are 2 players one of them are Xs one of them are Os. All you have to do is you have to try getting your symbol 3 times in a row without the other player blocking you")
def quit_game():
    app.destroy()
    
app = App(title="Tic Tac Toe", layout="grid", width=200, height=250)
buttonlist = [] # Empty list to contain a list of Buttons

Player1_label = Text(app, text="Player 1",  align="top", grid=[0, 0, 2 , 1])
Player1 = TextBox(app, text=empty, align="top", grid=[2, 0, 3, 1])# Player 1 enters the username

Player2_label = Text(app, text="Player 2",  align="top", grid=[0, 1, 2 , 1])
Player2 = TextBox(app, text=empty, align="top", grid=[2, 1, 3, 1])# Player 2 enters the username

Instructions = PushButton(app, command=instructions, text="Instructions", grid=[0, 5, 3, 1])# Display the instructions
                          
Quit = PushButton(app, command=quit_game ,text="Quit",grid=[10, 0, 3, 2])

# Create Buttons for game, in 3 rows of 3
z=0
for x in range(3):
    for y in range(2, 5):
        buttonlist.append(PushButton(app, text=empty, args=str(z), grid=[x, y], command=clicked))
        z+=1

app.display()

我遇到的问题是显示谁是赢家。我知道如何让一个窗口显示获胜者,执行此操作的行是:

app.info("Tic Tac Toe Winner","The winner is" + Player1.value)

但我遇到的问题是知道比赛结束时谁是赢家,因此并显示他们是赢家,我也有一种感觉,找出赢家与buttonlist我制作了清单,但我只是不知道该怎么做,所以如果有人可以帮助我,我将不胜感激。

Thanks


不错的游戏。为了使用游戏板,我建议创建一个内部数据表示,而不是按照惯例一直使用 GUI 元素。

原因是,如果您在任何地方都使用 gui 元素,它可能会更慢,因为它不是理想的数据表示。您无法使用 pickle 等保存数据,并且还对您使用的 gui 框架添加了强烈的依赖关系。 例如。如果您以后打算将其转换为网络应用程序等,您将遇到困难。

因此,我只是创建了一个简单的数据表示形式,其中将字段存储在二维数组中。

# check_win checks if there are three markings
# in one row/column or diagonally
def check_win():
    # the checks array is just a trick to
    # reduce the amount of code,
    # you could avoid it by just adding
    # one nested loop where the outer iterates 
    # over y and the inner over x
    # one with the outer on x and the inner on y
    # and then two others with just one loop
    # for the diagonals
    # the body of the inner loops would
    # esentially look the same as for the while
    # loop below
    checks= [(0, 0, 1, 1), (0, 2, 1, -1)]
    for i in range(3):
        checks.append((i, 0, 0, 1))
        checks.append((0, i, 1, 0))
    won= None
    for y, x, incr_y, incr_x in checks:
        player= field[y][x]
        found= player is not None
        while found and x < 3 and y < 3:
            found= (player == field[y][x])
            y+= incr_y
            x+= incr_x
        if found:
            won= player
            break
    return won

# I also changed your clicked method a bit, so
# it calles the check_win method
# and also changed the signature, so
# it gets the y and x coordinate of the
# button which makes maintaining the
# field array inside the clicked method
# a bit simpler and also seems more natural
# to me
def clicked(y, x):
    button = buttonlist[y][x] # Finds out which button was pressed
    global empty, player
    if button.text != empty:
        pass # If button already pushed do nothing
    else:
        # Marks button with user's go
        button.text = player
        field[y][x] = player
        # Switches players
        if player == "X":
            player = "O"
        else:
            player = "X"
    won= check_win()
    if won is not None:
        print(f'Player {won} has won the game')
    return

# now I initialize the field array
# it will contain None for an untouched
# cell and X/O if taken by the corresponding
# user
field= [[None] * 3 for i in range(3)]
buttonlist= list()

# to get the buttons to call the 
# clicked function with the new
# signature and also maintain the
# buttons in a two dimensional array
# I changed the order of your loops
# and the args argument
for y in range(0, 3):
    rowlist= list()
    buttonlist.append(rowlist)
    for x in range(3):
        rowlist.append(PushButton(app, text=empty, args=(y, x), grid=[x, y+2], command=clicked))
        z+=1

app.display()


# a plain vanilla version of check_win would look something like:

def check_win():
    for start in range(3):
        x= start
        mark= field[0][x]
        for y in range(1, 3):
            if field[y][x] != mark:
                # the sequence is not complete
                mark= None
        if mark is not None:
            # player who set the mark won
            return mark
        y= start
        mark= field[y][0]
        for x in range(1, 3):
            if field[y][x] != mark:
                # the sequence is not complete
                mark= None
        if mark is not None:
            # player who set the mark won
            return mark
    mark= field[0][0]
    for x in range(1, 3):
        if field[y][x] != mark:
            # the sequence is not complete
            mark= None
    if mark is not None:
        # player who set the mark won
        return mark
    mark= field[0][3]
    for x in range(1, 3):
        if field[y][2-x] != mark:
            # the sequence is not complete
            mark= None
    if mark is not None:
        # player who set the mark won
        return mark
    return None        
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 guizero 在 python 中知道 Tic Tac Toe 中谁是获胜者 的相关文章

  • 如何在 SQLAlchemy 中连接两个表中的数据?

    我有3张桌子 Account User and Organization Account由组成id name and organization id User由组成email and organization id Organization
  • 通过 rpy2 将 numpy 数组传递给 R 时出现不一致数组

    我正在尝试将 numpy 数组传递到 R 中的 GAMLSS 包 import numpy as np import rpy2 robjects as robjects from rpy2 robjects import numpy2ri
  • 如何测试 Flask 开发服务器是否已启动?

    我的 Flask 应用程序上有一个测试装置 它启动开发服务器来测试一些用户交互 对于第一个测试 我想确保服务器已启动 一般而言 无需测试特定响应代码 执行此操作的最佳方法是什么 我希望我能用self assertTrue response
  • 如何将 python 点列表转换为 numpy 图像数组?

    我有一个 python 点列表 x y 坐标 200 245 344 248 125 34 它表示二维平面上的轮廓 我想使用一些 numpy scipy 算法进行平滑 插值等 它们通常需要 numpy 数组作为输入 例如scipy ndim
  • 是否可以在数据类中使用 *args?

    我最近开始使用数据类 https www python org dev peps pep 0557 它们将成为 3 7 的一个很好的补充 我很好奇是否或如何可以使用数据类重新创建此类的相同功能 class Nav object def in
  • 您必须使用 dtype float(Tensorflow) 为占位符张量“Placeholder”提供值

    import tensorflow as tf import os import sklearn preprocessing import pandas as pd import numpy as np print os getcwd os
  • 如何在 difflibs html 输出中突出显示每行超过两个字符

    我在用difflib HtmlDiff比较两个文件 我希望在输出的 html 中突出显示差异 当一行中最多有两个不同的字符时 这已经有效 a 2 000 b 2 120 但是 当一行上有更多不同的字符时 在输出中整行将被标记为红色 在左侧
  • 将字符转换为日期时间 odoo 9

    我有两个字符字段 从 odoo 中的 excel 或 csv 导入数据 time 1 fields Char string Time 1 time 2 fields Char string Time 2 result fields Floa
  • 如何删除Python中特定字符之前的所有字符?

    我想删除指定字符或字符集之前的所有字符 例如 intro lt gt I m Tom 现在我想删除 lt gt before I m 或者更具体地说 I 有什么建议么 Use re sub 只需匹配所有字符即可I然后将匹配的字符替换为I r
  • 如何使用ssl启动flask_socketio应用程序?

    我应该如何使用 SSL 将 app run 转换为 sockio run 我有下面的应用程序启动代码与 Flask 开发服务器一起运行 if name main app run ssl context ssl cert ssl key 我现
  • 尝试使用 Paramiko 通过 SSH 连接到新的 EC2 实例时出现问题

    我正在编写一个脚本 该脚本使用 boto 启动一个新的 EC2 实例 并使用 Paramiko SSH 客户端在该实例上执行远程命令 无论出于何种原因 Paramiko 客户端无法连接 我收到错误 Traceback most recent
  • Python并发.futures.ThreadPoolExecutor max_workers

    我在网上找了好久 但没有用 请帮助或尝试给我一些如何实现这一目标的想法 当我使用 python 模块时concurrent futures ThreadPoolExecutor max workers None 我想知道max worker
  • 带约束的简单线性回归

    我开发了一种算法来循环 15 个变量并为每个变量生成一个简单的 OLS 然后算法再循环 11 次以产生相同的 15 个 OLS 回归 但 X 变量的滞后每次增加 1 我选择具有最高 r 2 的自变量 并使用 3 4 或 5 个变量的最佳滞后
  • 清除pyqt中布局中的所有小部件

    有没有办法清除 删除 布局中的所有小部件 self plot layout QtGui QGridLayout self plot layout setGeometry QtCore QRect 200 200 200 200 self r
  • Python 中 `if name == "__main__"` 是什么意思? [复制]

    这个问题在这里已经有答案了 可能的重复 name main gt 做什么 https stackoverflow com questions 419163 what does if name main do 我已经用 Python 编写脚本
  • Django:503 服务不可用

    Related 我对 Python 及其框架完全陌生 在学习了一些 Python 基础知识后 我只是尝试一下 Django Problem 现在我正在尝试在第一次安装后运行 Django 服务器 服务器运行没有任何错误 但是当我尝试访问该网
  • 导入不起作用

    我有两个文件说a py and b py 在 a py 中 我们的确是 import xxx from b import 在 b py 中我们有一个函数需要module xxx 现在当函数在b py被调用自a py它找不到模块xxx 为什么
  • 在标准 python 线程中发出信号

    我有一个线程应用程序 其中有一个网络线程 UI 部分通过callback到这个线程 线程是一个normalpython 线程 它是NO QThread 是否可以在该线程内发出 PyQT Slot 不 不可能像这样从 python 线程发出
  • 就地改变 numpy 函数输出数组

    我正在尝试编写一个对数组执行数学运算并返回结果的函数 一个简化的例子可以是 def original func A return A 1 A 1 为了加速并避免为每个函数调用分配新的输出数组 我希望将输出数组作为参数 并就地更改它 def
  • 访问 django for 循环中的元素

    我有一个 Django 模板 其中包含以下代码 该模板创建多个按钮并尝试通过单击 在同一按钮上 删除 隐藏其中一个按钮 for h in helicopters div class btn group div

随机推荐

  • 将数据附加到已存在的 AudioBuffer 对象

    我正在寻找将数据附加到already现存的音频缓冲区 https developer mozilla org en US docs Web API AudioContext createBuffer正在使用网络音频播放 收到要播放的音频数据
  • 在 gdb-multiarch 中指定架构

    如果我使用任何arm编译器编译C程序 例如arm none eabi gcc 然后调用gdb multiarch使用二进制文件作为第二个参数 它将正确确定机器类型 并且我可以调试我的远程应用程序 然而如果我打电话gdb multiarch就
  • Linux 中以百分比形式准确计算 CPU 使用率?

    这是一个已经被问过很多次的问题 但是我找不到得到充分支持的答案 许多人建议使用 top 命令 但如果您运行 top 一次 因为您有一个脚本 例如每 1 秒收集一次 Cpu 使用情况 它将始终给出相同的 Cpu 使用结果 示例1 https
  • “COM”、“USB”、“串口”有什么区别? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我对这3个概念很困惑 我的理解是 Serial Port通常表示 RS 232 兼容端口 RS 推荐标准 USB代表Universal S
  • 如何使用 $.getJSON 从博主提要获取数据

    我想从博主提要中获取数据使用 getJSON 函数 我使用此代码来获取版本 但它不起作用
  • 从 Spark 保存分区 parquet HIVE 表时出现问题

    火花1 6 0 蜂巢1 1 0 cdh5 8 0 我在将数据帧从 Spark 保存到镶木地板支持的分区 Hive 表中时遇到一些问题 这是我的代码 val df sqlContext createDataFrame rowRDD schem
  • mysql/sqlserver 中截断与删除的比较[重复]

    这个问题在这里已经有答案了 关于 mysql sql 服务器的一件事一直困扰着我 即删除 截断 哪一个更好更快 在哪里使用删除 在哪里使用截断 DELETE DELETE 是一个 DML 命令 DELETE 语句使用行锁执行 表中的每一行都
  • Hive:如何显示表的所有分区?

    我有一个包含 1000 多个分区的表 Show partitions 命令仅列出少量分区 如何显示所有分区 Update 我发现 show partitions 命令仅列出 500 个分区 select where 仅处理 500 个分区
  • Numpy: arr[...,0,:] 有效。但是如何存储切片命令 (..., 0, :) 中包含的数据呢?

    在 Numpy 我想通常是 Python 中 如何存储切片索引 例如 0 以便传递它并将其应用于各种数组 比如说 如果能够在函数之间传递切片索引 那就太好了 Python 根据切片语法创建特殊对象 但仅在方括号内用于索引 您可以手动创建这些
  • 生成随机字符串

    好吧 我知道有很多这样的线程 但我对 vb net 很陌生 但我无法编辑给出的源代码来制作我真正想要的内容 所以我想要一个函数 它将生成随机字符串 每个字符串包含 15 32 个字符 每个字符串将具有以下字符 并非全部在同一字符串 但其中一
  • 如何使用clients2.google.com 下载CRX?

    上周我遇到了一些困难 我已经能够使用以下链接格式使用 Chrome 商店中列出的扩展名的 ID 下载 crx 文件 现在 最近几周发布到 chrome 商店的任何新 chrome 扩展程序都将无法使用 它不会下载任何东西 使用fiddler
  • 确保用户发布的博客评论安全

    我正在我的网站上创建博客引擎 没有什么花哨 用户将注册一些基本信息 包括评论本身 即该问题的问题 在评论字段中 用户可以编写一些文本 但目前没有什么可以阻止他在那里编写任何有害的内容 这会在使用评论渲染页面时弄乱页面 所以我想知道完成这三个
  • Mat-checkbox 已选中但不更改复选框状态

    我正在实现一个语言切换组件 它显示复选框 一个用于应用程序的每种语言 翻译为 ngx translate 单击其中一个复选框时 应用程序语言已正确切换 但单击的 mat checkbox 仍未选中 模板
  • 使用 as.Date 格式化月份缩写[重复]

    这个问题在这里已经有答案了 我正在处理每月数据 并有一个日期字符向量 格式如下 Sep 2012 Aug 2012 Jul 2012 等等 回到 1981 年 我尝试过使用 as Date dates b Y where b代表月份缩写 但
  • 使用集成 Windows 身份验证时提示输入登录详细信息

    对于 ASP NET 应用程序 使用集成 Windows 身份验证时如何提示用户输入用户名 密码 我想在页面后面的代码中使用 C 来执行此操作 我想要一些页面 例如http 内网 admin http intranet admin 提示输入
  • iPhone 的 PhoneGap 数据库应用有什么要求?

    我想创建一个访问数据库的简单应用程序 Does PhoneGap它的框架中有这个功能吗 它使用哪种数据库技术 MySQL 有数据库吗 为 iPhone 开发 PhoneGap 数据库应用程序有哪些要求 数据库 Sqlite 数据库 直接嵌入
  • 如何计算java中相同(PALINDROME)的单词数

    我是一名 Java 开发新手 我想用Java编写代码来计算段落中回文词的数量 假设是 用户可以输入包含尽可能多的句子的段落 每个单词之间以空格分隔 每个句子之间以句点分隔 单词前后的标点符号将被忽略 而单词内部的标点符号将被计算在内 输入示
  • Python:从类B中的类A调用方法A?

    有很多与此类似的问题 但没有一个答案能切中要害 所以请耐心等待 我正在尽最大努力使用 Python 学习 OOP 但我不断遇到错误 比如这个 这让我觉得这一切都是毫无意义的 只使用方法会更容易 这是我的代码 class TheGUI wx
  • 在数字海洋上部署的 laravel 网站显示空白屏幕并尝试通过 https 加载 css 和 js 文件

    我在这里完成了关于部署 laravel 应用程序的教程之一https www techalyst com posts laravel hosting with digital ocean droplet step by step tutor
  • 如何使用 guizero 在 python 中知道 Tic Tac Toe 中谁是获胜者

    我创建了一个名为 Tic Tac Toe 的游戏 有 2 位玩家 其中一位是 X 其中一位是 O 您所要做的就是将您的符号 3 连成一排 而其他人不会阻挡您 游戏的 GUI 如下所示 Code from guizero import App