pygame制作坦克大战

此生再无相见时 提交于 2020-03-15 12:02:20

游戏介绍

通过方向键控制坦克移动

程序设计步骤

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()

运行结果

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!