我是Python的新手,但我发现编写代码非常有趣
dictionary_of_locations = {
'location_1': (2214, 1026), # x, y coordinates
'location_2': (2379, 1016),
'location_3': (2045, 1092),
'location_4': (2163, 1080),
'location_5': (2214, 1080),
'location_6': (2262, 1078),
}
我想运行一段代码来选择位置坐标,并按+-15随机化x和y值
我真正想要做的是:
for i in dictionary_of_locations.values():
pyautogui.click(i), print('clicking on location ' + str(i + 1) + ' !'), time.sleep(.75)
发布于 2021-02-25 11:41:39
使用random.randint
import random
loc = ... # Do whatever to get your desired coordinates
loc = (loc[0] + random.randint(-15, 15), loc[1] + random.randint(-15, 15))
或者,如果你不想只想要整数,还想要浮点数:
import random
loc = ... # Do whatever to get your desired coordinates
loc = (loc[0] + random.random() * 30 - 15, loc[1] + random.random() * 30 - 15)
发布于 2021-02-25 11:43:21
您可以使用randint(lb, ub)
获取介于下限/上界之间的随机整数
from random import randint
for loc in dictOfLoc:
newLoc = (dictOfLoc[loc][0] + randint(-15, 15),
dictOfLoc[loc][1] + randint(-15, 15))
dictOfLoc[loc] = newLoc
发布于 2021-02-25 11:55:13
示例:
import numpy as np
import time
dictionary_of_locations = {
'location_1': (2214, 1026), # x, y coordinates
'location_2': (2379, 1016),
'location_3': (2045, 1092),
'location_4': (2163, 1080),
'location_5': (2214, 1080),
'location_6': (2262, 1078),
}
def get_random(x, y):
"""
Get (x, y) and return (random_x, random_y) according to rand_range
+1 is added to high bound because randint is high exclusive [low, high)
:param x: position x
:param y: position y
:return: random values for x and y with range 15
"""
rand_range = 15 # for -/+ 15
x_low = x - rand_range
x_high = x + rand_range + 1
y_low = y - rand_range
y_high = y + rand_range + 1
rand_x = np.random.randint(low=x_low, high=x_high)
rand_y = np.random.randint(low=y_low, high=y_high)
return rand_x, rand_y
for location, positions in dictionary_of_locations.items():
current_x, current_y = positions
new_x, new_y = get_random(current_x, current_y)
print(f'clicking on {location} (x, y): ({new_x},{new_y}) !')
time.sleep(.75)
# output
# clicking on location_1 (x, y): (2209,1040) !
# clicking on location_2 (x, y): (2364,1005) !
# clicking on location_3 (x, y): (2052,1086) !
# clicking on location_4 (x, y): (2160,1092) !
# clicking on location_5 (x, y): (2222,1079) !
# clicking on location_6 (x, y): (2275,1082) !
https://stackoverflow.com/questions/66367663
复制相似问题