import pygame
class MainProgress:
screen_width = 500
screen_height = 300
screen = None
@staticmethod
def start_game():
pygame.display.init()
MainProgress.screen = pygame.display.set_mode((MainProgress.screen_width, MainProgress.screen_height))
pygame.display.set_caption('Tank war')
pygame.Surface.fill(MainProgress.screen, (255, 255, 255))
MainProgress.screen.blit(MainProgress.set_text(), (0, 0))
@staticmethod
def set_text():
pygame.font.init()
font = pygame.font.SysFont("黑體", 20)
text = font.render('你的分數為10', True, (0, 0, 0))
return text
class BaseItem(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
class Tank():
def __init__(self):
self.speed = 10
self.direction = "up"
self.life = 3
self.images = {
"up": pygame.image.load(r"E:\PythonNote\image\p1tankU.gif"),
"down": pygame.image.load(r"E:\PythonNote\image\p1tankD.gif"),
"left": pygame.image.load(r"E:\PythonNote\image\p1tankL.gif"),
"right": pygame.image.load(r"E:\PythonNote\image\p1tankR.gif"),
}
self.image = self.images[self.direction]
self.rect = self.image.get_rect() # rect一個surface就可以用rect.left(top,bottom,right,center,centerx,centery)修改位置
self.rect.centerx = 250 # 修改中心的x坐標
self.rect.centery = 290
self.up_move = False
self.down_move = False
self.left_move = False
self.right_move = False
def get_event(self):
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN:
print('key down')
if event.key == pygame.K_w:
self.direction = "up"
self.up_move = True
elif event.key == pygame.K_a:
self.direction = "left"
self.left_move = True
elif event.key == pygame.K_s:
self.direction = "down"
self.down_move = True
elif event.key == pygame.K_d:
self.direction = "right"
self.right_move = True
elif event.key == pygame.K_SPACE:
print('fire')
elif event.type == pygame.KEYUP:
print('key up')
if event.key == pygame.K_w:
self.up_move = False
elif event.key == pygame.K_a:
self.left_move = False
elif event.key == pygame.K_s:
self.down_move = False
elif event.key == pygame.K_d:
self.right_move = False
def move_tank(self):
if self.up_move and self.rect.top > 0:
self.rect.centery -= 1
if self.down_move and self.rect.bottom <= MainProgress.screen_height:
self.rect.centery += 1
if self.left_move and self.rect.left > 0:
self.rect.centerx -= 1
if self.right_move and self.rect.right <= MainProgress.screen_width:
self.rect.centerx += 1
self.image = self.images[self.direction]
MainProgress.screen.blit(tank.image, tank.rect)
pygame.display.flip()
tank = Tank()
while True:
MainProgress.start_game()
tank.get_event()
tank.move_tank()
我想實作坦克的連續移動,
關鍵就是坦克移動getevent這個函式,我覺得沒啥問題,但是每次按下移動都會同時提示keydown和keyup,所以就無法實作坦克連續移動,求大神幫忙看看
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/24847.html
上一篇:django部署,win10+django+apache-->https
下一篇:【NAS with RL】2017-ICLR-Neural Architecture Search with Reinforcement Learning-論文閱讀
