PyGame 人物静态与动态的移动方式,以及鼠标与人物触碰

实现人物移动时静态与动态的切换展示,并与鼠标触碰,鼠标闪动

在这里插入图片描述

  1. 人物的静态动态移动,
  2. 鼠标碰撞人物则闪烁鼠标指针
  • 增加了主角 和 指针 以及碰撞三个类
  • 代码没啥难点 就是开关多
# 鼠标开关 ===================
黄指针闪动 = False
# 主角人物开关 ============================================
动态图片开关 = False
目前动态位置 = False
主角移动开关 = False
静态图片开关 = True
目前静态位置 = "默认静态图片"

最大移动范围 = 60000  # 人物的移动边界 


class 精灵类(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
class 指针(精灵类):
    def __init__(self,left,top):
        self.image = pygame.image.load('img/指针手.png').convert_alpha()
        self.黄指针手 = [pygame.image.load("img/黄指针手{0}.png".format(i)).convert_alpha() for i in range(1, 4)]
        self.index = 0
    def 展示指针(self):
        screen.blit(self.image, (鼠标_x,鼠标_y) )
    def 黄闪指针闪动(self):
        screen.blit(self.黄指针手[self.index % 3], (鼠标_x, 鼠标_y))
        self.index += 1

class 主角人物():
    def __init__(self, left, top):
        self.images = {
            "向下走": [pygame.image.load("img/无名小子 ({0}).png".format(i)).convert_alpha() for i in range(1, 4)],
            "向左走": [pygame.image.load("img/无名小子 ({0}).png".format(i)).convert_alpha() for i in range(5, 8)],
            "向右走": [pygame.image.load("img/无名小子 ({0}).png".format(i)).convert_alpha() for i in range(11, 14)],
            "向上走": [pygame.image.load("img/无名小子 ({0}).png".format(i)).convert_alpha() for i in range(8, 11)]}
        self.index = 0
        self.步数 = 66
        self.direction = "向上走"
        self.image = self.images[self.direction]
        self.rect = self.image[0].get_rect()

        self.imag = {
            "默认静态图片": pygame.image.load("img/无名小子 (2).png"),
            "向下走": pygame.image.load("img/无名小子 (2).png"),
            "向左走": pygame.image.load("img/无名小子 (6).png"),
            "向右走": pygame.image.load("img/无名小子 (12).png"),
            "向上走": pygame.image.load("img/无名小子 (9).png")}
        self.dire = "默认静态图片"
        self.im = self.imag[self.dire]
        self.img = self.images[self.direction]
        self.速度 = 20
        self.主角是否被碰撞 = True



    def 主角静图移动(self):
        if 动态图片开关:
            self.image = self.images[目前动态位置]
            screen.blit(self.image[self.index % 3], (surface_x + self.rect.left, surface_y + self.rect.top))
            self.index += 1
            if 主角移动开关:
                主角.人物移动()
        if 静态图片开关:
            self.im = self.imag[目前静态位置]
            screen.blit(self.im, (surface_x + self.rect.left, surface_y + self.rect.top))

    def 人物移动(self):
        if 目前动态位置 == "向上走":
            if self.rect.top > 0:
                self.rect.top -= self.速度
        elif 目前动态位置 == "向下走":
            if self.rect.top < 最大移动范围 - self.rect.height:
                self.rect.top += self.速度
        elif 目前动态位置 == "向左走":
            if self.rect.left > 0:
                self.rect.left -= self.速度
        elif 目前动态位置 == "向右走":
            if self.rect.left <  最大移动范围 - self.rect.width:
                self.rect.left += self.速度

    def 鼠标碰撞检测(self):
        if self.rect.collidepoint( (鼠标_x-surface_x , 鼠标_y-surface_y) ):
            self.主角是否被碰撞 = True
            global 黄指针闪动
            黄指针闪动 = True

        else:
            self.当前人物被碰撞 = False
            黄指针闪动 = False
    主角.主角静图移动()
    主角.鼠标碰撞检测()

    指针_1.展示指针()
    
 for event in pygame.event.get():
        if event.type == pygame.QUIT:
            switch = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                print("上")
                主角.direction2 = "向上走"
                目前动态位置 = "向上走"
                目前静态位置 = "向上走"
                静态图片开关 = False
                动态图片开关 = True
                主角移动开关 = True

            elif event.key == pygame.K_DOWN:
                print("下")
                主角.direction2 = "向下走"
                目前动态位置 = "向下走"
                目前静态位置 = "向下走"
                静态图片开关 = False
                动态图片开关 = True
                主角移动开关 = True
            elif event.key == pygame.K_LEFT:
                print("左")
                主角.direction2 = "向左走"
                目前动态位置 = "向左走"
                目前静态位置 = "向左走"
                静态图片开关 = False
                动态图片开关 = True
                主角移动开关 = True
            elif event.key == pygame.K_RIGHT:
                print("右")
                主角.direction2 = "向右走"
                目前动态位置 = "向右走"
                目前静态位置 = "向右走"
                静态图片开关 = False
                动态图片开关 = True
                主角移动开关 = True
        if event.type == pygame.KEYUP:
            主角是否移动 = False
            主角移动开关 = False
            动态图片开关 = False
            静态图片开关 = True
    pygame.mouse.set_visible(False)
    指针_1.展示指针()
    if 黄指针闪动:
        指针_1.黄闪指针闪动()

以下完整代码:

from pygame.locals import *
import  pygame,time,sys

pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((1920,1080), FULLSCREEN)
surface = pygame.image.load("images/6666.jpg")  # 6666*6666 背景 可下方拼接

#背景
surface_x = 0
surface_y = 0


fps_count= 0
start_fps = time.time()
clock = pygame.time.Clock()

#
# 鼠标开关 ===================
黄指针闪动 = False

# 主角人物开关 ============================================
动态图片开关 = False
目前动态位置 = False
主角移动开关 = False
静态图片开关 = True
目前静态位置 = "默认静态图片"
最大移动范围 = 60000  # 人物的移动边界 


class 精灵类(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)  
class 指针(精灵类):
    def __init__(self,left,top):
        self.image = pygame.image.load('img/指针手.png').convert_alpha()
        self.黄指针手 = [pygame.image.load("img/黄指针手{0}.png".format(i)).convert_alpha() for i in range(1, 4)]
        self.index = 0
    def 展示指针(self):
        screen.blit(self.image, (鼠标_x,鼠标_y) )
    def 黄闪指针闪动(self):
        screen.blit(self.黄指针手[self.index % 3], (鼠标_x, 鼠标_y)) 
        self.index += 1

class 主角人物():
    def __init__(self, left, top):
        self.images = {
            "向下走": [pygame.image.load("img/无名小子 ({0}).png".format(i)).convert_alpha() for i in range(1, 4)],
            "向左走": [pygame.image.load("img/无名小子 ({0}).png".format(i)).convert_alpha() for i in range(5, 8)],
            "向右走": [pygame.image.load("img/无名小子 ({0}).png".format(i)).convert_alpha() for i in range(11, 14)],
            "向上走": [pygame.image.load("img/无名小子 ({0}).png".format(i)).convert_alpha() for i in range(8, 11)]}
        self.index = 0
        self.步数 = 66
        self.direction = "向上走"
        self.image = self.images[self.direction]
        self.rect = self.image[0].get_rect()

        self.imag = {
            "默认静态图片": pygame.image.load("img/无名小子 (2).png"),
            "向下走": pygame.image.load("img/无名小子 (2).png"),
            "向左走": pygame.image.load("img/无名小子 (6).png"),
            "向右走": pygame.image.load("img/无名小子 (12).png"),
            "向上走": pygame.image.load("img/无名小子 (9).png")}
        self.dire = "默认静态图片"
        self.im = self.imag[self.dire]
        self.img = self.images[self.direction]
        self.速度 = 20
        self.主角是否被碰撞 = True



    def 主角静图移动(self):
        if 动态图片开关:
            self.image = self.images[目前动态位置]
            screen.blit(self.image[self.index % 3], (surface_x + self.rect.left, surface_y + self.rect.top))
            self.index += 1
            if 主角移动开关:
                主角.人物移动()
        if 静态图片开关:
            self.im = self.imag[目前静态位置]
            screen.blit(self.im, (surface_x + self.rect.left, surface_y + self.rect.top))

    def 人物移动(self):
        if 目前动态位置 == "向上走":
            if self.rect.top > 0:
                self.rect.top -= self.速度
        elif 目前动态位置 == "向下走":
            if self.rect.top < 最大移动范围 - self.rect.height:
                self.rect.top += self.速度
        elif 目前动态位置 == "向左走":
            if self.rect.left > 0:
                self.rect.left -= self.速度
        elif 目前动态位置 == "向右走":
            if self.rect.left <  最大移动范围 - self.rect.width:
                self.rect.left += self.速度

    def 鼠标碰撞检测(self):
        if self.rect.collidepoint( (鼠标_x-surface_x , 鼠标_y-surface_y) ):
            self.主角是否被碰撞 = True
            global 黄指针闪动
            黄指针闪动 = True

        else:
            self.当前人物被碰撞 = False
            黄指针闪动 = False


# 创建主角人物
主角 = 主角人物(222,333)

# 鼠标指针===============
指针_1 = 指针(236,365)

switch = True
while switch:
    #展示帧
    clock.tick(60)
    now = time.time()
    fps = fps_count / (now - start_fps)
    myfont = pygame.font.Font(None, 60)
    fpsImage = myfont.render(str(fps), True, (255,255,255))
    鼠标_x, 鼠标_y = pygame.mouse.get_pos()


	# 建造地板
    Scope = 5000 # 以背景宽  创建6w*6w地板
    for x in range(11):
        screen.blit(surface, (surface_x + Scope, surface_y)) # 隔一个,并向右画10次
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 5000 ) )#向右画10次
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 10000 ) ) # 为啥不循环? 循环就掉帧
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 15000 ) )
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 20000 ) )
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 25000 ) )
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 30000 ) )
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 35000 ) )
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 40000 ) )
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 45000 ) )
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 50000 ) )
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 55000 ) )
        screen.blit(surface, (surface_x + Scope - 5000, surface_y + 60000 ) )
        Scope += 5000
    fps_count += 1
    screen.blit(surface,(surface_x,surface_y))

    主角.主角静图移动()
    主角.鼠标碰撞检测()

    #
    指针_1.展示指针()


    # 鼠标控制背景移动 =====================================
    for x in range(6):
        c, d = pygame.mouse.get_pos()  # 鼠标位置
        screen_speed = 10  # 背景移动速度
        if c > 0 and d == 0:
            surface_y += screen_speed
        if c == 0 and d > 0:
            surface_x += screen_speed
        if c > 0 and d == 1079:  # 1920*1080
            surface_y -= screen_speed
        if c == 1919 and d > 0:  # 1920*1080
            surface_x -= screen_speed
        # 如果大于边界
        if surface_x > 0:
            surface_x = 0
        if surface_y > 0:
            surface_y = 0
    screen.blit(fpsImage, (10, 10))


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            switch = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                print("上")
                主角.direction2 = "向上走"
                目前动态位置 = "向上走"
                目前静态位置 = "向上走"
                静态图片开关 = False
                动态图片开关 = True
                主角移动开关 = True

            elif event.key == pygame.K_DOWN:
                print("下")
                主角.direction2 = "向下走"
                目前动态位置 = "向下走"
                目前静态位置 = "向下走"
                静态图片开关 = False
                动态图片开关 = True
                主角移动开关 = True


            elif event.key == pygame.K_LEFT:
                print("左")
                主角.direction2 = "向左走"
                目前动态位置 = "向左走"
                目前静态位置 = "向左走"
                静态图片开关 = False
                动态图片开关 = True
                主角移动开关 = True


            elif event.key == pygame.K_RIGHT:
                print("右")
                主角.direction2 = "向右走"
                目前动态位置 = "向右走"
                目前静态位置 = "向右走"
                静态图片开关 = False
                动态图片开关 = True
                主角移动开关 = True


        if event.type == pygame.KEYUP:
            主角是否移动 = False
            主角移动开关 = False
            动态图片开关 = False
            静态图片开关 = True


    pygame.mouse.set_visible(False)
    指针_1.展示指针()
    if 黄指针闪动:
        指针_1.黄闪指针闪动()


    pygame.display.update()





  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使 Pygame 的对象跟随鼠标移动,你可以在游戏主循环使用 `pygame.mouse.get_pos()` 函数来获取鼠标的当前位置,然后将对象的位置设置为鼠标的位置。下面是一个示例代码来演示如何实现这一功能: ```python import pygame # 初始化 Pygame pygame.init() # 设置窗口尺寸 window_width = 800 window_height = 600 window = pygame.display.set_mode((window_width, window_height)) # 导入角色图片 character_image = pygame.image.load("character.png") character_rect = character_image.get_rect() # 游戏主循环 running = True while running: window.fill((255, 255, 255)) # 清屏 # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 获取鼠标的当前位置 mouse_x, mouse_y = pygame.mouse.get_pos() # 设置角色的位置为鼠标的位置 character_rect.centerx = mouse_x character_rect.centery = mouse_y # 绘制角色 window.blit(character_image, character_rect) pygame.display.flip() # 退出 Pygame pygame.quit() ``` 在上面的代码,我们首先导入 Pygame 并初始化。然后,我们设置了一个窗口,并导入了要跟随鼠标移动的角色图片。在游戏主循环,我们首先清屏,然后处理事件。通过使用 `pygame.mouse.get_pos()` 函数,我们可以获取鼠标的当前位置。然后,我们将角色的位置设置为鼠标的位置,通过更新角色的 `centerx` 和 `centery` 属性。最后,我们在窗口上绘制角色,并通过调用 `pygame.display.flip()` 来更新窗口显示。 请注意,上述代码的角色图片和路径应该根据你自己的情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值