用Tkinter创建游戏板 [英] Creating a game board with Tkinter

查看:57
本文介绍了用Tkinter创建游戏板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建 连接四人 的简单游戏>使用 Python(2.7)

I am trying to build a simple game of Connect Four with Python(2.7)

我创建了一个板,其中包含一个简单的多维Python列表.
我的董事会列表如下:

I have created a board, that consists of a simple multidimensional Python list.
My Board list looks like this:

board = [
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,_,_,_,_,_,_],
    [_,_,_,_,O,_,_,_,_,_],
    [_,_,_,_,X,_,_,_,_,_],
    [_,_,_,_,X,O,_,_,_,_],
    [_,_,_,_,X,O,_,_,_,_],
]

X是 Player1 ,O是 Player2 (或计算机).

Were X is Player1 and O is Player2 (or Computer).

现在,我已经为 GUI 创建了一些基本代码,如下所示:

Now, I have created some basic code for the GUI, like this:

# Connect 4 Game
import Tkinter

screen = Tkinter.Tk()
screen.title("My First Game")

#Create a board
board = Tkinter.Canvas(screen,width=500,height=500)
board.pack()

screen.mainloop()

问题:我如何创建木板的视觉表示,以便在每个列表中都有一个矩形?另外,有没有一种方法可以检测单击矩形时是否替换了相应的列表值?

Question: How can i create a visual representation of the board, so that for every list, there is a rectangle? Also, is there a way to detect, when a rectangle is clicked and replace the corresponding list value?

推荐答案

我创建了一个标签板,并根据单击的颜色对其进行了着色:

I created a board of labels and color them according to which is clicked:

import Tkinter as tk

board = [ [None]*10 for _ in range(10) ]

counter = 0

root = tk.Tk()

def on_click(i,j,event):
    global counter
    color = "red" if counter%2 else "black"
    event.widget.config(bg=color)
    board[i][j] = color
    counter += 1


for i,row in enumerate(board):
    for j,column in enumerate(row):
        L = tk.Label(root,text='    ',bg='grey')
        L.grid(row=i,column=j)
        L.bind('<Button-1>',lambda e,i=i,j=j: on_click(i,j,e))

root.mainloop()

这不会做任何验证(例如,确保单击的元素在底部).使用类而不是全局数据也将更好,但这是有兴趣的编码人员的练习:).

This doesn't do any validation (to make sure that the element clicked is at the bottom for example). It would also be much better with classes instead of global data, but that's an exercise for the interested coder :).

这篇关于用Tkinter创建游戏板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆