在Python中将项目随机放置在列表列表中
我是Python 的初学者,我一直在尝试编写扫雷游戏。基本上,我有点不知道如何设置我的类,以便它使用列表列表创建一个 5x5 的单元格网格,然后在该网格上随机放置 3 个地雷,并计算每个单元格附近的地雷数量。
我想我会使用一个 __init__ 方法来调用另外两个方法:一个用于放置地雷,另一个用于计算每个单元格的邻域。
我对如何设置有点迷失,所以有什么建议吗?
I'm a beginner at using Python and I've been trying to code a Minesweeper game. Basically, I'm a bit lost on how to set up my class so that it creates a 5x5 grid of cells using a list of lists, then randomly places 3 mines on this grid, and counts the number of mines in each cell's neighborhood.
I figured I would use an __init__
method that would call on two other methods: one for placing the mines, and another for counting each cell's neighborhood.
I'm a bit lost on how to set those up though so any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面是一些可以帮助您入门的代码:
Here's a little code to get you started:
每个单元格只是二维列表中的一个坐标 (x, y)。所以如果我理解正确的话,你只需要拿出三个随机坐标并将它们分配给 board[x][y] 。
我可能会这样做。
如果您想要更多地雷,您可以将这些代码行概括为循环并将坐标放入列表中。不过,可能有一种更简洁的方法来做到这一点。
不知道有什么简单的方法可以计算出我头顶上的相邻细胞。
Each cell is just a coordinate (x, y) in your 2d list. So you just need to come up with three random coordinates and assign them to board[x][y] if I understand you correctly.
I might do it like this.
If you want more mines you can just generalize those lines of code into a loop and put the coordinates into a list. There might be a more concise way to do this though.
Don't know of an easy way to count the neighbor cells off the top of my head.
要创建随机列表,最好的方法是这样做 -
这会随机地就地洗牌您的列表。
或者,如果您想从列表中随机获取一个元素,请尝试 -
To create a random list, the best is to do this -
This randomly shuffles your list in-place.
Or if you want to get an element from a list randomly, try -