首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Python 3扫雷机tkinter游戏

Python 3扫雷机tkinter游戏
EN

Code Review用户
提问于 2019-02-17 04:59:20
回答 1查看 790关注 0票数 3

我刚刚完成了我的扫雷游戏使用tkinter,并想知道我如何可以改进我的程序。

代码语言:javascript
运行
AI代码解释
复制
from tkinter import *
from tkinter import messagebox
from random import randint

class setupwindow():
    def __init__(window): #window is the master object of the setup window
        window.root = Tk()
        window.root.title("Setup")
        window.root.grid()

        window.finish = "N"

        labels = ["Height:", "Width:", "Mines:"]
        window.label = ["","",""]
        window.entry = ["","",""]

        for i in range(3):
            window.label[i] = Label(text = labels[i])
            window.label[i].grid(row = i, column = 1)
            window.entry[i] = Entry()
            window.entry[i].grid(row = i, column = 2)

        window.startbutton = Button(text = "Start", command = lambda: setupwindow.onclick(window))
        window.startbutton.grid(column = 2)
        window.root.mainloop()

    def onclick(window):
        setupwindow.verification(window)
        if window.verf == "Y":
            window.finish = "Y"
            window.root.destroy()
            return window

    def verification(window):
        height = window.entry[0].get()
        width = window.entry[1].get()
        mines = window.entry[2].get()

        window.verf = "N"
        if height.isdigit() and width.isdigit() and mines.isdigit():
            height = int(height)
            width = int(width)
            mines = int(mines)

            if height > 0 and height <= 24:
                totalsquares = height * width

                if width > 0 and width <= 48:

                    if mines > 0:
                        if mines < totalsquares:
                            window.verf = "Y"
                            window.height = height
                            window.width = width
                            window.mines = mines

                        else:
                            messagebox.showerror("Invalid", "You cannot have more mines than squares!")
                    else:
                        messagebox.showerror("Invalid", "You can't play minesweeper without mines!")
                else:
                    messagebox.showerror("Invalid", "Width must be between 1 and 48 inclusive")
            else:
                messagebox.showerror("Invalid", "Height must be between 1 and 24 inclusive")
        else:
            messagebox.showerror("Invalid", "All values must be integers")


class gamewindow():
    def __init__(s, setup):  #s is the master object of the main game
        s.height = setup.height
        s.width = setup.width
        s.mines = setup.mines

        s.root = Tk()
        s.root.title("Minesweeper")
        s.root.grid()

        s.finish = "N"
        s.maingrid = list()
        for i in range(s.height):
            s.maingrid.append([])
            for x in range(s.width):
                s.maingrid[i].append(" ")
                s.maingrid[i][x] = Button(height = 0, width = 3, font = "Calibri 15 bold", text = "", bg = "gray90", command = lambda i=i, x=x: gamewindow.onclick(s, i, x))

                s.maingrid[i][x].bind("<Button-3>", lambda event="<Button-3>", i=i, x=x: gamewindow.rightclick(event, s, i, x))
                s.maingrid[i][x].grid(row = i, column = x)
                s.maingrid[i][x].mine = "False"

        totalsquares = s.height * s.width
        s.scoreneeded = totalsquares - s.mines
        s.score = 0

        indexlist = list()
        for i in range(totalsquares):
            indexlist.append(i)

        spaceschosen = list() #where the mines are going to be
        for i in range(s.mines):
            chosenspace = randint(0, len(indexlist) - 1)
            spaceschosen.append(indexlist[chosenspace])
            del indexlist[chosenspace]

        for i in range(len(spaceschosen)):
            xvalue = int(spaceschosen[i] % s.width)
            ivalue = int(spaceschosen[i] / s.width)

            s.maingrid[ivalue][xvalue].mine = "True"

        s.root.mainloop()


    def onclick(s, i, x):
        colourlist = ["PlaceHolder", "Blue", "Green", "Red", "Purple", "Black", "Maroon", "Gray", "Turquoise"]

        if s.maingrid[i][x]["text"] != "F" and s.maingrid[i][x]["relief"] != "sunken":
            if s.maingrid[i][x].mine == "False":
                s.score += 1

                combinationsi = [1, -1, 0, 0, 1, 1, -1, -1]
                combinationsx = [0, 0, 1, -1, 1, -1, 1, -1] #All the surrounding spaces

                minecount = 0
                for combinations in range(len(combinationsi)):
                    tempi = i + combinationsi[combinations]
                    tempx = x + combinationsx[combinations]

                    if tempi < s.height and tempx < s.width and tempi >= 0 and tempx >= 0:
                        if s.maingrid[tempi][tempx].mine == "True":
                            minecount = minecount + 1

                if minecount == 0:
                    minecount = ""

                s.maingrid[i][x].configure(text = minecount, relief = "sunken", bg = "gray85")

                if str(minecount).isdigit():
                    s.maingrid[i][x].configure(fg = colourlist[minecount])

                if minecount == "":
                    for z in range(len(combinationsi)):
                        if s.finish == "N":
                            ivalue = i + int(combinationsi[z])
                            xvalue = x + int(combinationsx[z])

                            if ivalue >= 0 and ivalue < s.height and xvalue >=0 and xvalue < s.width:
                                if s.maingrid[ivalue][xvalue]["relief"] != "sunken":
                                    gamewindow.onclick(s, ivalue, xvalue)

                if s.score == s.scoreneeded and s.finish == "N":
                    messagebox.showinfo("Congratulations", "A winner is you!")
                    s.finish = "Y"
                    s.root.destroy()


            else:
                s.maingrid[i][x].configure(bg = "Red", text = "*")
                for a in range(len(s.maingrid)):
                    for b in range(len(s.maingrid[a])):
                        if s.maingrid[a][b].mine == "True":
                            if s.maingrid[a][b]["text"] == "F":
                                s.maingrid[a][b].configure(bg = "Green")
                            elif s.maingrid[a][b]["bg"] != "Red":
                                s.maingrid[a][b].configure(bg = "Pink", text = "*")

                        elif s.maingrid[a][b]["text"] == "F":
                            s.maingrid[a][b].configure(bg = "Yellow")

                messagebox.showinfo("GAME OVER", "You have lost")
                s.root.destroy()

    def rightclick(event, s, i, x):
        if s.maingrid[i][x]["relief"] != "sunken":
            if s.maingrid[i][x]["text"] == "":
                s.maingrid[i][x].config(text = "F")
            elif s.maingrid[i][x]["text"] == "F":
                s.maingrid[i][x].config(text = "?")
            else:
                s.maingrid[i][x].config(text = "")


if __name__ == "__main__":
    setup = setupwindow()
    if setup.finish == "Y":
        game = gamewindow(setup)
    quit()
EN

回答 1

Code Review用户

回答已采纳

发布于 2019-02-17 06:14:11

  1. 佩普-8
    • 类名通常应该使用CapWords约定。#类名
    • 当用于指示关键字参数时,或用于指示未注释函数参数的默认值时,不要在=符号周围使用空格。#白空间
    • 始终在实例方法的第一个参数中使用self。#函数和方法-参数
    • 还有其他PEP-8违规事件。阅读完整文件

  2. 保护条款 什么是警卫条款以及如何使用它们?
  3. 在需要之前不要使用for i in range(len(list))。即使您需要它,也可以使用enumerate代替。

  4. range转换为list
代码语言:javascript
运行
AI代码解释
复制
        indexlist = list()
        for i in range(totalsquares):
            indexlist.append(i)

等于indexlist = list(range(totalsquares))

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/213648

复制
相关文章
Python中的编码
Python处理字符串,写文件时会碰到许多的编码问题,特别是涉及到中文的时候,非常烦人,但又不得不学。下面主要记录工作过程中碰到的Python编码问题。 1. 字符串编码 Python的字符串类型为s
Tyan
2017/12/29
1K0
解决安卓中XML文件声明高度 宽度无效的问题
搬砖的时候,需要在popupwindow里嵌套一个ListView用来展示动态菜单。重写了ListView的高度为所有的Item高度之和。 item: <?xml version="1.0"
Xiaolei123
2018/06/28
2.1K0
编码声明的问题(php或meta)
编码声明的方法:一种是利用php header来进行声明,另外一种是利用HTML <meta >标签进行声明 1.利用php header()函数声明,这个header()函数的作用是把括号里面的信息发到http标头。  header("Content-type: text/html; charset=xxx");  例如: php页面为utf编码 header("Content-type: text/html; charset=utf-8");  php页面为gbk编码 header("Conten
joshua317
2018/04/10
1.2K0
文字编码 - XML 教程
XML 指可扩展标记语言,被设计用来传输和存储数据。本文记录XML基础知识。 教程参考w3school。 简介 XML 指可扩展标记语言(EXtensible Markup Language) XML 是一种标记语言,很类似 HTML XML 的设计宗旨是传输数据,而非显示数据 XML 标签没有被预定义。您需要自行定义标签 XML 被设计为具有自我描述性。 XML 是 W3C 的推荐标准 XML 是没有任何行为的纯文本,仅编码保存数据 用途 XML 把数据从 HTML 分离 XML 简化数据共享 X
为为为什么
2022/08/04
6420
文字编码 - XML 教程
Python中的编码问题
视频汇总首页:http://edu.51cto.com/lecturer/index/user_id-4626073.html
py3study
2020/01/06
2K0
python中的编码问题
在python2.x中,有两种数据类型,unicode和str,这两个都是basestring的子类
py3study
2020/01/05
1.4K0
Python中类的声明,使用,属性,实例
注意这里的方法__intit__(self)下划线是前面两个下划线,后面两个下划线,并不是一个下划线。
py3study
2020/01/15
5.7K0
python中的编码与解码
编码/解码本质上是一种映射(对应关系),比如‘a’用ascii编码则是65,计算机中存储的就是00110101,但是显示的时候不能显示00110101,还是要显示'a',但计算机怎么知道00110101是'a'呢,这就需要解码,当选择用ascii解码时,当计算机读到00110101时就到对应的ascii表里一查发现是'a',就显示为'a'
李拜六不开鑫
2018/09/04
1.3K0
python中的编码与解码
Python 中的 Elias Delta 编码
首先,在为 Elias Delta 编码编写代码之前,我们将实现 Elias delta 编码。
海拥
2021/12/20
6670
python中烦人的编码问题
mysql数据中都是UTF编码,导出到文件称csv还是xls都是utf-8,用python的pandas读取可以,但每次写代码的时候都需要很小心看文件原来是什么编码
机械视角
2019/10/23
8080
Spring 基于 XML 的声明式事务控制(配置方式)
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
多凡
2019/11/01
4680
python中轻松声明变量和使用
如果变量已经被声明过,在Python中实际上是被初始化赋值过,那么就可以在声明后进行调用,调用的时候,只需要使用变量的名称即可。
刘金玉编程
2019/08/20
1.3K0
Spring使用自带的DataSourceTransactionManager声明式事务(xml)模板
我这里用的是Druid连接池 applicationConttext.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://
用户9006224
2022/12/21
4400
Python中编码问题(UnicodeDecodeError)的处理
之前也遇到过,但是没有深入的去了解和测试,今天借此问题,对python的编码问题做个详细的学习;首先说明一点的是,目前公司的开发环境是Python 2.7;
SEian.G
2021/03/18
3.8K0
浅谈 Python 2 中的编码问题
Python 2.x 里的编码实在是一件令人烦躁的事情。不断有初学者被此问题搞得晕头转向。我自己也在很长一段时间内深受其害,直到现在也仍会在开发中偶尔被坑。在本教室的提问和讨论中,编码问题也占据了相当大的比重。 然而这个问题并不能一两句话轻易解答。今天在这里稍微分析一下,希望能帮各位理清这里面的问题。 要弄清编码问题,首先明确几个概念: str、unicode、encode、decode str 就是我们通常说的字符串,在 python 中是由引号包围的一串字符。但是 Python 中的默认字符并不包括中文
Crossin先生
2018/04/17
1K0
Spring 基于纯注解方式的声明事务控制(不带XML)
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
多凡
2019/11/01
4740
JAVA中的声明语句
JSP声明语句:<%!声明语句%>,通常声明全局变量、常量、方法、类 JSP Scriptlet:<%java代码%>,其中可包含局部变量、java语句 JSP表达式:<%=java 代码%> 显示注释:即HTML注释,可以在客户端显示<!–注释部分--> 隐式注释:即JSP注释,不能在客户端显示<%--注释部分--%> <!-- 显示注释:声明局部变量、java语句 --> 以下是举得例子,帮助你理解 <% int result = 1; out.println(NUM + "+" + result +
Twcat_tree
2022/11/30
9960
Spring Cache抽象-基于XML的配置声明(基于EhCache的配置)
首先请阅读Spring Cache抽象-基于XML的配置声明(基于ConcurrentMap的配置),本篇博文基于XML的配置,使用了Ehcache缓存管理器。
小小工匠
2021/08/17
3750
Spring JDBC-使用XML配置声明式事务
大多数开发者选择声明式事务管理的功能,这种方式对代码的侵入性最小,可以让事务管理完全从业务代码中移除,非常符合非侵入式轻量容器的理念。
小小工匠
2021/08/17
4470
点击加载更多

相似问题

需要关于Swift while语句的建议

44

关于while循环内打印语句的查询

115

关于带有开关的do-while语句

30

关于涉及while和switch语句的购买问题

20

未知while while语句

14
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档