Python 如何让对象以不同的模式移动

Python 如何让对象以不同的模式移动,python,pygame,Python,Pygame,对于我的代码,我希望小鸡(敌人)以4种不同的方式移动: 垂直、水平、对角和跟随玩家(猪) 每只鸡都应该有自己的动作,并且独立地移动。只有两只小鸡能成对角走 我只对它们的垂直和水平运动进行了编程,但它们存在问题;有时,它们都水平移动,有时,垂直移动。有时它们根本不动 这是我的密码: def game_loop(): x_change = 0 y_change = 0 foodCounter = 0 Score = 0 list =

对于我的代码,我希望小鸡(敌人)以4种不同的方式移动:

垂直、水平、对角和跟随玩家(猪)

每只鸡都应该有自己的动作,并且独立地移动。只有两只小鸡能成对角走

我只对它们的垂直和水平运动进行了编程,但它们存在问题;有时,它们都水平移动,有时,垂直移动。有时它们根本不动

这是我的密码:

def game_loop():

    x_change = 0
    y_change = 0
    foodCounter = 0
    Score = 0           
    list =         ["Vertical","Vertical","Horizontal","Horizontal","Follow","Diagonal1","Diagonal2"]
    baddies = []
    item = 0

    x = (display_width * 0.45)
    y = (display_height * 0.8)

    foodx = random.randrange(48, display_width - 48)
    foody = random.randrange(54, display_height - 54)

    gameExit = False
    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -8
                if event.key == pygame.K_RIGHT:
                    x_change = 8
                if event.key == pygame.K_UP:
                    y_change = -8
                if event.key == pygame.K_DOWN:
                    y_change = 8

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    y_change = 0

        if x > 705:
            x_change = 0
            x = 705
        if x < -10:
            x_change = 0
            x = -10
        if y < -15:
            y_change = 0
            y = -15
        if y > 505:
            y_change = 0
            y = 505

        x += x_change
        y += y_change

        gameDisplay.fill(white)
        gameDisplay.blit(background,(-50,-50))

        food = pygame.Rect(foodx, foody,48 , 54)

        if foodCounter == 0:
            gameDisplay.blit(foodImage, food)

        player = pygame.Rect(x, y,108,105)

        if player.colliderect(food):
            foodCounter += -1
            Score += 1
            foodx = random.randrange(48, display_width - 48)
            foody = random.randrange(54, display_height - 54)
            foodCounter += 1

            item = random.randint(1, len(list))
            print(item)

            if item == 1 or item == 2:
                newchicken = {'rect':pygame.Rect(random.randint(0,display_width-45),0,45,63),
                          'surface':pygame.transform.scale(enemyImage,(45,63)),
                          'vertical': "vertical",
                          'down': "down"
                          }
                item = 0
                baddies.append(newchicken)

            if item == 3 or item == 4:
                newchicken = {'rect':pygame.Rect(0,random.randint(0,display_height-45),45,63),
                          'surface': pygame.transform.scale(enemyImage, (45,63)),
                          'horizontal': "horizontal",
                          'right': "right"
                          }
                item = 0
                baddies.append(newchicken)

            if item == 6:
                newchicken = {'rect':pygame.Rect(200,0,45,63),
                          'surface':pygame.transform.scale(enemyImage,(45,63)),
                          'diagonal1': "diagonal1"
                          }
                if "Diagonal1" in list:
                    list.remove("Diagonal1")

                item = 0
                baddies.append(newchicken)

            if len(list) == 7:
                if item == 7:
                    newchicken = {'rect':pygame.Rect(100,600,45,63),
                              'surface':pygame.transform.scale(enemyImage,(45,63)),
                              'diagonal2': "diagonal2"
                          }
                    if "Diagonal2" in list:
                        list.remove("Diagonal2")

                    item = 0
                    baddies.append(newchicken)
            if len(list) == 6:
                if item == 6:
                    newchicken = {'rect':pygame.Rect(100,600,45,63),
                              'surface':pygame.transform.scale(enemyImage,(45,63)),
                              'diagonal2': "diagonal2"
                          }
                    if "Diagonal2" in list:
                        list.remove("Diagonal2")

                    item = 0
                    baddies.append(newchicken)

        gameDisplay.blit(pigImage, player)

        for b in baddies:
            gameDisplay.blit(b['surface'],b['rect'])

        for b in baddies:
            if "vertical" in newchicken:
                if "down" in newchicken:
                    if not b['rect'].bottom >= 600:
                        b['rect'].move_ip(0, 2)
                    if b['rect'].bottom >= 600 :
                        del newchicken['down']
                        newchicken["up"] = "up"
                if "up" in newchicken:
                    if not b['rect'].top <= 0:
                        b['rect'].move_ip(0,-2)
                    if b['rect'].top <= 0:
                        del newchicken ['up']
                        newchicken["down"] = "down"

            if "horizontal" in newchicken:
                print ("horizontal")
                if "right" in newchicken:
                    if not b['rect'].right >= 800:
                        b['rect'].move_ip(2,0)
                    if b['rect'].right >= 800:
                        del newchicken['right']
                        newchicken['left'] = "left"
                if "left" in newchicken:
                    if not b['rect'].left <= 0:
                        b['rect'].move_ip(-2,0)
                    if b['rect'].left <= 0:
                        del newchicken ['left']
                        newchicken['right'] = "right"

        pygame.display.update()
        clock.tick(60)

game_loop()    
def game_loop():
x_变化=0
y_变化=0
foodCounter=0
分数=0
列表=[“垂直”、“垂直”、“水平”、“水平”、“跟随”、“对角线1”、“对角线2”]
坏人=[]
项目=0
x=(显示宽度*0.45)
y=(显示高度*0.8)
foodx=random.randrange(48,显示宽度-48)
foody=random.randrange(54,显示高度-54)
gameExit=False
不退出游戏时:
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
pygame.退出
退出
如果event.type==pygame.KEYDOWN:
如果event.key==pygame.K_左:
x_变化=-8
如果event.key==pygame.K_RIGHT:
x_变化=8
如果event.key==pygame.K_UP:
y_变化=-8
如果event.key==pygame.K_向下:
y_变化=8
如果event.type==pygame.KEYUP:
如果event.key==pygame.K_左或event.key==pygame.K_右:
x_变化=0
如果event.key==pygame.K_向上或event.key==pygame.K_向下:
y_变化=0
如果x>705:
x_变化=0
x=705
如果x<-10:
x_变化=0
x=-10
如果y<-15:
y_变化=0
y=-15
如果y>505:
y_变化=0
y=505
x+=x_变化
y+=y_变化
游戏显示。填充(白色)
blit(背景,(-50,-50))
food=pygame.Rect(foodx,foody,48,54)
如果foodCounter==0:
游戏显示.blit(食品图像,食品)
player=pygame.Rect(x,y,108105)
如果玩家.colliderect(食物):
foodCounter+=-1
分数+=1
foodx=random.randrange(48,显示宽度-48)
foody=random.randrange(54,显示高度-54)
foodCounter+=1
item=random.randint(1,len(列表))
打印(项目)
如果项目==1或项目==2:
newchicken={'rect':pygame.rect(random.randint(0,display_width-45),0,45,63),
“曲面”:pygame.transform.scale(enemyImage,(45,63)),
‘垂直’:‘垂直’,
“向下”:“向下”
}
项目=0
坏人。追加(新鸡)
如果项目==3或项目==4:
newchicken={'rect':pygame.rect(0,random.randint(0,display_height-45),45,63),
“曲面”:pygame.transform.scale(enemyImage,(45,63)),
‘水平’:‘水平’,
“对”:“对”
}
项目=0
坏人。追加(新鸡)
如果项目==6:
newchicken={'rect':pygame.rect(200,0,45,63),
“曲面”:pygame.transform.scale(enemyImage,(45,63)),
“对角线1”:“对角线1”
}
如果列表中有“对角线1”:
列表。删除(“对角线1”)
项目=0
坏人。追加(新鸡)
如果len(list)==7:
如果项目==7:
newchicken={'rect':pygame.rect(100600,45,63),
“曲面”:pygame.transform.scale(enemyImage,(45,63)),
“对角线2”:“对角线2”
}
如果列表中有“对角线2”:
列表。删除(“对角线2”)
项目=0
坏人。追加(新鸡)
如果len(list)==6:
如果项目==6:
newchicken={'rect':pygame.rect(100600,45,63),
“曲面”:pygame.transform.scale(enemyImage,(45,63)),
“对角线2”:“对角线2”
}
如果列表中有“对角线2”:
列表。删除(“对角线2”)
项目=0
坏人。追加(新鸡)
blit(pigImage,播放器)
对于坏人中的b:
blit(b['surface',b['rect'])
对于坏人中的b:
如果NewChick中的“垂直”:
如果NewChick中出现“down”:
如果不是b['rect']。底部>=600:
b['rect'].移动ip(0,2)
如果b['rect'].bottom>=600:
德尔纽基克[下]
新鸡[“向上”]=“向上”
如果在newchicken中为“up”:
如果不是b['rect'].top=800:
德尔纽基克['对']
新鸡['left']=“left”
如果在newchicken中为“左”:

如果不是b['rect'].left您的代码不起作用,因为您在迭代
坏人时总是在
newchicken
中检查密钥,而我想您应该改为检查
b

但是你应该做的是改变你的代码,把游戏中不同的逻辑问题分开。此外,只需使用类而不是dict来对属于一起的数据和行为进行分组


让我们想一想:

我们有某种实体,基本上
newchicken = {'rect':pygame.Rect(100,600,45,63),
              'surface':pygame.transform.scale(enemyImage,(45,63)),
              'diagonal2': "diagonal2"
             }
class Animal(pg.sprite.Sprite):
    def __init__(self, color, pos, logic, *groups):
        super().__init__(*groups)
        self.image = pg.surface.Surface((40, 40))
        self.image.fill(color)
        self.rect = self.image.get_rect(topleft=pos)
        self.logic = logic
        self.direction = pg.Vector2((0, 0))

    def update(self):
        self.logic(self)
def move_vertical(animal):
    if animal.direction.length() == 0:
        animal.direction = pg.Vector2(5, 0)

    animal.rect.move_ip(*animal.direction)
    if not screen_rect.contains(animal.rect):
        animal.direction *= -1
        animal.rect.move_ip(animal.direction)

def move_horizontal(animal):
    if animal.direction.length() == 0:
        animal.direction = pg.Vector2(0, 5)

    animal.rect.move_ip(*animal.direction)
    if not screen_rect.contains(animal.rect):
        animal.direction *= -1
        animal.rect.move_ip(animal.direction)

def move_to_mouse(animal):
    pos = pg.mouse.get_pos()
    v = pg.Vector2(pos) - pg.Vector2(animal.rect.center)
    if v.length() > 0:
        v.normalize_ip()
    v *= 5
    animal.rect.move_ip(*v)
import pygame as pg
pg.init()
clock = pg.time.Clock()
running = True
screen = pg.display.set_mode((640, 480))
screen.fill((255, 255, 255))
screen_rect = screen.get_rect()

def move_vertical(animal):
    if animal.direction.length() == 0:
        animal.direction = pg.Vector2(5, 0)

    animal.rect.move_ip(*animal.direction)
    if not screen_rect.contains(animal.rect):
        animal.direction *= -1
        animal.rect.move_ip(animal.direction)

def move_horizontal(animal):
    if animal.direction.length() == 0:
        animal.direction = pg.Vector2(0, 5)

    animal.rect.move_ip(*animal.direction)
    if not screen_rect.contains(animal.rect):
        animal.direction *= -1
        animal.rect.move_ip(animal.direction)

def move_to_mouse(animal):
    pos = pg.mouse.get_pos()
    v = pg.Vector2(pos) - pg.Vector2(animal.rect.center)
    if v.length() > 0:
        v.normalize_ip()
    v *= 5
    animal.rect.move_ip(*v)

class Animal(pg.sprite.Sprite):
    def __init__(self, color, pos, logic, *groups):
        super().__init__(*groups)
        self.image = pg.surface.Surface((40, 40))
        self.image.fill(color)
        self.rect = self.image.get_rect(topleft=pos)
        self.logic = logic
        self.direction = pg.Vector2((0, 0))

    def update(self):
        self.logic(self)

sprites = pg.sprite.Group()
Animal(pg.color.Color('yellow'), ( 10,  10), move_vertical,   sprites)
Animal(pg.color.Color('red'),    (200, 400), move_vertical,   sprites)
Animal(pg.color.Color('orange'), (500, 100), move_horizontal, sprites)
Animal(pg.color.Color('brown'),  (100, 200), move_to_mouse,   sprites)

while running:

    for e in pg.event.get():
        if e.type == pg.QUIT:
            running = False

    sprites.update()

    screen.fill((255, 255, 255))
    sprites.draw(screen)
    pg.display.update()

    clock.tick(60)