Python微信打飞机游戏编程学习笔记02

 继上一段的代码。继续完善中
此段代码主要
1.增加了主飞机的载入,并且是动态效果的主飞机
2.增加了主飞机的移动控制
终于有了游戏互动的感觉...继续加油

import pygame                   #导入pygame库
from pygame.locals import *     #导入pygame库中的一些常量
from sys import exit            #导入sys库中的exit函数

#定义窗口的分辨率
SCREEN_WIDTH =  480
SCREEN_HEIGHT =  640

#计数ticks
ticks = 0

#创建字典,按下上下左右键的的增量
offset ={pygame.K_LEFT:0,pygame.K_RIGHT:0,pygame.K_UP:0,pygame.K_DOWN:0}

#初始化游戏
pygame.init()
screen = pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])
pygame.display.set_caption('这是一个打飞机游戏!')

#载入背景图
background = pygame.image.load('images/background.png')

#载入资源图
hero1 = pygame.image.load('images/me1.png')
hero2 = pygame.image.load('images/me2.png')
hero_pos=[200,500]


#事件循环
while True:
    #绘制背景
    screen.blit(background,(0,0))

    #绘制飞机,在循环过程中让每过25个周期切换2个飞机图。这样会产生动图的效果
    if ticks % 50 < 25:
        screen.blit(hero1,hero_pos)
    else:
        screen.blit(hero2,hero_pos)

    ticks += 1


    #更新屏幕
    pygame.display.update()


    #处理游戏退出
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()


        #按键按下和放开的事件,按下时坐标增3,放开,置零
        if event.type == pygame.KEYDOWN:
            if event.key in offset:
                offset[event.key] = 3   #增量的大小,主飞机移动速度的快慢


        elif event.type == pygame.KEYUP:
            if event.key in offset:
                offset[event.key] = 0

    #计算增加x坐标增量,y坐标增量
    offset_x=offset[pygame.K_RIGHT]-offset[pygame.K_LEFT]
    offset_y=offset[pygame.K_DOWN]-offset[pygame.K_UP]

    #飞机新坐标
    hero_pos=[hero_pos[0]+offset_x,hero_pos[1]+offset_y]

运行如下:

猜你喜欢

转载自blog.csdn.net/veray/article/details/85268941