猫史档案馆


【Python作品分享】移动小球【作品秀】

用户:26号26号查看:0 回复:3 评论:0 创建时间:2021-02-03T11:05:51


【作品展示】

center_image

 

【作品介绍】

随便做的(@_@)

操作说明:

按鼠标左键,小球移到鼠标;

按鼠标右键,小球停止移到鼠标;

方向键控制小球。

 

【作品源代码】

import pygame

pygame.init()
screen = pygame.display.set_mode((喵0, 喵0))
pygame.display.set_caption("一个球")
blue = 0, 0, 200
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255, 255, 255))
ball = pygame.Surface((30, 30))  # 建立球的矩形背景区
ball.fill((255, 255, 255))  # 矩形区域背景为白色
pygame.draw.circle(ball, (0, 0, 255), (15, 15), 15, 0)  # 画蓝色球

rect1 = ball.get_rect()  # 取得球的矩形背景区域
rect1.center = (320, 35)  # 球的初始位置
x, y = rect1.topleft  # 球左上角坐标
dx = 15  # 球移动距离

clock = pygame.time.Clock()
playing = False
running = True

print('按鼠标左键,小球移到鼠标;\n按鼠标右键,小球停止移到鼠标;\n方向键控制小球')

while running:
    clock.tick(30)  # 每秒执行30次
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    keys = pygame.key.get_pressed()  # 检查按键是按下
    if keys[pygame.K_RIGHT]:  # 按向右键且未达右边界
        rect1.centerx += dx  # 向右移动
    if keys[pygame.K_LEFT]:  # 按向左键且未达左边界
        rect1.centerx -= dx  # 向左移动
    if keys[pygame.K_UP]:
        rect1.centery -= dx  # 向上移动
    if keys[pygame.K_DOWN]:
        rect1.centery += dx  # 向下移动

    buttons = pygame.mouse.get_pressed()
    if buttons[0]:  # 按下左键后拖动鼠标球可移动
        playing = True
    elif buttons[2]:  # 按下右键后拖动鼠标球不能移动
        playing = False
    if playing == True:  # 球可移动状态
        mouses = pygame.mouse.get_pos()  # 取得鼠标坐标
        rect1.centerx = mouses[0]  # 把鼠标的x坐标作为球中心的X坐标
        rect1.centery = mouses[1]  # 把鼠标的y坐标作为球中心的y坐标

    screen.blit(background, (0, 0))  # 清除绘图窗口
    screen.blit(ball, rect1.topleft)
    pygame.display.update()
pygame.quit()

 

【提示】

部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:

https://python.codemao.cn


回复

上一页1 页 / 共 1下一页
BZIClawLYNEYBZIClawLYNEY

……………………………………………………………………………………

emotion_编程猫_冷漠

点赞0


评论


我需要复制粘贴我需要复制粘贴

emotion_编程猫_翻白眼

点赞0


评论


晨月霜星晨月霜星

你怎么安装的pygame?我咋装不上?

点赞0


评论