|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
最近做了一个测试打字速度和反应力的小游戏,代码如下:
main.py
- # !usr/bin/env python
- # -*- coding:utf-8 -*-
- from time import time
- import pygame
- import color
- import button
- import random
- import pickle
- from os.path import isfile
- class Game:
- def __init__(self):
- # 初始化pygame的模块
- pygame.init()
- pygame.font.init()
- pygame.display.init()
- # 窗口尺寸
- self.screen_size = self.screen_width, self.screen_height = 420, 550
- self.screen: pygame.Surface = pygame.display.set_mode(self.screen_size)
- pygame.display.set_icon(pygame.image.load("icon.png").convert_alpha())
- self.started = False
- self.clock = pygame.time.Clock()
- self.numdisplay_once = True
- self.second = 1.2
- self.time_complete = False
- self.score = []
- self.complete_timer_once = True
- self.second_level_once = True
- self.third_level_once = True
- self.fourth_level_once = True
- self.blit_raise_level_text = True
- # 事件id
- self.numchange_timer = pygame.USEREVENT
- self.complete_timer = pygame.USEREVENT + 1
- self.raise_level_timer = pygame.USEREVENT + 2
- if not isfile("result.pkl"):
- open("result.pkl", "wb").close()
- def Start(self):
- while True:
- self.start_button = button.StartButton()
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- exit()
- if event.type == pygame.MOUSEBUTTONUP:
- if not self.started:
- if 135 <= pygame.mouse.get_pos()[0] <= 285 and 300 <= pygame.mouse.get_pos()[1] <= 360:
- self.started = True
- if event.type == self.numchange_timer:
- if self.second <= 0.01:
- self.time_complete = True
- else:
- self.second -= 0.01
- if event.type == self.complete_timer:
- exit()
- if event.type == pygame.KEYUP:
- if event.key == pygame.K_ESCAPE:
- exit()
- if event.key == ord(self.letter) + 32:
- if self.started and (not self.time_complete):
- self.numdisplay_once = True
- self.stop_time = time()
- self.score.append(self.stop_time - self.start_time)
- self.ShowLetter()
- self.screen.fill(color.GREEN)
- if not self.started:
- self.StartButton()
- self.screen.blit(self.start_button, (135, 300))
- else:
- if not self.time_complete:
- for index, each in enumerate(self.Text()):
- if index == 0:
- self.screen.blit(each, (10, 10))
- else:
- self.screen.blit(each, (15, 40))
- self.screen.blit(self.Time(), (190, 80))
- self.ShowLetter()
- self.ShowScore()
- else:
- if self.complete_timer_once:
- pygame.time.set_timer(self.complete_timer, 3000)
- self.complete_timer_once = False
- font_surface: pygame.Surface = pygame.font.SysFont("SimHei", 23).render(
- "时间不够啦!", False, color.WHITE)
- self.screen.blit(
- font_surface,
- ((self.screen_width - font_surface.get_width()) / 2,
- (self.screen_height - font_surface.get_height()) / 2)
- )
- if self.score:
- font_surface: pygame.Surface = pygame.font.SysFont("SimHei", 23).render(
- "你的成绩是:平均{:.5f}秒/字符。".format(sum(self.score) / len(self.score)), False, color.WHITE
- )
- else:
- font_surface: pygame.Surface = pygame.font.SysFont("SimHei", 23).render(
- "你的成绩是:平均1.2秒/字符。", False, color.WHITE
- )
- self.screen.blit(
- font_surface,
- ((self.screen_width - font_surface.get_width()) / 2,
- (self.screen_height - font_surface.get_height()) / 2 + 45)
- )
- self.Save()
- self.clock.tick(60)
- pygame.display.flip()
- def StartButton(self):
- if 135 <= pygame.mouse.get_pos()[0] <= 285 and 300 <= pygame.mouse.get_pos()[1] <= 360:
- self.start_button = button.StartButtonHover(self.start_button)
- else:
- self.start_button = button.StartButton()
- @staticmethod
- def Text() -> list:
- font = pygame.font.SysFont("SimHei", 20)
- font_surface_list = [font.render("游戏开始啦!屏幕出现了哪个字母,你就要按", False, color.WHITE),
- font.render("下它!难度会不断增加哦!", False, color.WHITE)]
- return font_surface_list
- def Time(self) -> pygame.Surface:
- if self.numdisplay_once:
- self.start_time = time()
- self.second = self.RaiseLevel()
- pygame.time.set_timer(self.numchange_timer, 10)
- self.letter = chr(random.randint(65, 90))
- self.numdisplay_once = False
- font_surface = pygame.font.SysFont("SimHei", 115).render("{:.2f}".format(self.second), False, color.RED)
- return font_surface
- def ShowLetter(self):
- self.screen.blit(
- pygame.font.SysFont("SimHeu", 180).render(self.letter, False, color.BLUE),
- (150, 260)
- )
- def ShowScore(self):
- self.stop_time = time()
- if self.score:
- score = (sum(self.score) + (self.stop_time - self.start_time)) / (len(self.score) + 1)
- else:
- score = self.stop_time - self.start_time
- self.screen.blit(pygame.font.SysFont("SimHei", 25).render(
- "你目前的成绩是:" + "{:.5f}".format(score) + "秒/字符", False, color.WHITE
- ), (20, 200))
- def Save(self):
- if self.score:
- result = float("{:.5f}".format(sum(self.score) / len(self.score)))
- else:
- result = 1.2000
- try:
- highest_score = pickle.load(open("result.pkl", "rb"))
- except EOFError:
- font_surface: pygame.Surface = pygame.font.SysFont("SimHei", 23).render(
- "创造新纪录!", False, color.WHITE
- )
- self.screen.blit(font_surface,
- ((self.screen_width - font_surface.get_width()) / 2,
- (self.screen_height - font_surface.get_height()) / 2 + 100))
- open("result.pkl", "w").close()
- pickle.dump(result, open("result.pkl", "wb"))
- else:
- if highest_score >= result:
- font_surface: pygame.Surface = pygame.font.SysFont("SimHei", 23).render(
- "创造新纪录!", False, color.WHITE
- )
- self.screen.blit(font_surface,
- ((self.screen_width - font_surface.get_width()) / 2,
- (self.screen_height - font_surface.get_height()) / 2 + 100))
- open("result.pkl", "w").close()
- pickle.dump(result, open("result.pkl", "wb"))
- else:
- font_surface: pygame.Surface = pygame.font.SysFont("SimHei", 23).render(
- "你的最高纪录是:平均" + str(highest_score) + "秒/字符。", False, color.WHITE
- )
- self.screen.blit(font_surface,
- ((self.screen_width - font_surface.get_width()) / 2,
- (self.screen_height - font_surface.get_height()) / 2 + 100))
- def RaiseLevel(self):
- if len(self.score) >= 75:
- return 0.5
- elif len(self.score) >= 38:
- return 0.8
- elif len(self.score) >= 15:
- return 1
- else:
- return 1.2
- if __name__ == '__main__':
- game = Game()
- game.Start()
复制代码
button.py
- # !usr/bin/env python
- # -*- coding:utf-8 -*-
- import pygame
- import color
- def StartButton() -> pygame.Surface:
- font = pygame.font.SysFont("SimHei", 33)
- font_surface = font.render('开始游戏', False, color.BLACKRED)
- button_surface = pygame.Surface((150, 60))
- button_surface.fill(color.GRAY)
- button_surface.blit(font_surface, (10, 10))
- return button_surface
- def StartButtonHover(start_button: pygame.Surface) -> pygame.Surface:
- st = start_button
- st.fill(color.BLACK)
- font = pygame.font.SysFont("SimHei", 33)
- font_surface = font.render('开始游戏', False, color.BLACKRED)
- st.blit(font_surface, (10, 10))
- return st
复制代码
color.py
- # !usr/bin/env python
- # -*- coding:utf-8 -*-
- GREEN = 0, 255, 0
- GRAY = 55, 50, 45
- BLACK = 0, 0, 0
- BLACKRED = 160, 0, 0
- WHITE = 255, 255, 255
- RED = 255, 0, 0
- BLUE = 0, 0, 255
复制代码
运行也没问题
pyinstaller 打包也没问题
- pyinstaller -F Python\项目\TestTypingSpeed\main.py
- 265 INFO: PyInstaller: 3.5
- 280 INFO: Python: 3.7.4
- 280 INFO: Platform: Windows-7-6.1.7601-SP1
- 280 INFO: wrote F:\编程\main.spec
- 280 INFO: UPX is not available.
- 296 INFO: Extending PYTHONPATH with paths
- ['F:\\编程\\Python\\项目\\TestTypingSpeed', 'F:\\编程']
- 296 INFO: checking Analysis
- 296 INFO: Building Analysis because Analysis-00.toc is non existent
- 296 INFO: Initializing module dependency graph...
- 312 INFO: Initializing module graph hooks...
- 312 INFO: Analyzing base_library.zip ...
- 8793 INFO: running Analysis Analysis-00.toc
- 8856 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
- required by f:\python 3.7.4\python.exe
- 10915 INFO: Caching module hooks...
- 10931 INFO: Analyzing F:\编程\Python\项目\TestTypingSpeed\main.py
- 11087 INFO: Loading module hooks...
- 11087 INFO: Loading module hook "hook-encodings.py"...
- 11258 INFO: Loading module hook "hook-pydoc.py"...
- 11258 INFO: Loading module hook "hook-xml.py"...
- 11945 INFO: Looking for ctypes DLLs
- 11945 INFO: Analyzing run-time hooks ...
- 11960 INFO: Looking for dynamic libraries
- 12475 INFO: Looking for eggs
- 12475 INFO: Using Python library f:\python 3.7.4\python37.dll
- 12475 INFO: Found binding redirects:
- []
- 12491 INFO: Warnings written to F:\编程\build\main\warn-main.txt
- 12600 INFO: Graph cross-reference written to F:\编程\build\main\xref-main.html
- 12647 INFO: checking PYZ
- 12647 INFO: Building PYZ because PYZ-00.toc is non existent
- 12647 INFO: Building PYZ (ZlibArchive) F:\编程\build\main\PYZ-00.pyz
- 13978 INFO: Building PYZ (ZlibArchive) F:\编程\build\main\PYZ-00.pyz completed successfully.
- 13994 INFO: checking PKG
- 13994 INFO: Building PKG because PKG-00.toc is non existent
- 13994 INFO: Building PKG (CArchive) PKG-00.pkg
- 18424 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
- 18471 INFO: Bootloader f:\python 3.7.4\lib\site-packages\PyInstaller\bootloader\Windows-32bit\run.exe
- 18471 INFO: checking EXE
- 18471 INFO: Building EXE because EXE-00.toc is non existent
- 18471 INFO: Building EXE from EXE-00.toc
- 18471 INFO: Appending archive to EXE F:\编程\dist\main.exe
- 18486 INFO: Building EXE from EXE-00.toc completed successfully.
复制代码
但用 pyinstaller 打包之后,惨了……
- Traceback (most recent call last):
- File "main.py", line 5, in <module>
- ModuleNotFoundError: No module named 'pygame'
- [3288] Failed to execute script main
复制代码
这是怎么回事呀,我明明安装了pygame的……
求各位大神解答!
|
|