gpt4 book ai didi

python - 使用 (x,y) 坐标到达特定的 "village"(Python 3)

转载 作者:太空宇宙 更新时间:2023-11-04 07:08:48 25 4
gpt4 key购买 nike

很抱歉标题与我的问题无关。帮我想一个,我会改(如果可能的话)。

这是我想做的。我会尽量保持简短。

在坐标网格 (0-9) 中随机生成一些村庄。每个村庄都有一个类别、坐标和一个随机的村庄名称。

我已经成功地弄清楚了如何打印游戏板。我坚持让玩家能够输入坐标来查看村庄的详细信息。

这是我目前的代码。

def drawing_board():
board_x = '0 1 2 3 4 5 6 7 8 9'.split()
board_y = '1 2 3 4 5 6 7 8 9'.split()
total_list = [board_x]
for i in range(1,10):
listy = []
for e in range(0,9):
if e == 0:
listy.append(str(i))
listy.append('.')
total_list.append(listy)
return total_list
drawing = drawing_board()
villages = [['5','2'],['5','5'],['8','5']] #I would like these to be random
#and associated with specific villages.
#(read below)
for i in villages:
x = int(i[1])
y = int(i[0])
drawing[x][y] = 'X'

for i in drawing:
print(i)
print()
print('What village do you want to view?')

这会打印游戏板。然后我在考虑制作一个看起来像这样的类:

import random
class new_village():
def __init__(self):
self.name = 'Random name'
x = random.randint(1,9)
y = random.randint(1,9)
self.coordinates = [x,y]
tribe = random.randint(1,2)
if tribe == 1:
self.tribe = 'gauls'
elif tribe == 2:
self.tribe = 'teutons'

def getTribe(self):
print('It is tribe ' +self.tribe)

def getCoords(self):
print(str(self.coordinates[0])+','+str(self.coordinates[1]))

现在是我坚持的部分。我怎样才能到达玩家可以输入坐标并查看这样的村庄的地方?

最佳答案

您的代码存在一些问题,导致您无法针对您的问题实现干净的解决方案。

首先,我会让 board_xboard_y 实际上包含整数而不是字符串,因为您要在 __init__ new_village 的方法。

>>> board_x = list(range(10))
>>> board_y = list(range(1,10))
>>> board_x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> board_y
[1, 2, 3, 4, 5, 6, 7, 8, 9]

此外,我会像这样在 map 上创建一个没有村庄的所有位置的列表:

locations = [(x,y) for x in board_x for y in board_y]

现在你的类代码的关键问题是两个村庄可以在完全相同的位置生成。当发生这种情况并且用户输入坐标时,您如何知道应该打印哪些值?为防止这种情况,您可以将 locations 传递给 __init__ 方法。

def __init__(self, locations):
# sanity check: is the board full?
if not locations:
print('board is full!')
raise ValueError

# choose random location on the board as coordinates, then delete it from the global list of locations
self.coordinates = random.choice(locations)
del locations[locations.index(self.coordinates)]

# choose name and tribe
self.name = 'Random name'
self.tribe = random.choice(('gauls', 'teutons'))

因为你已经为你的村庄创建了一个类,你的列表 villages 实际上应该包含这个类的实例,即而不是

villages = [['5','2'],['5','5'],['8','5']]

你可以发布

villages = [new_village(locations) for i in range(n)] 

其中 n 是您想要的村庄数。现在,为了便于进一步查找,我建议创建一个字典,将您板上的位置映射到村庄实例:

villdict = {vill.coordinates:vill for vill in villages}

最后,现在可以轻松处理用户输入并在输入位置打印村庄的值。

>>> inp = tuple(int(x) for x in input('input x,y: ').split(','))
input x,y: 5,4
>>> inp
(5, 4)

您现在可以发出:

if inp in villdict:
chosen = villdict[inp]
print(chosen.name)
print(chosen.tribe)
else:
print('this spot on the map has no village')

关于python - 使用 (x,y) 坐标到达特定的 "village"(Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24690591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com