游戏介绍
通过方向键控制坦克移动
程序设计步骤
1.导入模块
2.编写移动代码
3.坦克移动
代码编写
'''
@Author: your name
@Date: 2020-03-15 11:37:58
@LastEditTime: 2020-03-15 11:38:00
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: \3.14\tank.py
'''
import os,sys,pygame
from pygame.locals import *
def control_tank(event):
speed=[x,y]=[0,0]
speed_offset=1
img=""
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_LEFT:
speed[0]-=speed_offset
if event.key==pygame.K_RIGHT:
speed[0]=speed_offset
if event.key==pygame.K_UP:
speed[1]-=speed_offset
if event.key==pygame.K_DOWN:
speed[1]=speed_offset
if event.type==pygame.KEYUP:
if event.type in[pygame.K_UP,pygame.K_DOWN,pygame.K_RIGHT,pygame.K_LEFT]:
speed=[0,0]
return speed
def play_tank():
pygame.init()
window_size=Rect(0,0,640,480)
speed=[1,1]
color_white=(255,255,255)
screen=pygame.display.set_mode(window_size.size)
pygame.display.set_caption("坦克大战")
tank_image = pygame.image.load("tankU.bmp")
back_image=pygame.image.load("back_image.jpg")
tank_rect=tank_image.get_rect()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
cur_speed=control_tank(event)
tank_rect=tank_rect.move(cur_speed).clamp(window_size)
screen.blit(back_image,(0,0))
screen.blit(tank_image,tank_rect)
pygame.display.update()
if __name__ == '__main__':
play_tank()
运行结果
来源:oschina
链接:https://my.oschina.net/u/4459532/blog/3195247