在pygame中能够用键盘控制角色也能用鼠标。
如何用鼠标控制角色?
1.首先导入pygame模块以及常用的函数和常量,可以用以下代码导入这些模块:
import pygame as pg #导入pygame模块,可以为了简便命名为pg
from pygame.locals import *#常用的函数和常量
import sys#最后会用到
2.加载你要移动的图片。你可以使用以下代码加载图片:
image = pg.image.load("image.png")#加载图片,括号内的image是照片的名字可以改动
3.创建一个窗口来显示游戏界面。你可以使用以下代码创建一个窗口:
pg.init() # 初始化pygame
screen = pg.display.set_mode((400, 400)) # 创建窗口大小为400*400的窗口
4.在游戏循环中,监听鼠标事件并移动图片。你可以使用以下代码实现:
while True:
for event in pg.event.get():
if event.type == pg.MOUSEMOTION: # 监听鼠标移动事件
# 获取鼠标的坐标
mouseX, mouseY = pg.mouse.get_pos()
# 设置图片的新位置为鼠标的坐标
imageRect = image.get_rect()
imageRect.centerx = mouseX
imageRect.centery = mouseY
# 清空屏幕
screen.fill((255, 255, 255))
# 在新位置绘制图片
screen.blit(image, imageRect)
if event.type == pg.QUIT:
pg.quit()
sys.exit(0)
总结一下顺便加上一些必要的代码:
import pygame as pg #导入pygame模块,可以为了简便命名为pg
from pygame.locals import *#常用的函数和常量
import sys
image = pg.image.load("image.png")#加载图片
pg.init() # 初始化pygame
screen = pg.display.set_mode((400, 400)) # 创建窗口大小为400*400的窗口
image = pg.transform.scale(image,(800, 800))#图片大小
clock = pg.time.Clock() #Clock对象可以控制FPS
while True:
for event in pg.event.get():
if event.type == pg.MOUSEMOTION: # 监听鼠标移动事件
# 获取鼠标的坐标
mouseX, mouseY = pg.mouse.get_pos()
# 设置图片的新位置为鼠标的坐标
imageRect = image.get_rect()
imageRect.centerx = mouseX
imageRect.centery = mouseY
# 清空屏幕
screen.fill((255, 255, 255))
# 在新位置绘制图片
screen.blit(image, imageRect)
if event.type == pg.QUIT:
pg.quit()
sys.exit(0)
clock.tick(60) #设置FPS
pg.display.flip()