这是Rubik的Cube加扰生成器的尝试。有时我会一次又一次地转过同一张脸,例如(R,R')。我尝试使用for和while循环修复此问题,但没有成功。
import ast
import _ast
def get_variables(node):
variables = set()
if hasattr(node, 'body'):
for subnode in node.body:
variables |= get_variables(subnode)
elif isinstance(node, _ast.Assign):
for name in node.targets:
if isinstance(name, _ast.Name):
variables.add(name.id)
return variables
print(get_variables(ast.parse(open('file.py').read())))
答案 0 :(得分:0)
我为您提供此解决方案:
import random
MOVES = ['R', 'L', 'D', 'U', 'B', 'F']
MODFIERS = ['', '2', "'"]
def getScramble(length=25):
return ''.join([random.choice(MOVES) for _ in range(length)])
def isValid(scramble):
for seq in ['LR', 'DU', 'BF'] + [move * 2 for move in MOVES]:
if seq in scramble or seq[::-1] in scramble:
return False
return True
while True:
scramble = getScramble()
if isValid(scramble):
break
scramble = ' '.join([move + random.choice(MODFIERS) for move in scramble])
print(scramble)
答案 1 :(得分:0)
我已将您的加扰功能重写为更加有效,并且可以完全按照您的期望工作。
import random
moves = ("R", "F", "U", "L", "B", "D")
modifiers = ("", "2", "'")
def getscramble(n=25):
scramble = random.choices(moves, k=n)
def is_valid(c, c2):
together = c + c2
return (c != c2 and together not in
("RL", "UD", "FB", "LR", "DU", "BF"))
for x in range(1, n):
before = scramble[x - 1]
current = scramble[x]
while not is_valid(before, current):
current = scramble[x] = random.choice(moves)
for i, x in enumerate(random.choices(modifiers, k=n)):
scramble[i] += x
return " ".join(scramble)
答案 2 :(得分:0)
如果添加的最后一个值相同,则无法添加列表。
这是一个更好的while循环,可以满足您的需求:
i = len(scramble)
while i < 25:
current_face = random.choice(moves)
if i == 0:
scramble.append(current_face)
elif scramble[i - 1] == current_face:
continue
else:
scramble.append(current_face)
i += 1
print(' '.join(scramble))
此循环确保列表的长度固定。您可以将修饰符添加到此列表中。
但是。.如果您不习惯使用修饰符的概念,那么出于随机性和简单性的考虑,最好的做法是将上面的循环与带有所有可能排列的长列表一起使用。
import random
def getscramble():
moves = ["R", "F", "U", "L", "B", "D",
"R'", "F'", "U'", "L'", "B'", "D'",
"R2", "F2", "U2", "L2", "B2", "D2"]
scramble = []
i = len(scramble)
while i < 25:
curent_face = random.choice(moves)
if i == 0:
scramble.append(curent_face)
elif (scramble[i - 1])[0] == curent_face[0]:
continue
else:
scramble.append(curent_face)
i += 1
print(' '.join(scramble))
getscramble()
以上代码的输出为:
L' R D2 U L' U' F R2 L' U2 D' R' F' B2 F2 L2 R' D' L2 F' U2 F U2 R D