如何使精灵在碰撞中成为一个圆圈

时间:2019-03-03 13:10:56

标签: python pygame

这段代码是一个基本的空间模拟,我正在尝试制作,因此,如果您的鼠标移过一个行星,它将显示该行星的信息。但此刻碰撞是一个正方形。我如何做到这一点,所以碰撞只有在它飞过地球而不是整个正方形时才会发生。

#import the library

import pygame,math,random


#initialise the engine
pygame.init()


#classes
class planet(pygame.sprite.Sprite):

   def __init__(self,name,colour,distance,eccentricity,radius,x,y,angle,orbitperiod,filename):
    pygame.sprite.Sprite.__init__(self)
    self.screen = screen
    self.name = name
    self.colour = colour
    self.distance = distance
    self.eccentricity = eccentricity
    self.radius = radius
    self.x = x
    self.y = y
    self.angle = angle
    self.orbitperiod = orbitperiod
    self.filename = filename


    self.image = pygame.image.load(self.filename).convert_alpha()

    self.image = pygame.transform.scale(self.image,[int(self.radius),int(self.radius)])



    self.rect = self.image.get_rect()


class slider():

   def __init__(self,name,intval,minval,maxval,pos):
    self.name = name
    self.intval = intval
    self.minval = minval
    self.maxval = maxval
    self.xpos = 1520
    self.ypos = pos
    self.surf = pygame.surface.Surface((250, 50))
    self.hit = False



    self.txt_surf = font.render(name, 1, Black)
    self.txt_rect = self.txt_surf.get_rect(center=(125, 15))



    #slider background #

    self.surf.fill((Blue))
    pygame.draw.rect(self.surf, Black, [0, 0, 250, 75], 3)
    pygame.draw.rect(self.surf, Blueviolet, [10, 10, 230, 10], 0)
    pygame.draw.rect(self.surf, Blueviolet, [10, 10, 230, 10], 1)
    pygame.draw.rect(self.surf, White, [10, 30, 230, 5], 0)

    self.surf.blit(self.txt_surf, self.txt_rect)

    # button surface #
    self.button_surf = pygame.surface.Surface((20, 20))
    self.button_surf.fill(Transparent)
    self.button_surf.set_colorkey(Transparent)
    pygame.draw.circle(self.button_surf,Black, (10, 10), 6, 0)
    pygame.draw.circle(self.button_surf,Green, (10, 10), 4, 0)

   def draw(self):

    # static

    surf = self.surf.copy()

    # dynamic

    pos = (10+int((self.intval-self.minval)/(self.maxval-self.minval)*230), 33)
    self.button_rect = self.button_surf.get_rect(center=pos)
    surf.blit(self.button_surf, self.button_rect)
    self.button_rect.move_ip(self.xpos, self.ypos)

    # screen

    screen.blit(surf, (self.xpos, self.ypos))


   def move(self):
    self.intval = (pygame.mouse.get_pos()[0] - self.xpos - 10) / 230 * (self.maxval - self.minval) + self.minval


##      print(self.intval)
    if self.intval < self.minval:
         self.intval = self.minval
    if self.intval > self.maxval:
         self.intval = self.maxval


class Button:
   def __init__(self, x, y, width, height, colour, surface, letter):
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.colour = colour
    self.surface = surface
    self.letter = letter

   def is_pressed(self):
    mouse_position = pygame.mouse.get_pos()
    mouse_x = mouse_position[0]
    mouse_y = mouse_position[1]
    if mouse_x > self.x:
         if mouse_x < self.x + self.width:
            if mouse_y > self.y:
                 if mouse_y < self.y + self.height:

                    mouse_click = pygame.mouse.get_pressed()
                    left_click = mouse_click[0]
                    if left_click:
                         self.colour = (0,0,0)
                         return True
    self.colour = (Blueviolet)
    return False

   def draw_button(self):
    pygame.draw.rect(self.surface, self.colour,(self.x,self.y, self.width, self.height))
    font = pygame.font.SysFont('Calbri',15,True,False)
    text = font.render(self.letter, True, Black)
    text_rect = text.get_rect(center=(self.x+self.width/2,self.y+self.height/2))
    screen.blit(text, text_rect)




def addtostring(input_word,newletter):
   return input_word + newletter


def orbit(planet):
   if planet.name == "Planet X":
    a = planetxdistance.intval*(1.496*10**8)
    e = planetxeccentricity.intval
    angle_radians = math.radians(planet.angle)
    angle=angle_radians*planetxorbitperiod.intval*speedmodifier
    r = a*(1-(e*math.cos(angle)))

    planet.x = int(math.cos(angle)*r/10**zoom.intval)
    planet.y = int(math.sin(angle)*r/10**zoom.intval)




    planet.angle+=pauseplaymodifier
    planet.x +=(centre[0]-(planet.radius/2))
    planet.y +=(centre[1]-(planet.radius/2))
    planet.rect.x = planet.x
    planet.rect.y = planet.y

   else:
##    print(planet.x,planet.y)
    a = planet.distance*(1.496*10**8)
    e = planet.eccentricity
    angle_radians = math.radians(planet.angle)
    angle=angle_radians*planet.orbitperiod*speedmodifier
    r = a*(1-(e*math.cos(angle)))

    planet.x = int(math.cos(angle)*r/10**(zoom.intval))
    planet.y = int(math.sin(angle)*r/10**(zoom.intval))




    planet.angle+=pauseplaymodifier
    planet.x +=centre[0]-(planet.radius/2)
    planet.y +=centre[1]-(planet.radius/2)

    planet.rect.x = planet.x
    planet.rect.y = planet.y

#define colours



White = (255, 255, 255)
Black = (0, 0, 0)
Red = (255, 50, 50)
Yellow = (255, 255, 0)
Green = (0, 255, 50)
Blue = (50, 50, 255)
Grey = (200, 200, 200)
Orange = (200, 100, 50)
Cyan = (0, 255, 255)
Magenta = (255, 0, 255)
Blueviolet = (138,43,226)
Random = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
Transparent = (1,1,1)

moveticks = 0
Paused = False
pauseplaymodifier = 1
speedmodifier = 1
years = 1

newletter = ""
input_word = ""

# sprite

planet_listsprite = pygame.sprite.Group()
all_sprites_list = pygame.sprite.Group()

counter = 0
spritehit = False


#window

size = (1800,800)
screen = pygame.display.set_mode(size)
centre = [800,400]

background = pygame.image.load("Space.png").convert()

# planets

planet_draw =[]

# slider

font = pygame.font.SysFont("Calibri", 15)
zoom = slider("Zoom",5,5,8,120)
planetxdistance = slider("Distance from sun",0,0,40,400)
planetxeccentricity = slider("Eccentricity",0.5,0,1,450)
planetxradius = slider("Radius of planet",7,1,600,500)
planetxorbitperiod = slider("Speed of orbit",1,0,6,550)
slides = [zoom,planetxdistance,planetxeccentricity,planetxradius,planetxorbitperiod]

# buttons
buttons = []

paused = False

play = Button(1520,60,100,50,Blueviolet,screen,"Play")
pause = Button(1670,60,100,50,Blueviolet,screen,"Pause")

pluszoom = Button(1705,180,55,50,Blueviolet,screen,"+")
minuszoom = Button(1520,180,55,50,Blueviolet,screen,"-")

buttons = [play,pause,pluszoom,minuszoom]

# moving scroll thing

intpos = []
finpos = []
differencex = ""
differencey = ""


# screen,name,colour,distance,eccentricity,radius,x,y,angle,orbit period
planet_list =[
        ["Planet X",(random.randint(0,255),random.randint(0,255),random.randint(0,255)),planetxdistance.intval,planetxeccentricity.intval,planetxradius.intval,0,0,0,planetxorbitperiod.intval,"PlanetX.png"],
        ['Sun', Red,0,0,695,0,0,0,1,"Sun.png"],
        ['Mercury',(random.randint(0,255),random.randint(0,255),random.randint(0,255)),0.387,0.2056,2.440,0,0,7.005,4.1521,"Mercury.png"],
        ['Venus',(random.randint(0,255),random.randint(0,255),random.randint(0,255)),0.723,0.0068,6.052,0,0,3.3947,1.6255,"Venus.png"],
        ['Earth',(random.randint(0,255),random.randint(0,255),random.randint(0,255)),1,0.0167,6.371,0,0,0,1,"Earth.png"],
##          ['Moon',(random.randint(0,255),random.randint(0,255),random.randint(0,255)),0.00256957534,0.0549,1.737,0,0,0,13.51851852,"Moon.png"],
        ['Mars',(random.randint(0,255),random.randint(0,255),random.randint(0,255)),1.524,0.0934,3.390,0,0,1.851,0.5316,"Mars.png"],
        ['Jupiter',(random.randint(0,255),random.randint(0,255),random.randint(0,255)),5.203,0.0484,69.911,0,0,1.305,0.0843,"Jupiter.png"],
        ['Saturn',(random.randint(0,255),random.randint(0,255),random.randint(0,255)),9.537,0.0542,58.232,0,0,2.484,0.03396,"Saturn.png"],
        ['Uranus',(random.randint(0,255),random.randint(0,255),random.randint(0,255)),19.191,0.0472,25.362,0,0,0.770,0.0119027,"Uranus.png"],
        ['Neptune',(random.randint(0,255),random.randint(0,255),random.randint(0,255)),30.069,0.0086,24.622,0,0,1.769,0.0068447,"Neptune.png"],
        ]

for i in range(50):
   planet_list.append(['Astoroid',Random,(random.randrange(2200, 3200))/1000,0.05,1,0,0,random.randint(0,360),1,"Astoroid.png"])

for i in planet_list:
   planet_draw.append(planet(i[0],i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8],i[9]))

for i in range(len(planet_list)):
    planet_listsprite.add(planet_draw)
    all_sprites_list.add(planet_draw)


targetfps = 60.00


#set window title

pygame.display.set_caption("Orbit Simulator")

#loop unti the user clicks the close button

done = False

#used to manage how fast the screen updates

clock = pygame.time.Clock()

#------ Main program Loop ------



while not done:

   #--- Main event loop
    for event in pygame.event.get():
        pos = pygame.mouse.get_pos()
        if event.type == pygame.QUIT:
            done = True

        if event.type == pygame.MOUSEBUTTONDOWN:


            pos = pygame.mouse.get_pos()
            xpos = pos[0]
            ypos = pos[1]
            for i in slides:
                if i.button_rect.collidepoint(pos):
                    i.hit = True

        elif event.type == pygame.MOUSEBUTTONUP:
            pos = pygame.mouse.get_pos()
            xpos = pos[0]
            ypos = pos[1]
            for i in slides:
                i.hit = False
        if event.type ==pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                if moveticks == 10:
                    centre[1]-=1
                    moveticks = 0
                else:
                    moveticks+=1

            elif event.key == pygame.K_DOWN:
                if moveticks ==10:
                    centre[1]+=1
                    moveticks = 0
                else:
                    moveticks+=1
            elif event.key == pygame.K_LEFT:
                if moveticks == 10:
                    centre[0]-=1
                    moveticks = 0
                else:
                    moveticks-=1
            elif event.key == pygame.K_RIGHT:
                print(moveticks)

                if moveticks==10:
                    centre[0]+=1
                    moveticks =0
                else:
                    moveticks+1

        for i in planet_listsprite:
            if i.rect.collidepoint(pos[0],pos[1]):
                spritehit = True
                print("Hit",counter)
                counter+=1
            else:
                spritehit = False




   #------ Game logic should go here ------
        if pause.is_pressed():
            pause.colour = Blue
            pauseplaymodifier = 0
        if play.is_pressed():
            play.colour = Blue
            pauseplaymodifier = 1
        if pluszoom.is_pressed():
            speedmodifier+=1
        if minuszoom.is_pressed():
            if speedmodifier == 1:
                pass
            elif speedmodifier >1:
                speedmodifier= speedmodifier-1
            elif speedmodifier <1:
                pass


# STUCK ON ZOOM AND MAKING IT DECREAASEE


    for planet in all_sprites_list:
        orbit(planet)

    for i in slides:
        if i.hit:
            i.move()


#   #------ Drawing code should go here -------

    screen.fill(Black)

    screen.blit(background,(0,0))

    for i in all_sprites_list:
        all_sprites_list.draw(screen)


# menu
    pygame.draw.rect(screen,White,[1500,0,1800,800])
    pygame.draw.rect(screen,Blueviolet,[1500,0,300,800],5)
    font = pygame.font.SysFont('Calibri',20,True,False)
    text = font.render("Menu",True,Black)
    screen.blit(text,[1520,25])
# slider
    for s in slides:
        s.draw()

#buttons
    for i in buttons:
        i.draw_button()
# pause play
    pygame.draw.rect(screen,Black,[1570,180,135,50])
    font = pygame.font.SysFont('Calibri',25,True,False)
    text = font.render(str(speedmodifier),True,White)
    screen.blit(text,[1605,200])


# input text
    font = pygame.font.SysFont('Calibri',20,True,False)
    text = font.render(input_word,True,Black)
    screen.blit(text,[1620,300])

    font = pygame.font.SysFont('Calibri',20,True,False)
    text = font.render("Input word:",True,Black)
    screen.blit(text,[1510,300])


   #update the screen

    pygame.display.flip()


   #------ Limit to 60 frames per second ------

    clock.tick(60)

#------ When the loop ends, quit ------


pygame.quit()

如果您需要这些代码,则需要一些图像,我也可以发送给您

0 个答案:

没有答案