2D游戏作业:坦克大战——实现坦克移动

删除回忆录丶 提交于 2020-03-23 17:12:46

3 月,跳不动了?>>>

游戏介绍:

通过上下左右键实现坦克的上下左右移动,并实现坦克根据上下左右键改变图片方向。

代码参考:

import os,sys,pygame
from pygame.locals import *
def control_tank(event):
    speed=[x,y]=[0,0]
    speed_offset=1
    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('D:/2D/tankU.bmp')
    back_image=pygame.image.load('D:/2D/back_image.jpg')
    tank_rect=tank_image.get_rect()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    tank_image = pygame.image.load('D:/2D/tankL.bmp')
                if event.key == pygame.K_RIGHT:
                    tank_image = pygame.image.load('D:/2D/tankR.bmp')
                if event.key == pygame.K_UP:
                    tank_image = pygame.image.load('D:/2D/tankU.bmp')
                if event.key == pygame.K_DOWN:
                    tank_image = pygame.image.load('D:/2D/tankD.bmp')
            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()

结果展示:

![

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