pygame写物体移动
import pygame import sys import time pygame.init() size = width,height = 800,600 screen = pygame.display.set_mode(size) color = 255,255,255 background=pygame.image.load(r'/Users/bytedance/Desktop/my/back.jpeg') #背景图片,加r background=pygame.transform.scale(background, (800, 600)) ball = pygame.image.load('/Users/bytedance/Desktop/my/ball.jpeg') ball = pygame.transform.scale(ball, (30, 30)) ballrect = ball.get_rect() rect = pygame.image.load('/Users/bytedance/Desktop/my/dog01.jpeg') rect = pygame.transform.scale(rect, (100, 100)) rectarea = rect.get_rect() rectarea.move_ip(400-100,600-35) speed =[5,5] state_time = pygame.time.Clock() x,y=380,600-100 #初始小狗位置 move_x=move_y=0 while True: # 死循环确保窗口一直显示 for event in pygame.event.get(): # 遍历所有事件 if event.type == pygame.QUIT: # 如果单击关闭窗口,则退出 sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: move_x = -5 elif event.key == pygame.K_RIGHT: move_x = 5 elif event.key == pygame.K_UP: move_y = -5 elif event.key == pygame.K_DOWN: move_y = 5 elif event.type == pygame.KEYUP: move_x = 0 move_y = 0 x += move_x y += move_y state_time.tick(50) ballrect = ballrect.move(speed) #小球随机动 screen.fill(color) screen.blit(background,(0,0)) screen.blit(ball,ballrect) screen.blit(rect,(x,y)) pygame.display.flip() if ballrect.left<0 or ballrect.right>width: speed[0] = -speed[0] if ballrect.top<0: speed[1] = -speed[1] if ballrect.bottom==600-30 and ballrect.left+50>=x and ballrect.left<=x+200 : speed[1] = -speed[1] if ballrect.bottom>600+50: speed[1] = -speed[1] pygame.quit()
简单放个效果图哈,随便搭了一下。。。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类