首页 > 解决方案 > 将 2D 坐标转换为 2D 数组中的相应索引

问题描述

我正在编写井字游戏,我管理每个单元格状态的方式是通过这样的数组:

cell_states = [
  [-1, -1, -1],
  [-1, -1, -1],
  [-1, -1, -1]
]

但是,我游戏中的每个单元格都有一个窗口坐标(x, y)(0, 0)左下角在哪里。如何对函数进行编程,使其根据坐标输入返回二维数组的索引?我在想这样的事情:

index = coords_to_index(x=0, y=0) #(0, 0) should be at the bottom left corner.
print(index) #prints (2, 0), the geometrically corresponding index. This is the part I'm struggling with.

关于如何做到这一点的任何建议?欢迎提出更好的管理单元状态的方法。谢谢!

标签: pythonarrayscoordinates

解决方案


推荐阅读