C:\Users\plsf9\PyCharmMiscProject\.venv\Scripts\python.exe C:\Users\plsf9\PyCharmMiscProject\TANK.py
pygame 2.6.1 (SDL 2.28.4, Python 3.13.3)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:\Users\plsf9\PyCharmMiscProject\TANK.py", line 79, in <module>
game.start_game()
~~~~~~~~~~~~~~~^^
File "C:\Users\plsf9\PyCharmMiscProject\TANK.py", line 30, in start_game
my_tank = Tank(400,300)
^^^^
NameError: name 'Tank' is not defined
import pygame
#设置通用属性
BG_COLOR = pygame.Color(0,0,0)
TEXT_COLOR = pygame.Color(255,0,0)
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
class MainGame:
'''
游戏主窗口类
'''
window = None
#def __init__(self) -> None:
# 初始化 Pygame
pygame.init()
# 初始化字体模块
pygame.font.init()
# 创建字体对象
font = pygame.font.SysFont('kaiti', 18)
def __init__(self) -> None:
pass
def start_game(self) -> None:
'''
开始游戏
'''
pygame.display.init()
MainGame.window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('TANK 1.0')
#创建一个我方坦克
my_tank = Tank(400,300)
while True:
MainGame.window.fill(BG_COLOR)
num = 6
text = self.get_text_surface(f'Enemy Tank {num}')
MainGame.window.blit(text, (10,10))
#增加事件
self.get_event()
my_tank.display_tank()
pygame.display.update()
def get_text_surface(self, text:str):
'''
获取文字的图片
'''
# 初始化字体模块
#pygame.font.init()
# 获取可以使用的字体
# print(pygame.font.get_fonts())
# 创建字体
#self.font = pygame.font.SysFont('kaiti',18)
# 绘制文字信息
text_surface = self.font.render(text, True, TEXT_COLOR)
# 将绘制的文字信息返回
return text_surface
def get_event(self):
event_list = pygame.event.get()
for event in event_list:
# 判断是什么事件,然后做出相应的处理
if event.type == pygame.QUIT:
# 点击关闭按钮
self.end_game()
if event.type == pygame.KEYDOWN:
# 按下键盘
if event.key == pygame.K_LEFT:
print('坦克向左移动')
elif event.key == pygame.K_RIGHT:
print('坦克向右移动')
elif event.key == pygame.K_UP:
print('坦克向上移动')
elif event.key == pygame.K_DOWN:
print('坦克向下移动')
def end_game(self) -> None:
'''
结束游戏
'''
print('GAME OVER')
exit()
if __name__ == '__main__':
game = MainGame()
game.start_game()
class Tank:
def __init__(self,left,top):
self.images = { 'U':pygame.image.load('./img/p1tankU.gif'),
'D':pygame.image.load('./img/p1tankD.gif'),
'L':pygame.image.load('./img/p1tankL.gif'),
'R':pygame.image.load('./img/p1tankR.gif'),}
# 设置我方坦克的方向
self.direction = 'L'
# 获取图片信息
self.image = self.images.get(self.direction)
# 获取图片的矩形
self.rect = self.image.get_rect()
# 设置我方坦克位置
self.rect.left = left
self.rect.top = top
#坦克的移动方法
def move(self):
pass
#碰撞墙壁的方法
def hitWalls(self):
pass
#射击方法
def shot(self):
pass
#展示坦克
def display_tank(self)-> None:
'''
显示坦克
'''
MainGame.window.blit(self.image, self.rect)
pass