使用Python 2。7:
import math
# Get coordinates of possible dislocations
def get_possible_dislocations(initial_x, initial_y, max_steps):
possible_dislocations = []
for x in range(-max_steps,max_steps+1):
for y in range(-max_steps,max_steps+1):
if math.pow(x, 2) + math.pow(y, 2) <= math.pow(max_steps, 2):
possible_dislocations += [[initial_x + x, initial_y + y]]
return possible_dislocations
print get_possible_dislocations(0,0,2)
# Returns [[-2, 0], [-1, -1], [-1, 0], [-1, 1], [0, -2], [0, -1], [0, 0], [0, 1], [0, 2], [1, -1], [1, 0], [1, 1], [2, 0]]
如果你想與pygame的測試它,你可以做到這一點,如:
import math
import pygame, sys
from pygame.locals import *
# Get coordinates of possible dislocations
def get_possible_dislocations(initial_x, initial_y, max_steps):
possible_dislocations = []
for x in range(-max_steps,max_steps+1):
for y in range(-max_steps,max_steps+1):
if math.pow(x, 2) + math.pow(y, 2) <= math.pow(max_steps, 2):
possible_dislocations += [[initial_x + x, initial_y + y]]
return possible_dislocations
# Initialize Pygame
pygame.init()
crashed = False
display_width = 500
display_height = 500
clock = pygame.time.Clock()
display=pygame.display.set_mode((display_width,display_height),0,32)
white=(255,255,255)
blue=(0,0,255)
display.fill(white)
center_w = display_width/2
center_h = display_height/2
# Calculate possible dislocations
possible_dislocations = get_possible_dislocations(center_w, center_h, 50)
# Draw pixels on every possible dislocation, starting from the center of the display
for loc in possible_dislocations:
pygame.draw.rect(display,blue,(loc[0],loc[1],2,2))
# Run the display
while not crashed:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
clock.tick(60)
在這個例子中,角色可以移動50步。如果圍繞與中心保持相同距離的點移動,則結果爲圓形。如果你可以去那個圈內的任何地方,你可以得到磁盤的笛卡爾座標。
只需在兩個範圍的末尾添加+1即可。 Python中的範圍不是包含結束的。 – samgak
@samgak完美謝謝! –