在 Python 中创建类似棋盘游戏的网格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4954395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create Board Game-like Grid in Python
提问by chimeracoder
I am thinking of creating a board game in Python, one which will have a grid of spaces, each with different properties, and which may or may not have pieces resting on them. These pieces should be able to move between spaces, though subject to various rules. (Chess or checkers would be good examples of what I'm thinking of, though my game would have different/more complicated rules, and the grid may not be square, even if the spaces are).
我正在考虑用 Python 创建一个棋盘游戏,它将有一个空间网格,每个空间都有不同的属性,并且可能有也可能没有放在上面的棋子。这些棋子应该能够在空间之间移动,但要遵守各种规则。(国际象棋或跳棋将是我所想的很好的例子,尽管我的游戏会有不同/更复杂的规则,并且网格可能不是方形的,即使空格是)。
I wrote a Java implementation of something similar for a data structures class, using a modified version of linked lists. But this is Python, so I imagine there's a better way to do it (maybe even a library out there?)
我使用链表的修改版本为数据结构类编写了一个类似的 Java 实现。但这是 Python,所以我想有更好的方法来做到这一点(甚至可能是一个库?)
采纳答案by Bryan Oakley
Drawing a chessboard is pretty trivial with Tkinter. Here's a really simple example:
使用 Tkinter 绘制棋盘非常简单。这是一个非常简单的例子:
import Tkinter as tk
class GameBoard(tk.Frame):
def __init__(self, parent, rows=8, columns=8, size=32, color1="white", color2="blue"):
'''size is the size of a square, in pixels'''
self.rows = rows
self.columns = columns
self.size = size
self.color1 = color1
self.color2 = color2
self.pieces = {}
canvas_width = columns * size
canvas_height = rows * size
tk.Frame.__init__(self, parent)
self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0,
width=canvas_width, height=canvas_height, background="bisque")
self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2)
# this binding will cause a refresh if the user interactively
# changes the window size
self.canvas.bind("<Configure>", self.refresh)
def addpiece(self, name, image, row=0, column=0):
'''Add a piece to the playing board'''
self.canvas.create_image(0,0, image=image, tags=(name, "piece"), anchor="c")
self.placepiece(name, row, column)
def placepiece(self, name, row, column):
'''Place a piece at the given row/column'''
self.pieces[name] = (row, column)
x0 = (column * self.size) + int(self.size/2)
y0 = (row * self.size) + int(self.size/2)
self.canvas.coords(name, x0, y0)
def refresh(self, event):
'''Redraw the board, possibly in response to window being resized'''
xsize = int((event.width-1) / self.columns)
ysize = int((event.height-1) / self.rows)
self.size = min(xsize, ysize)
self.canvas.delete("square")
color = self.color2
for row in range(self.rows):
color = self.color1 if color == self.color2 else self.color2
for col in range(self.columns):
x1 = (col * self.size)
y1 = (row * self.size)
x2 = x1 + self.size
y2 = y1 + self.size
self.canvas.create_rectangle(x1, y1, x2, y2, outline="black", fill=color, tags="square")
color = self.color1 if color == self.color2 else self.color2
for name in self.pieces:
self.placepiece(name, self.pieces[name][0], self.pieces[name][1])
self.canvas.tag_raise("piece")
self.canvas.tag_lower("square")
# image comes from the silk icon set which is under a Creative Commons
# license. For more information see http://www.famfamfam.com/lab/icons/silk/
imagedata = '''
R0lGODlhEAAQAOeSAKx7Fqx8F61/G62CILCJKriIHM+HALKNMNCIANKKANOMALuRK7WOVLWPV9eR
ANiSANuXAN2ZAN6aAN+bAOCcAOKeANCjKOShANKnK+imAOyrAN6qSNaxPfCwAOKyJOKyJvKyANW0
R/S1APW2APW3APa4APe5APm7APm8APq8AO28Ke29LO2/LO2/L+7BM+7BNO6+Re7CMu7BOe7DNPHA
P+/FOO/FO+jGS+/FQO/GO/DHPOjBdfDIPPDJQPDISPDKQPDKRPDIUPHLQ/HLRerMV/HMR/LNSOvH
fvLOS/rNP/LPTvLOVe/LdfPRUfPRU/PSU/LPaPPTVPPUVfTUVvLPe/LScPTWWfTXW/TXXPTXX/XY
Xu/SkvXZYPfVdfXaY/TYcfXaZPXaZvbWfvTYe/XbbvHWl/bdaPbeavvadffea/bebvffbfbdfPvb
e/fgb/Pam/fgcvfgePTbnfbcl/bfivfjdvfjePbemfjelPXeoPjkePbfmvffnvbfofjlgffjkvfh
nvjio/nnhvfjovjmlvzlmvrmpvrrmfzpp/zqq/vqr/zssvvvp/vvqfvvuPvvuvvwvfzzwP//////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////yH+FUNyZWF0ZWQgd2l0aCBU
aGUgR0lNUAAh+QQBCgD/ACwAAAAAEAAQAAAIzAD/CRxIsKDBfydMlBhxcGAKNIkgPTLUpcPBJIUa
+VEThswfPDQKokB0yE4aMFiiOPnCJ8PAE20Y6VnTQMsUBkWAjKFyQaCJRYLcmOFipYmRHzV89Kkg
kESkOme8XHmCREiOGC/2TBAowhGcAyGkKBnCwwKAFnciCAShKA4RAhyK9MAQwIMMOQ8EdhBDKMuN
BQMEFPigAsoRBQM1BGLjRIiOGSxWBCmToCCMOXSW2HCBo8qWDQcvMMkzCNCbHQga/qMgAYIDBQZU
yxYYEAA7
'''
if __name__ == "__main__":
root = tk.Tk()
board = GameBoard(root)
board.pack(side="top", fill="both", expand="true", padx=4, pady=4)
player1 = tk.PhotoImage(data=imagedata)
board.addpiece("player1", player1, 0,0)
root.mainloop()
回答by Senthil Kumaran
You can consider your underlying board implementation as different kind of datastructures.
您可以将底层电路板实现视为不同类型的数据结构。
- List of lists - l1 = [[1,2,3],[4,5,6],[7,8,9]]
- Dict with values as list = d1 = {a:[1,2,3],b:[4,5,6],c:[7,8,9]}
- Dict with keys are coordinates and values which you can assign.
- As a Graph
- 列表列表 - l1 = [[1,2,3],[4,5,6],[7,8,9]]
- 字典的值为 list = d1 = {a:[1,2,3],b:[4,5,6],c:[7,8,9]}
- 带有键的字典是您可以分配的坐标和值。
- 作为图表
Here is a design of an empty chessboard.
这是一个空棋盘的设计。
>>> chessboard = {}
>>> for row in range(8):
... for col in range(8):
... chessboard[(row,col)] = 0
...
>>>
You can use any of these and design the logic of your game. For higher level elements you can tie these objects or elements within to spites of pygame
您可以使用其中任何一种来设计您的游戏逻辑。对于更高级别的元素,您可以将这些对象或元素与pygame 的恶意联系起来

