• C++
  • pygame 第三课 ---键盘和鼠标的控制

  • @ 2024-3-23 19:17:37

检测按键

import sys
import pygame
from pygame.locals import *

pygame.init()  # 初始化pygame模块
WIDTH = 800  # 定义游戏窗口的宽
HEIGHT = 480  # 定义游戏窗口的高
FPS = 60
SCREEN_SIZE = (WIDTH, HEIGHT)  # 定义一个元组
screen = pygame.display.set_mode(SCREEN_SIZE)  # 初始化一个显示画面的窗口
pygame.display.set_caption("MyPygame")  # 设置标题

blue = (0, 162, 232)  # 蓝色

fish = pygame.image.load("./PNG/Guppy0.png")  # 加载一张图片 ./ 表示当前目录
pos = fish.get_rect()  # 获取图片的坐标
# speed = [1, 1]  # 设定速度,分别是x方向和y方向
speedx = 5
speedy = 5
clock = pygame.time.Clock()
while True:  # 游戏主循环
    clock.tick(FPS)
    for event in pygame.event.get():  # 获取事件
        if event.type == QUIT:  # 退出
            pygame.quit()  # 退出pygame模块
            sys.exit()  # 退出系统
    key = pygame.key.get_pressed()  # 获取键盘状态
    if key[K_UP] and pos.top > 0:  # 如果方向键 上 按下,并且角色没有超过上边界
        pos.y -= speedy  # 向上移动一个速度的值
    if key[K_DOWN] and pos.bottom < HEIGHT:
        pos.y += speedy
    if key[K_LEFT] and pos.left > 0:
        pos.x -= speedx
    if key[K_RIGHT] and pos.right < WIDTH:
        pos.x += speedx
    screen.fill(blue)  # 用纯色填充窗口
    screen.blit(fish, pos)  # 绘制图像

    pygame.display.update()  # 更新窗口画面显示
import sys
import pygame
from pygame.locals import *
import random

pygame.init()  # 初始化pygame模块
WIDTH = 800  # 定义游戏窗口的宽
HEIGHT = 480  # 定义游戏窗口的高
FPS = 60
SCREEN_SIZE = (WIDTH, HEIGHT)  # 定义一个元组
screen = pygame.display.set_mode(SCREEN_SIZE)  # 初始化一个显示画面的窗口
pygame.display.set_caption("MyPygame")  # 设置标题
cc = [0, 162, 232]  # 蓝色
fish = pygame.image.load("./PNG/Guppy3.png")  # 加载一张图片 ./ 表示当前目录
pos = fish.get_rect()  # 获取图片的坐标
speed = [1, 1]  # 设定速度,分别是x方向和y方向
# speed = 5
pygame.mouse.set_visible(False)  # 隐藏鼠标
pygame.key.stop_text_input() #停止处理输入法事件
clock = pygame.time.Clock()

flag = 0
while True:  # 游戏主循环
    clock.tick(FPS)
    for event in pygame.event.get():  # 获取事件
        if event.type == QUIT:  # 退出
            pygame.quit()  # 退出pygame模块
            sys.exit()  # 退出系统
    key = pygame.key.get_pressed()  # 获取键盘状态
    mouse_pos = pygame.mouse.get_pos()  # 获取鼠标位置
#     pos.center = mouse_pos  # 修改角色中心位置为鼠标位置
    if pos.collidepoint(mouse_pos):
        pos.x=random.randint(1,WIDTH-50)
        pos.y=random.randint(1,HEIGHT-50)
    if key[K_SPACE]:
        pos.x=random.randint(1,WIDTH-50)
        pos.y=random.randint(1,HEIGHT-50)

    if key[K_c]:
        cc[0]=random.randint(0,255)
        cc[1]=random.randint(0,255)
        cc[2]=random.randint(0,255)
    screen.fill(cc)  # 用纯色填充窗口
    
    
    if key[K_1]:
        flag = 1
    if key[K_2]:
        flag = 0
    if flag == 1:
        pos = pos.move(speed)  # 移动图像
        if pos.top<0 or pos.bottom>HEIGHT:
            speed[1]=-speed[1]
        if pos.left<0 or pos.right > WIDTH:
            speed[0]=-speed[0]
    
    screen.blit(fish, pos)  # 绘制图像

    pygame.display.update()  # 更新窗口画面显示


0 条评论

目前还没有评论...