pygame--图片随鼠标移动

练习pygame
以下代码为:在画布上绘制一个背景图,再绘制一个图片随着鼠标的移动而移动

import pygame

# 定义画布的大小
W = 900
H = 800
size = (W, H)
back = (0, 0, 0)    # 背景色
screen = pygame.display.set_mode(size)  # 创建一个窗口
pygame.display.set_caption("我是标题11")    # 设置标题
back_img = pygame.image.load('1.jpg')   # 加载背景大图
mouse_img = pygame.image.load('2.jpg')  # 加载鼠标图片
rect = back_img.get_rect()  # 获得背景图的矩形位置

is_true = True  # 定义一个循环开始结束的标志
while is_true:  # 游戏主循环
    # 获取事件,如果用户点击退出,则退出循环
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_true = False
    # 设置背景色
    screen.fill(back)
    # 将背景大图画上去
    screen.blit(back_img, rect)

    # 获取鼠标位置
    x, y = pygame.mouse.get_pos()
    # 得到鼠标图片的坐标(坐标以窗口左上角为基准点)
    x -= mouse_img.get_width() / 2
    y -= mouse_img.get_height() / 2
    # 将鼠标图片画上去
    screen.blit(mouse_img, (x, y))
    # 重新绘制整个屏幕对应的窗口
    pygame.display.flip()

效果为:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45422695/article/details/127785225