How to set ships randomly using pygame
Question:
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
Answers:
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 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
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.