下载库
pip install pygame
代码
import pygame
import random
import sys
import ctypes
from ctypes import windll, byref, create_unicode_buffer, create_string_buffer
# 键盘布局相关的常量和函数
class KeyboardLayout:
def __init__(self):
self.user32 = ctypes.WinDLL('user32', use_last_error=True)
self.kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
def get_keyboard_layout(self):
# 获取当前键盘布局
handle = self.user32.GetForegroundWindow()
thread_id = self.user32.GetWindowThreadProcessId(handle, 0)
layout_id = self.user32.GetKeyboardLayout(thread_id)
return layout_id & 0xFFFF
def switch_to_english(self):
try:
# 加载英文键盘布局(美式英语)
result = self.user32.LoadKeyboardLayoutW("00000409", 1)
if result:
print("已切换到英文键盘")
return result
except Exception as e:
print(f"切换键盘布局失败: {e}")
return False
def is_english_layout(self):
return self.get_keyboard_layout() == 0x409
# 初始化pygame
pygame.init()
# 设置游戏窗口
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("打字游戏")
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
# 尝试加载支持中文的字体
try:
font = pygame.font.SysFont('microsoftyaheimicrosoftyaheiui', 36)
big_font = pygame.font.SysFont('microsoftyaheimicrosoftyaheiui', 72)
except:
font = pygame.font.Font(None, 36)
big_font = pygame.font.Font(None, 72)
class Word:
def __init__(self, text):
self.text = text
self.x = random.randint(10, WIDTH - 100)
self.y = 0
self.speed = random.uniform(1.0, 2.0)
self.color = YELLOW
def move(self):
self.y += self.speed
def draw(self, screen):
text_surface = font.render(self.text, True, self.color)
screen.blit(text_surface, (self.x, self.y))
class Game:
def __init__(self):
self.words = []
self.current_input = ""
self.score = 0
self.lives = 3
self.word_list = ["cat", "dog", "run", "jump", "play", "game", "code", "test"]
self.spawn_timer = 0
self.spawn_delay =200
self.game_over = False
self.keyboard = KeyboardLayout()
def spawn_word(self):
if len(self.words) < 10:
new_word = Word(random.choice(self.word_list))
self.words.append(new_word)
def update(self):
self.spawn_timer += 1
if self.spawn_timer >= self.spawn_delay:
self.spawn_word()
self.spawn_timer = 0
for word in self.words[:]:
word.move()
if word.y > HEIGHT:
self.words.remove(word)
self.lives -= 1
if self.lives <= 0:
self.game_over = True
def handle_input(self, event):
# 在每次输入前检查并切换键盘布局
if not self.keyboard.is_english_layout():
self.keyboard.switch_to_english()
if event.key == pygame.K_RETURN:
self.check_input()
elif event.key == pygame.K_BACKSPACE:
self.current_input = self.current_input[:-1]
else:
if event.unicode.isalnum():
self.current_input += event.unicode
def check_input(self):
for word in self.words[:]:
if self.current_input.lower() == word.text.lower():
self.words.remove(word)
self.score += len(word.text) * 10
self.current_input = ""
return
def draw(self, screen):
screen.fill(BLACK)
# 绘制所有单词
for word in self.words:
word.draw(screen)
# 绘制当前输入
input_surface = font.render(f"输入: {self.current_input}", True, WHITE)
screen.blit(input_surface, (10, HEIGHT - 40))
# 绘制分数和生命值
score_surface = font.render(f"score: {self.score}", True, WHITE)
lives_surface = font.render(f"life: {self.lives}", True, RED)
screen.blit(score_surface, (10, 10))
screen.blit(lives_surface, (WIDTH - 100, 10))
# 游戏结束画面
if self.game_over:
game_over_surface = big_font.render("游戏结束!", True, RED)
final_score_surface = font.render(f"最终分数: {self.score}", True, WHITE)
screen.blit(game_over_surface, (WIDTH//2 - 100, HEIGHT//2 - 50))
screen.blit(final_score_surface, (WIDTH//2 - 80, HEIGHT//2 + 20))
def main():
clock = pygame.time.Clock()
game = Game()
running = True
# 初始生成一些单词
for _ in range(10):
game.spawn_word()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if not game.game_over and event.type == pygame.KEYDOWN:
game.handle_input(event)
if not game.game_over:
game.update()
game.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
标签:spawn,word,python,self,单词,小游戏,pygame,font,def
From: https://blog.csdn.net/m0_62802836/article/details/144746726