我想知道如何将不同的精灵设置为矩阵中的不同数字。例如,如果我有一个矩阵:
[[ 2 -1 1 0 1 1]
[-1 0 2 0 3 1]
[ 0 -1 0 -1 1 2]]
如何在该号码出现的特定地点为1号,2号,3号等添加某个敌人。
矩阵中的数字是随机生成的。到目前为止,这是我的代码:
from random import *
import numpy as np
rows = 3
cols = 6
matrix = np.matrix(np.random.randint(-1,4, size=(rows, cols)))
我想做什么:
def create_enemies():
for int in matrix:
if int == 1:
enemy = Enemy()
enemy_group.add(enemy)
if int == 2:
enemy2 = Enemy2()
enemy_group.add(enemy2)
答案 0 :(得分:2)
for i in range(rows):
for j in range(cols):
position = matrix[i][j]
if position == 1:
enemy = Enemy()
matrix[i][j] = enemy
enemy_group.add(enemy)
elif position == 2:
enemy = Enemy2()
matrix[i][j] = enemy
enemy_group.add(enemy)
else:
enemy = Enemy3()
matrix[i][j] = enemy
enemy_group.add(enemy)
更好的解决方案是在矩阵中设置随机精灵,并避免完全设置数字。类似的东西:
import random
class Dog:
def __init__(self):
self.x = 1
class Cat:
def __init__(self):
self.x = 1
class Pig:
def __init__(self):
self.x = 1
rows = 6
cols = 3
choices = [Dog(), Cat(), Pig()]
matrix = [[random.choice(choices) for i in range(rows)] for j in range(cols)]
print(matrix)