python小游戏小恐龙1
#coding=utf-8
#coding=gbk
import pygame
from itertools import cycle
from pygame.locals import * #导入pygame中的常量
SCREENWIDTH=600#窗口宽度
SCREENHEIGHT=260#窗口高
FPS=30
#定义一个滚动地图
class Mymap():
def __init__(self,x,y):
self.bg=pygame.image.load("image/bg.png").convert_alpha()
self.x=x
self.y=y
def map_rolling(self):
if self.x<-590:#小于-790说明地图已经移动完毕
self.x=600#给地图一个新的坐标点
else:
self.x-=5#5个像素向左移动
def map_update(self):
SCREEN.blit(self.bg,(self.x,self.y))
class Dinosaur():
def __init__(self):
self.rect=pygame.Rect(0,0,0,0)#初始化恐龙图形
self.jumpState=False#跳跃状态
self.jumpHeight=130#跳跃高度
self.lowest_y=140#最低坐标
self.jumpValue=0#跳跃增量
#恐龙动图索引
self.dinosaurIndex=0
self.dinosureIndexGen=cycle([0,1,2])
#加载恐龙图片
self.dinosaur_img=(pygame.image.load("image/konglong.png").convert_alpha(),
pygame.image.load("image/konglong1.png").convert_alpha(),
pygame.image.load("image/konglong2.png").convert_alpha())
# self.dinosaur_img = pygame.image.load("image/konglong.png").convert_alpha()
self.jump_autio=pygame.mixer.Sound("audio/张.mp3")#跳
self.rect.size=self.dinosaur_img[1].get_size()
self.x=50#绘制恐龙x坐标
self.y=self.lowest_y#绘制恐龙y坐标
self.rect.topleft=(self.x,self.y)
def jump(self):
self.jumpState=True
def move(self):
if self.jumpState: #当起跳的时候
if self.rect.y>=self.lowest_y:#如果站在地上
self.jumpValue=-50#以五个像素向上跳跃
if self.rect.y<=self.lowest_y - self.jumpHeight:#到达顶部向下掉
self.jumpValue=50#5个像素向下掉;
self.rect.y+=self.jumpValue#循环改变恐龙y坐标
if self.rect.y>=self.lowest_y:#如果恐龙回到地图
self.jumpState=False#关闭跳跃状态
def draw_dinosaur(self):
dinosaurIndex=next(self.dinosureIndexGen)#匹配恐龙图片
SCREEN.blit(self.dinosaur_img[dinosaurIndex],(self.x,self.rect.y))#控制恐龙
def mainGame():
score=0#得分
ovre=False
global SCREEN,FPSCLOCK, enent
pygame.init()#经过初始化之后我们就可以随便使用pygame
#使用pygame时钟之前,必须创建一个Clock对象的一个实例
#控制每个循环多长时间运行一次
FPSCLOCK=pygame.time.Clock()
#先创建一个窗体,方便我们与程序之间的交互
SCREEN=pygame.display.set_mode((SCREENWIDTH,SCREENHEIGHT))
pygame.display.set_caption("小恐龙")#窗体标题
bg1=Mymap(0,0)
bg2=Mymap(800,0)
while True:
#判断是否单机了关闭窗体
for enent in pygame.event.get():
#如果单击了关闭窗体就把窗体关闭
if enent.type==QUIT:
exit() #关闭窗体
if enent.type==KEYDOWN and enent.key==K_SPACE:
if dinosaur.rect.y >= dinosaur.lowest_y:
dinosaur.jump()
dinosaur.jump_autio.play()
pygame.display.update()#更新整个窗体
FPSCLOCK.tick(FPS)#循环应该多长时间运行一次
if ovre == False:
#绘制地图起到更新地图作用
bg1.map_update()
#地图移动
bg1.map_rolling()
bg2.map_update()
bg2.map_rolling()
dinosaur = Dinosaur()
dinosaur.move()
dinosaur.draw_dinosaur()
if __name__ == '__main__':
mainGame()