简体   繁体   中英

How can I loop over random numbers to get coordinates for my class?

I need a loop over all of my clans, which are instances of a class. Each clan needs to be assigned a position, ax and ay coordinate. Preferably as two lists or as a single tuple (but no idea how I specify that). This is how it works for the 1st clan. Afterwards I always have to check, if the position is already assigned. If so, you have to search for a new position until it is free. I then coded my class like this:

width = 20
height = 20
no_of_clans = 50

import random

class clan:
    def __init__(self, index, position_list):
        self.index = index
        self.position_list = position_list
        
        def index(no_of_clans):
            return list(range(1, no_of_clans +1))
        
        def position_list(self):
            for i in range(1, no_of_clans +1):
                positions = ()
                if i ==1: #i can do it either like this
                    positions = [(random.randint(0, width)), (random.randint(0, height))]
                    positions.append(x,y)
                else: #or like this, I do not know, which one is better, both are running
                    x = (random.randint(0, width))
                    y = (random.randint(0, height))
                    #check if x and y not already used
                    #assert
                    positions.append(x,y)
            return positions


print(positions)
  1. how can I assign positions randomly when also using 0.5 steps? I always get an error message.
  2. I never get a list of my positions back, but I do not know what I did wrong.

I know those are probably fairly basic questions but I am quite new to python an already searched for 5h today and I really do ot know where to start anymore. I would be really happy if someon could help me. Thank you so much in advance <3

I found the answer to my original question in this post: Coordinates of the edges of a honeycomb grid in python

Will update if I am finished with the class-thing:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM