如何使用Pygame随机设置船只位置。

huangapple go评论64阅读模式
英文:

How to set ships randomly using pygame

问题

我想使用Pygame设置船只,就像图像中那样。但是我只从#right(在长循环中)获得坐标。

如何修复这个问题?

英文:

I want to set ships like in image using pygame.
However I got coordinates only from #right(in long for loop).

How can I fix this?

for i in range(1,6):
    while True:
        x,y = random.randrange(14,24,1),random.randrange(1,11,1)
        angle = ship_angle[random.randrange(0,4,1)]
        X,Y = x+i*math.cos(angle),y+i*math.sin(angle)
        
        if  (14 <= X <= 24) and (1 <= Y <= 11) and (not((X,Y) in ai_ships)):
            #down
            if (x == X) and (y < Y):
                for d in range(i):
                    ai_ships.add((x*TILE,(y+d)*TILE))
                break
            #up
            if (x == X) and (y > Y):
                for d in range(i):
                    ai_ships.add((x*TILE,(y-d)*TILE))
                break
            #right
            if (y == Y) and (x < X):
                for d in range(i):
                    ai_ships.add(((x+d)*TILE,y*TILE))
                break
            #left
            if (y == Y) and (x > X):
                for d in range(i):
                    ai_ships.add(((x-d)*TILE,y*TILE))
                break
              
        else:
            continue

如何使用Pygame随机设置船只位置。

答案1

得分: 1

I don't know if this is the only problem, but math.cos(), sin() uses radians, so you want to use, for example:

angle = math.radians(ship_angle[random.randrange(0,4,1)])
      # ^^^^^^^^^^^^ Add this
X,Y = x+i*math.cos(angle),y+i*math.sin(angle)

This will convert your degrees to radians before calling the sin() and cos() functions.

英文:

I don't know if this is the only problem, but math.cos(), sin() uses radians, so you want to use, for example:

angle = math.radians(ship_angle[random.randrange(0,4,1)])
      # ^^^^^^^^^^^^ Add this
X,Y = x+i*math.cos(angle),y+i*math.sin(angle)

This will convert your degrees to radians before calling the sin() and cos() functions.

huangapple
  • 本文由 发表于 2023年2月27日 10:59:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576429.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定