我正在尝试最终使用Pygame创建矩阵式下雨代码动画。
我陷入了困境,我想为每个角色分配坐标,因为:
我在dict中不能有重复的键,所以这个结构不起作用:
CharacterMatrix = {character : [xPos, yPos]}
但是我也不能将唯一坐标作为Key,因为dict不会接受列表作为键,所以当然这也行不通:
CharacterMatrix = {[xPos, yPos] : character }
我现在的问题是:你如何优雅地存储大量具有相应x和y坐标的非独特随机字符?
非常感谢,抱歉,如果我监督了类似的问题!
答案 0 :(得分:1)
在python dicts中接受不可变类型作为键,因此使用tuple而不是list。
修改强> 例如:
In [1]: d = {(1, 2,): 'a', (1, 1): 'b', (2, 1): 'c', (2, 2): 'd'}
In [2]: d[(1, 1)]
Out[2]: 'b'
答案 1 :(得分:0)
您不存储矩阵,将列存储为“句子”,使用zip
从中创建行:
c = ["SHOW", "ME ", "THIS"]
r = [' '.join(row) for row in zip(*c)]
print (c)
for n in r:
print(n)
输出:
['SHOW', 'ME ', 'THIS']
S M T
H E H
O I
W S
现在你只需要改变内容 - 你可以切割字符串:
c[1] = "!"+c[1][:-1]
r = [' '.join(row) for row in zip(*c)]
for n in r:
print(n)
输出:
S ! T
H M H
O E I
W S
矩阵会很麻烦,你想要向下滚动单列,而其他列静止不动,可能想要替换单个字符。使用矩阵需要你一直降低速度,更容易修改“列句”(如上所述)或字符串列表:
from string import ascii_letters, digits
from itertools import product
import random
import os
import time
random.seed(42) # remove for more randomness
numCols = 10
numRows = 20
allCoods = list(product(range(numCols),range(numRows))) # for single char replacement
pri = ascii_letters + digits + '`?=)(/&%$§"!´~#' # thats what we display
# cred: https://stackoverflow.com/a/684344/7505395
def cls():
os.system('cls' if os.name=='nt' else 'clear')
def modCol(columns, which):
for (c,r) in which:
# replace change random characters
newOne = random.choice(pri)
columns[c] = columns[c][:r]+[newOne]+columns[c][r+1:]
for i in range(len(columns)):
if (random.randint(0,5) > 2):
# scroll some lines down by 1
columns[i].insert(0,random.choice(pri))
columns[i] = columns[i][:-1]
# creates random data for columns
cols = [random.choices(pri ,k=numRows ) for _ in range(numCols)]
while True:
cls()
# zip changes your columns-list into a row-tuple, the joins for printing
print ( '\n'.join(' '.join(row) for row in zip(*cols)))
time.sleep(1)
# which characters to change?
choi = random.choices(allCoods, k=random.randint(0,(numCols*numRows)//3))
modCol(cols, choi )