Pygame学习笔记3:用户输入以及Bomb Catcher游戏

Pygame学习笔记3:用户输入以及Bomb Catcher游戏,第1张

Pygame学习笔记3:用户输入以及Bomb Catcher游戏 事件检测

pygame.event.get()函数用于获取用户输入,通过以下代码可以持续获取用户输入,若用户点击窗口的×,即触发QUIT事件,则程序结束:

while True:
	for event in pygame.event.get():
		if event.type == QUIT:
			sys.exit()
键盘事件

键盘事件包括KEYUP和KEYDOWN,若想要响应按键按下的时候,则检查KEYDOWN,若想要响应按键释放的时候,则检查KEYUP。

一个比较常用的按键ESC,即Escape,常用于退出,因此事件的检测可以进一步为:

while True:
	for event in pygame.event.get():
		if event.type == QUIT:
			sys.exit()
		elif event.type == KEYUP:
			if event.key == pygame.K_ESCAPE:
				sys.exit()

默认的情况下,pygame对于一直按一个键只会发送一个事件,若要让pygame持续发送重复的事件,则需要打开键重复功能:

pygame.key.set_repeat(10)

参数是一个以毫秒为单位的重复值。

鼠标事件

pygame支持的鼠标事件有MOUSEMOTION、MOUSEBUTTONUP、MOUSEBUTTONDOWN,用法如下:

for event in pygame.event.get():
	if event.type == MOUSEMOTION:
		mouse_x, mouse_y = event.pos
		mov_x, mov_y = event.rel
	elif event.type == MOUSEBUTTONUP:
		mouse_up = event.button
		mouse_up_x, mouse_up_y = event.pos
	elif event.type == MOUSEBUTTONDOWN:
		mouse_down = event.button
		mouse_down_x, mouse_down_y = event.pos
设备轮询

可以使用pygame.key.get_pressed()函数一次轮询键盘所有的按键,若按下,则相应的键值为True,方便检测多个按键的按下:

keys = pygame.key.get_pressed()
if keys[K_ESCAPE]:
	sys.exit()
轮询键盘
import sys
import random
import time
import pygame
from pygame.locals import *


def print_text(font, x, y, text, color=(255, 255, 255), shadow=True):
    imgText = font.render(text, True, color)
    screen.blit(imgText, (x, y))


pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Keyboard Demo")
font1 = pygame.font.Font(None, 24)
font2 = pygame.font.Font(None, 200)
white = 255, 255, 255
yellow = 255, 255, 0

key_flag = False
correct_answer = 97  # 'a'
seconds = 11
score = 0
clock_start = 0
game_over = True

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == KEYDOWN:
            key_flag = True
        elif event.type == KEYUP:
            key_flag = False

    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()

    if keys[K_RETURN]:
        if game_over:
            game_over = False
            score = 0
            seconds = 11

    clock_start = time.time()
    current = time.time() - clock_start
    speed = score * 6
    if seconds - current < 0:
        game_over = True
    elif current <= 10:
        if keys[correct_answer]:
            correct_answer = random.randint(97, 122)
            score += 1

    screen.fill((0, 0, 200))

    print_text(font1, 0, 0, "Let's see how fast you can type!")
    print_text(font1, 0, 20, "Try to keep up for 10 seconds...")

    if key_flag:
        print_text(font1, 500, 0, "")

    if not game_over:
        print_text(font1, 0, 80, "Time:" + str(int(seconds - current)))

    print_text(font1, 0, 100, "Speed:" + str(speed) + " letters/min")

    if game_over:
        print_text(font1, 0, 160, "Press Enter to start...")

    print_text(font2, 0, 240, chr(correct_answer - 32), yellow)

    pygame.display.update()


轮询鼠标
import sys
import pygame
from pygame.locals import *


def print_text(font, x, y, text, color=(255, 255, 255), shadow=True):
    imgText = font.render(text, True, color)
    screen.blit(imgText, (x, y))


pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Mouse Demo")
font1 = pygame.font.Font(None, 24)
white = 255, 255, 255
mouse_x = mouse_y = 0
move_x = move_y = 0
mouse_down = mouse_up = 0
mouse_down_x = mouse_down_y = 0
mouse_up_x = mouse_up_y = 0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == MOUSEMOTION:
            mouse_x, mouse_y = event.pos
            move_x, move_y = event.rel
        elif event.type == MOUSEBUTTONDOWN:
            mouse_down = event.button
            mouse_down_x, mouse_down_y = event.pos
        elif event.type == MOUSEBUTTONUP:
            mouse_up = event.button
            mouse_up_x, mouse_up_y = event.pos

    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()
    screen.fill((0, 100, 0))
    print_text(font1, 0, 0, "Mouse Events")
    print_text(font1, 0, 20, "Mouse position: " + str(mouse_x) + ", " + str(mouse_y))
    print_text(font1, 0, 40, "Mouse relative: " + str(move_x) + ", " + str(move_y))
    print_text(font1, 0, 60, "Mouse button down: " + str(mouse_down) + " at " +
               str(mouse_down_x) + ", " + str(mouse_down_y))
    print_text(font1, 0, 80, "Mouse button up: " + str(mouse_up) + " at " +
               str(mouse_up_x) + ", " + str(mouse_up_y))
    print_text(font1, 0, 160, "Mouse Polling")

    x, y = pygame.mouse.get_pos()
    print_text(font1, 0, 180, "Mouse position: " + str(x) + ", " + str(y))

    # 鼠标的三个按键的状态
    b1, b2, b3 = pygame.mouse.get_pressed()
    print_text(font1, 0, 200, "Mouse buttons: " + str(b1) + ", " + str(b2) + ", " + str(b3))

    pygame.display.update()


Bomb Catcher

将前面的知识结合到一起,写一个Bomb Catcher游戏:

import random
import sys
import pygame
from pygame.locals import *


def print_text(font, x, y, text, color=(255, 255, 255), shadow=True):
    imgText = font.render(text, True, color)
    screen.blit(imgText, (x, y))


pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Bomb Catcher")
font1 = pygame.font.Font(None, 24)
# 设置鼠标看不见
pygame.mouse.set_visible(False)
white = 255, 255, 255
red = 220, 50, 50
yellow = 230, 230, 50
black = 0, 0, 0

lives = 3
score = 0
game_over = True
mouse_x = mouse_y = 0
pos_x = 300
pos_y = 460
bomb_x = random.randint(0, 500)
bomb_y = -50
vel_y = 0.7

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == MOUSEMOTION:
            mouse_x, mouse_y = event.pos
            move_x, move_y = event.rel
        elif event.type == MOUSEBUTTONUP:
            if game_over:
                game_over = False
                lives = 3
                score = 0

    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()
    screen.fill((0, 0, 200))
    if game_over:
        print_text(font1, 100, 200, "", white)
    else:
        bomb_y += vel_y

    if bomb_y > 500:
        bomb_x = random.randint(0, 500)
        bomb_y = -50
        lives -= 1
        if lives == 0:
            game_over = True
    elif bomb_y > pos_y:
        if bomb_x > pos_x and bomb_x < pos_x + 120:
            score += 10
            bomb_x = random.randint(0, 500)
            bomb_y = -50

    pygame.draw.circle(screen, black, (bomb_x - 4, int(bomb_y) - 4), 30, 0)
    pygame.draw.circle(screen, yellow, (bomb_x, int(bomb_y)), 30, 0)

    pos_x = mouse_x
    if pos_x < 0:
        pos_x = 0
    elif pos_x > 500:
        pos_x = 500

    pygame.draw.rect(screen, black, (pos_x - 4, pos_y - 4, 120, 40), 0)
    pygame.draw.rect(screen, red, (pos_x, pos_y, 120, 40), 0)

    print_text(font1, 0, 0, "LIVES: " + str(lives))
    print_text(font1, 500, 0, "SCORE: " + str(score))

    pygame.display.update()


任务一:当炸d触碰到底时,显示爆炸场景,并出现短暂的延迟

这里由于本人能力有限,做不出常见的那些爆炸的画面,因此只是稍微模拟一下。

源代码如下:

import random
import sys
import time

import pygame
from pygame.locals import *


def print_text(font, x, y, text, color=(255, 255, 255), shadow=True):
    imgText = font.render(text, True, color)
    screen.blit(imgText, (x, y))


pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Bomb Catcher")
font1 = pygame.font.Font(None, 24)
# 设置鼠标看不见
pygame.mouse.set_visible(False)
white = 255, 255, 255
red = 220, 50, 50
yellow = 230, 230, 50
black = 0, 0, 0

lives = 3
score = 0
game_over = True
mouse_x = mouse_y = 0
pos_x = 300
pos_y = 460
bomb_x = random.randint(0, 500)
bomb_y = -50
vel_y = 0.5

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == MOUSEMOTION:
            mouse_x, mouse_y = event.pos
            move_x, move_y = event.rel
        elif event.type == MOUSEBUTTONUP:
            if game_over:
                game_over = False
                lives = 3
                score = 0

    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        sys.exit()
    screen.fill((0, 0, 200))
    if game_over:
        print_text(font1, 100, 200, "", white)
    else:
        bomb_y += vel_y

    # 炸d到底
    if bomb_y > 500:
        # 显示爆炸场景
        screen.fill((0, 255, 0))
        pygame.draw.circle(screen, red, (300, 250), 100, 0)
        pygame.display.update()
        # 暂停片刻
        time.sleep(0.5)

        bomb_x = random.randint(0, 500)
        bomb_y = -50
        lives -= 1
        if lives == 0:
            game_over = True
    elif bomb_y > pos_y:
        if bomb_x > pos_x and bomb_x < pos_x + 120:
            score += 10
            bomb_x = random.randint(0, 500)
            bomb_y = -50

    pygame.draw.circle(screen, black, (bomb_x - 4, int(bomb_y) - 4), 30, 0)
    pygame.draw.circle(screen, yellow, (bomb_x, int(bomb_y)), 30, 0)

    pos_x = mouse_x
    if pos_x < 0:
        pos_x = 0
    elif pos_x > 500:
        pos_x = 500

    pygame.draw.rect(screen, black, (pos_x - 4, pos_y - 4, 120, 40), 0)
    pygame.draw.rect(screen, red, (pos_x, pos_y, 120, 40), 0)

    print_text(font1, 0, 0, "LIVES: " + str(lives))
    print_text(font1, 500, 0, "SCORE: " + str(score))

    pygame.display.update()


运行结果如下:

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5689913.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存