通过方法移动字符-python

通过方法移动字符-python,python,pygame,Python,Pygame,我试图通过调用该方法和我想移动的距离,将角色移动一定距离。到目前为止,我可以通过调用函数并放置x和y值来确定字符的位置。当用户单击鼠标时。在main方法中,我希望调用move方法。我试过两种move的实现,第一种move和第二种move_c,都不起作用。我正在使用python3和pygame 有什么建议吗 : 这是我的密码 import pygame, math from pygame.locals import * pygame.init() class Vector(): '''

我试图通过调用该方法和我想移动的距离,将角色移动一定距离。到目前为止,我可以通过调用函数并放置x和y值来确定字符的位置。当用户单击鼠标时。在main方法中,我希望调用move方法。我试过两种move的实现,第一种move和第二种move_c,都不起作用。我正在使用python3和pygame

有什么建议吗

:

这是我的密码

import pygame, math
from pygame.locals import *
pygame.init()

class Vector():
    '''

            creates operations to handle vectors such
            as direction, position, and speed
        '''
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self): # used for printing vectors
        return "(%s, %s)"%(self.x, self.y)

    def __getitem__(self, key):
        if key == 0:
            return self.x
        elif key == 1:
            return self.y
        else:
            raise IndexError("This "+str(key)+" key is not a vector key!")

    def __sub__(self, o): # subtraction
        return Vector(self.x - o.x, self.y - o.y)

    def length(self): # get length (used for normalize)
        return math.sqrt((self.x**2 + self.y**2)) 

    def normalize(self): # divides a vector by its length
        l = self.length()
        if l != 0:
            return (self.x / l, self.y / l)
        return None



class Sprite(pygame.sprite.Sprite):

    def __init__(self):
        '''
        Class:
            creates a sprite
        Parameters:
            - self
        '''
        self.image = pygame.image.load("Images/green.png").convert() # load image
        self.rect = self.image.get_rect()


        self.speed = 10 # movement speed of the sprite
        self.speedX = 0 # speed in x direction
        self.speedY = 0 # speed in y direction
        self.target = None # starts off with no target

    def set_position(self, x,y):
        self.rect.centerx= x
        self.rect.centery= y
        self.rect.center=(self.rect.centery, self.rect.centery)

    def get_position(self):
        return self.rect.center


    def move(self, distance):
        if self.target:
            direction =self.get_direction(self.target)
            position = self.get_position() # create a vector from center x,y value
            direction = Vector(direction[0], direction[1]) # and one from the target x,y
            distance = target - position # get total distance between target and position
        return distance

    def get_direction(self, target):
        '''
        Function:
            takes total distance from sprite.center
            to the sprites target
            (gets direction to move)
        Returns:
            a normalized vector
        Parameters:
            - self
            - target
                x,y coordinates of the sprites target
                can be any x,y coorinate pair in
                brackets [x,y]
                or parentheses (x,y)
        '''
        if self.target: # if the square has a target
            position = Vector(self.rect.centerx, self.rect.centery) # create a vector from center x,y value
            target = Vector(target[0], target[1]) # and one from the target x,y
            self.dist = target - position # get total distance between target and position

            direction = self.dist.normalize() # normalize so its constant in all directions
            return direction


    def distance_check(self, dist):
        '''
        Function:
            tests if the total distance from the
            sprite to the target is smaller than the
            ammount of distance that would be normal
            for the sprite to travel
            (this lets the sprite know if it needs
            to slow down. we want it to slow
            down before it gets to it's target)
        Returns:
            bool
        Parameters:
            - self
            - dist
                this is the total distance from the
                sprite to the target
                can be any x,y value pair in
                brackets [x,y]
                or parentheses (x,y)
        '''
        dist_x = dist[0] ** 2 # gets absolute value of the x distance
        dist_y = dist[1] ** 2 # gets absolute value of the y distance
        t_dist = dist_x + dist_y # gets total absolute value distance
        speed = self.speed ** 2 # gets aboslute value of the speed

        if t_dist < (speed): # read function description above
            return True


    def update(self):
        '''
        Function:
            gets direction to move then applies
            the distance to the sprite.center
            ()
        Parameters:
            - self
        '''        
        self.dir = self.get_direction(self.target) # get direction
        if self.dir: # if there is a direction to move
            if self.distance_check(self.dist): # if we need to stop
                self.rect.center = self.target # center the sprite on the target

            else: # if we need to move normal

                self.rect.centerx += (self.dir[0] * self.speed) # calculate speed from direction to move and speed constant
                self.rect.centery += (self.dir[1] * self.speed)
                self.rect.center = (round(self.rect.centerx),round(self.rect.centery)) # apply values to sprite.center

    def move_c(self,distance):
        self.dir = self.get_direction(self.target) # get direction
        if self.dir: # if there is a direction to move

            if self.distance_check(self.dist): # if we need to stop
                self.rect.center = self.target # center the sprite on the target

            else: # if we need to move normal
                self.rect.centerx += (self.dir[0] * self.speed) # calculate speed from direction to move and speed constant
                self.rect.centery += (self.dir[1] * self.speed)
                self.rect.center = (round(self.rect.centerx),round(self.rect.centery)) # apply values to sprite.center
        return distance
def main():

    screen = pygame.display.set_mode((640,480))
    pygame.display.set_caption("Test game")
    background_color = pygame.Surface(screen.get_size()).convert()
    background_color.fill((240,50,0))

##    line_points = [] # make a list for points
##    line_color = (0, 255, 255) # color of the lines

    sprite = Sprite() # create the sprite
    clock = pygame.time.Clock()
    sprite.set_position(100,400)

    running = True

    while running:
        clock.tick(30)

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

            if event.type == MOUSEBUTTONDOWN:
                  sprite.move(100)
##                  sprite.move_c(150)
##                sprite.target = event.pos # set the sprite.target to the mouse click position


        screen.blit(background_color, (0,0))

##        sprite.update() # update the sprite

        screen.blit(sprite.image, sprite.rect.topleft) # blit the sprite to the screen


        pygame.display.flip()

    pygame.quit() # for a smooth quit
if __name__ == "__main__":
    main()
精灵根本不动,更不用说50了

def move(self, distance):
        if self.target:
            direction =self.get_direction(self.target)
            position = self.get_position() # create a vector from center x,y value
            direction = Vector(direction[0], direction[1]) # and one from the target x,y
            distance = target - position # get total distance between target and position
        return distance
工作主回路

while running:
    clock.tick(30)

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

        if event.type == MOUSEBUTTONDOWN:
            sprite.target = event.pos # set the sprite.target to the mouse click position


    sprite.move_c(100)

    screen.blit(background_color, (0,0))
    screen.blit(sprite.image, sprite.rect.topleft) # blit the sprite to the screen
    pygame.display.flip()
您必须在每一帧调用
move_c()
来更改精灵的位置

顺便说一下,你可以用
sprite.update()
代替
sprite.move()
,但是
sprite.move()
不起作用


如果event.type==MOUSEBUTTONDOWN:

  • 当您按下鼠标按钮时,该值仅为一次
  • 当你一直按下按钮时,它不是真的

如果您只需要在按下鼠标按钮时执行某项操作,则必须这样做:

is_pressed = False

while running:
    clock.tick(30)

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

        if event.type == MOUSEBUTTONDOWN:
            is_pressed = True

        if event.type == MOUSEBUTTONUP:
            is_pressed = False

    if is_pressed:
         sprite.target = pygame.mouse.get_pos()
         sprite.move_c(100)

    screen.blit(background_color, (0,0))
    screen.blit(sprite.image, sprite.rect.topleft) # blit the sprite to the screen
    pygame.display.flip()
这样雪碧就会跟着老鼠


编辑:


我没有更多以前的工作代码,因为同时我做了修改-现在你只能使用箭头(左,右,上,下)来移动精灵。一次单击-一次移动(距离:100)

这次是完整代码(您必须更改位图文件名)

导入pygame、数学
从pygame.locals导入*
pygame.init()
类向量():
'''
创建处理向量的操作,例如
方向、位置和速度
'''
定义初始化(self,x,y):
self.x=x
self.y=y
def _ustr _;(self):#用于打印向量
返回“(%s,%s)”%(self.x,self.y)
def _u获取项目(自身,密钥):
如果键==0:
返回self.x
elif键==1:
回归自我
其他:
raise索引器(“此”+str(键)+“键不是向量键!”)
定义(self,o):#减法
返回向量(self.x-o.x,self.y-o.y)
定义长度(自身):#获取长度(用于规格化)
返回math.sqrt((self.x**2+self.y**2))
def normalize(self):#将向量除以其长度
l=self.length()
如果我0:
返回(自x/l、自y/l)
一无所获
类精灵(pygame.Sprite.Sprite):
定义初始化(自):
'''
类别:
创造一个精灵
参数:
-自我
'''
self.image=pygame.image.load(“ball1.png”).convert()#load image
self.rect=self.image.get_rect()
self.speed=10#精灵的移动速度
self.speedX=0#x方向的速度
自加速=0#y方向的速度
self.target=None#开始时没有目标
def设置位置(自身、x、y):
self.rect.centerx=x
self.rect.centery=y
#self.rect.center=(self.rect.centery,self.rect.centery)
def get_位置(自身):
返回自校正中心
def移动(自身、距离):
如果自我目标:
方向=self.get\u方向(self.target)
position=self.get_position()#从中心x,y值创建一个向量
方向=向量(方向[0],方向[1])#和距离目标x,y的一个
距离=自身目标-位置#获取目标和位置之间的总距离
返回距离
def get_方向(自身、目标):
'''
功能:
从sprite.center获取总距离
到精灵的目标
(获取移动的方向)
返回:
归一化向量
参数:
-自我
-目标
x、 精灵目标的y坐标
可以是任意x,y坐标对
括号[x,y]
或括号(x,y)
'''
if self.target:#如果正方形有目标
位置=向量(self.rect.centerx,self.rect.centery)#从中心x,y值创建向量
目标=向量(目标[0],目标[1])#和一个来自目标x,y的向量
self.dist=目标-位置#获取目标和位置之间的总距离
方向=self.dist.normalize()
返回方向
def距离检查(自身、距离):
'''
功能:
测试与目标之间的总距离
精灵到目标的距离小于
一段正常的距离
让精灵旅行
(这会让精灵知道它是否需要
慢下来,我们希望它慢下来
在它到达目标之前,它已经下降了)
返回:
布尔
参数:
-自我
-距离
这是到目标的总距离
向目标发射精灵
可以是中的任意x、y值对
括号[x,y]
或括号(x,y)
'''
dist_x=dist[0]**2#获取x距离的绝对值
dist_y=dist[1]**2#获取y距离的绝对值
t_dist=dist_x+dist_y#获取总绝对值距离
速度=自身。速度**2#获取速度的绝对值
如果t#u dist<(速度):#阅读上述功能说明
返回真值
def更新(自我):
'''
功能:
获取移动方向,然后应用
到精灵中心的距离
()
参数:
-自我
'''        
self.dir=self.get_direction(self.target)#get direction
if self.dir:#如果有移动的方向
如果自我距离检查(自我距离):#如果需要停车
self.rect.center=self.target#将精灵居中放置在目标上
is_pressed = False

while running:
    clock.tick(30)

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

        if event.type == MOUSEBUTTONDOWN:
            is_pressed = True

        if event.type == MOUSEBUTTONUP:
            is_pressed = False

    if is_pressed:
         sprite.target = pygame.mouse.get_pos()
         sprite.move_c(100)

    screen.blit(background_color, (0,0))
    screen.blit(sprite.image, sprite.rect.topleft) # blit the sprite to the screen
    pygame.display.flip()
import pygame, math
from pygame.locals import *
pygame.init()

class Vector():
    '''

            creates operations to handle vectors such
            as direction, position, and speed
        '''
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self): # used for printing vectors
        return "(%s, %s)"%(self.x, self.y)

    def __getitem__(self, key):
        if key == 0:
            return self.x
        elif key == 1:
            return self.y
        else:
            raise IndexError("This "+str(key)+" key is not a vector key!")

    def __sub__(self, o): # subtraction
        return Vector(self.x - o.x, self.y - o.y)

    def length(self): # get length (used for normalize)
        return math.sqrt((self.x**2 + self.y**2)) 

    def normalize(self): # divides a vector by its length
        l = self.length()
        if l != 0:
            return (self.x / l, self.y / l)
        return None



class Sprite(pygame.sprite.Sprite):

    def __init__(self):
        '''
        Class:
            creates a sprite
        Parameters:
            - self
        '''
        self.image = pygame.image.load("ball1.png").convert() # load image
        self.rect = self.image.get_rect()


        self.speed = 10 # movement speed of the sprite
        self.speedX = 0 # speed in x direction
        self.speedY = 0 # speed in y direction
        self.target = None # starts off with no target

    def set_position(self, x,y):
        self.rect.centerx= x
        self.rect.centery= y
        #self.rect.center=(self.rect.centery, self.rect.centery)

    def get_position(self):
        return self.rect.center


    def move(self, distance):
        if self.target:
            direction = self.get_direction(self.target)
            position = self.get_position() # create a vector from center x,y value
            direction = Vector(direction[0], direction[1]) # and one from the target x,y
            distance = self.target - position # get total distance between target and position
        return distance

    def get_direction(self, target):
        '''
        Function:
            takes total distance from sprite.center
            to the sprites target
            (gets direction to move)
        Returns:
            a normalized vector
        Parameters:
            - self
            - target
                x,y coordinates of the sprites target
                can be any x,y coorinate pair in
                brackets [x,y]
                or parentheses (x,y)
        '''
        if self.target: # if the square has a target
            position = Vector(self.rect.centerx, self.rect.centery) # create a vector from center x,y value
            target = Vector(target[0], target[1]) # and one from the target x,y
            self.dist = target - position # get total distance between target and position

            direction = self.dist.normalize() # normalize so its constant in all directions
            return direction


    def distance_check(self, dist):
        '''
        Function:
            tests if the total distance from the
            sprite to the target is smaller than the
            ammount of distance that would be normal
            for the sprite to travel
            (this lets the sprite know if it needs
            to slow down. we want it to slow
            down before it gets to it's target)
        Returns:
            bool
        Parameters:
            - self
            - dist
                this is the total distance from the
                sprite to the target
                can be any x,y value pair in
                brackets [x,y]
                or parentheses (x,y)
        '''
        dist_x = dist[0] ** 2 # gets absolute value of the x distance
        dist_y = dist[1] ** 2 # gets absolute value of the y distance
        t_dist = dist_x + dist_y # gets total absolute value distance
        speed = self.speed ** 2 # gets aboslute value of the speed

        if t_dist < (speed): # read function description above
            return True


    def update(self):
        '''
        Function:
            gets direction to move then applies
            the distance to the sprite.center
            ()
        Parameters:
            - self
        '''        
        self.dir = self.get_direction(self.target) # get direction
        if self.dir: # if there is a direction to move
            if self.distance_check(self.dist): # if we need to stop
                self.rect.center = self.target # center the sprite on the target

            else: # if we need to move normal

                self.rect.centerx += (self.dir[0] * self.speed) # calculate speed from direction to move and speed constant
                self.rect.centery += (self.dir[1] * self.speed)
                self.rect.center = (round(self.rect.centerx),round(self.rect.centery)) # apply values to sprite.center

    def move_c(self,distance):
        self.dir = self.get_direction(self.target) # get direction
        if self.dir: # if there is a direction to move

            if self.distance_check(self.dist): # if we need to stop
                self.rect.center = self.target # center the sprite on the target

            else: # if we need to move normal
                self.rect.centerx += (self.dir[0] * self.speed) # calculate speed from direction to move and speed constant
                self.rect.centery += (self.dir[1] * self.speed)
                self.rect.center = (round(self.rect.centerx),round(self.rect.centery)) # apply values to sprite.center
        return distance

    def move_d(self):
        if self.target:
            if abs(self.rect.x - self.target.x) > abs(self.speedX):
                self.rect.x += self.speedX
            else:
                self.rect.x = self.target.x

            if abs(self.rect.y - self.target.y) > abs(self.speedY):
                self.rect.y += self.speedY
            else:
                self.rect.y = self.target.y

            if self.rect == self.target:
                self.target = None

    def set_move_left(self, distance):
        if not self.target: 
            self.target = self.rect.copy()
            self.target.centerx -= distance 
            self.speedX = -self.speed
            self.speedY = 0

    def set_move_right(self, distance):
        if not self.target: 
            self.target = self.rect.copy()
            self.target.centerx += distance 
            self.speedX = self.speed
            self.speedY = 0

    def set_move_up(self, distance):
        if not self.target: 
            self.target = self.rect.copy()
            self.target.centery -= distance 
            self.speedX = 0
            self.speedY = -self.speed

    def set_move_down(self, distance):
        if not self.target: 
            self.target = self.rect.copy()
            self.target.centery += distance 
            self.speedX = 0
            self.speedY = self.speed

    def set_move(self, distance, pos):
        if not self.target: 
            self.target = self.rect.copy()
            dx = (pos[0] - self.rect.x)
            dy = (pos[1] - self.rect.y)

            if dx == 0 :
                ay = 0
            else:
                ay = float(distance)/dx

            if dy == 0 :
                ax = 0
            else:
                ax = float(dx)/dy

            self.target.centerx += distance * ax
            self.target.centery += distance * ay
            self.speedX = self.speed * ax
            self.speedY = self.speed * ay

            print "dx/dy:", dx, dy,
            print "ax/ay:", ax, ay

def main():

    screen = pygame.display.set_mode((640,480))
    pygame.display.set_caption("Test game")
    background_color = pygame.Surface(screen.get_size()).convert()
    background_color.fill((240,50,0))

##    line_points = [] # make a list for points
##    line_color = (0, 255, 255) # color of the lines

    sprite = Sprite() # create the sprite
    clock = pygame.time.Clock()
    sprite.set_position(100,400)

    running = True

    is_pressed = False

    while running:
        clock.tick(30)

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

            elif event.type == MOUSEBUTTONDOWN:
                #sprite.set_move(100, event.pos)
                pass

            elif event.type == KEYDOWN:
                if event.key == K_LEFT:                 
                    sprite.set_move_left(100)
                elif event.key == K_RIGHT:                  
                    sprite.set_move_right(100)
                elif event.key == K_UP:
                    sprite.set_move_up(100)
                elif event.key == K_DOWN:
                    sprite.set_move_down(100)


        sprite.move_d()

        screen.blit(background_color, (0,0))
        screen.blit(sprite.image, sprite.rect.topleft) # blit the sprite to the screen
        pygame.display.flip()

    pygame.quit() # for a smooth quit

if __name__ == "__main__":
    main()