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

原创
2020/03/23 17:04
阅读数 230

游戏介绍:

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

开发工具:Visual Studio Code

代码参考:

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

结果展示:

![

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部