不知道为什么,我用python的logging模块向文件里写日志,可不知道为什么,就是写不进去.
这是代码:
#! python3
# 导入模块
import pygame
import sys
from settings import Settings
from ship import Ship
from bullet import Bullet
from alien import Alien
import logging
import time
t = f'log/{time.strftime("%Y-%m-%d")}.log'
with open(t, "a") as file_object:
file_object.write("\n==========================\n\n")
logging.basicConfig(level=logging.DEBUG,
format=' [%(asctime)s] - [%(filename)s] - [%(levelname)s] - [%(message)s]',
filename=t, filemode='a')
logging.info('Start of program.')
class Alien_Invasion:
"""管理游戏行为和资源的类"""
def __init__(self):
"""初始化游戏并创建游戏资源"""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((0,0))
logging.info("Window has been created")
pygame.display.set_caption("外星人入侵")
self.bullets = pygame.sprite.Group()
self.ship = Ship(self)
logging.debug("Ship is ready")
def run_game(self):
"""开始游戏主循环"""
while True:
self._check_events()
self.ship.update()
self._update_bullet()
self._update_screen()
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _check_keydown_events(self, event):
"""响应按键"""
# right
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
logging.debug("Ship is moving left")
# left
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
logging.debug("Ship is moving right")
# fire bullet
elif event.key == pygame.K_SPACE:
self._fire_bullet()
# quit
elif event.key == pygame.K_q:
logging.info('End of program.')
sys.exit()
def _check_keyup_events(self, event):
"""响应松开"""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _fire_bullet(self):
"""创建一颗子弹,并将其加入到编组 bullet 中"""
if len(self.bullets) < self.settings.bullets_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update_bullet(self):
"""更新子弹的位置并删除消失的子弹"""
# 更新子弹位置
self.bullets.update()
# 删除消失子弹
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
def _update_screen(self):
"""更新屏幕上的图像,并切换到新屏幕"""
self.screen.fill(self.settings.bg_color)
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
pygame.display.flip()
if __name__ == "__main__":
# 创建游戏实例并运行游戏
ai = Alien_Invasion()
ai.run_game()
运行结果:
关于1楼提到的 time 模块问题,这里楼主用的 python3.9,这个版本的 time 模块确实有 strftime。
另外,就是我抽取了楼主代码中关于日志的部分,单独运行,实际是可以写入日志到文件中,不过系统是在 Linux 下,建议楼主也将代码单独抽出到一个文件独立运行,看是否正常。