python实现flappy bird小游戏


Posted in Python onDecember 24, 2018

本文实例为大家分享了python实现flappy bird游戏的具体代码,供大家参考,具体内容如下

flappygamemain.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Created on Dec 25 2016
@author: LINJUNJI 
@mail: ljj6@mail2.sysu.edu.cn 
"""
import pygame
from sys import exit
import random
from pygame.locals import *
from pygame.font import * 
from gamerole import *
import os
import datetime
import numpy as np
import operator

#图片路径信息
BackGround_image_path1='./sources/background/day.png'  #背景图片
BackGround_image_path2='./sources/background/night.png'

GetStart_image_path='./sources/guide/day/down.png'  #开始界面
GameOver_image_path='./sources/other/gameover.png'
Restart_image_path='./sources/other/restart.png'

Grade_blackball_path='./sources/other/grade_blackball.png'
white_gold_Medal_image_path='./sources/medal/white_gold_medal.png' #奖牌图片
gold_image_path='./sources/medal/gold_medal.png'
silver_medal_image_path='./sources/medal/silver_medal.png'
bronze_medal_image_path='./sources/medal/bronze_medal.png'

Ground_image_path='./sources/background/ground.png'  #地面图片

pilar_image_up_path='./sources/pilar/up.png'  #柱子图片
pilar_image_down_path='./sources/pilar/down.png'
Bird_image1_path='./sources/bird/up.png'   #小鸟图片
Bird_image2_path='./sources/bird/med.png'
Bird_image3_path='./sources/bird/down.png'

#游戏窗体设置
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('falppy_bird') 

#图片载入 
background_day=pygame.image.load(BackGround_image_path1)
background_night=pygame.image.load(BackGround_image_path2)
ground=pygame.image.load(Ground_image_path)
pilar_image_up=pygame.image.load(pilar_image_up_path)
pilar_image_down=pygame.image.load(pilar_image_down_path)
get_start_image=pygame.image.load(GetStart_image_path)
gameover_image=pygame.image.load(GameOver_image_path)
medal_blackball_image=pygame.image.load(Grade_blackball_path)
restart_image=pygame.image.load(Restart_image_path)

bird_images=[]
bird_image_up=pygame.image.load(Bird_image1_path)
bird_image_med=pygame.image.load(Bird_image2_path)
bird_image_down=pygame.image.load(Bird_image3_path)
bird_images.append(bird_image_up)
bird_images.append(bird_image_med)
bird_images.append(bird_image_down)

medal_images=[]
medal1=pygame.image.load(white_gold_Medal_image_path)
medal2=pygame.image.load(gold_image_path)
medal3=pygame.image.load(silver_medal_image_path)
medal4=pygame.image.load(bronze_medal_image_path)
medal_images.append(medal1)
medal_images.append(medal2)
medal_images.append(medal3)
medal_images.append(medal4)

#新建小鸟
bird_pos=[190,190] #小鸟初始位置
mybird=Bird(bird_images,bird_pos)

#柱子集合
pilar_set = pygame.sprite.Group()

#运行参数设置
pilar_frequency=0 #柱子更新参数
bird_frequency=0 #小鸟飞行频率
clock = pygame.time.Clock()
running=False
score=0
flag=1

def collide_circle(pilar, mybird): #碰撞检测函数
 if mybird.rect.right > pilar.pilar1_rect.left and mybird.rect.left < pilar.pilar1_rect.right:
 if (mybird.rect.top >pilar.pilar1_rect.bottom and mybird.rect.bottom <pilar.pilar2_rect.top):
  return False
 else:
  return True
 else:
 if mybird.rect.bottom > 400:
  return True
 else:
  return False
 
def get_history_record(score): #获取记录的得分
 record=[]
 index =0
 if os.path.isfile("record.txt"): #存在:获取记录到的内容 
 f=open("record.txt")
 line=f.readline()
 line=f.readline()
 while line !="":
  record.append([int(line.strip().split(",")[0]),line.strip().split(",")[1]])
  line=f.readline()
 f.close()
 record.append([score,str(datetime.datetime.now())])
 record.sort(key=operator.itemgetter(0),reverse=True)
 print record
 while len(record)>10:
 record.pop()
 file_writer = open("record.txt", 'w')
 file_writer.writelines("time"+","+"grade"+"\n")
 for i in range(len(record)):
 file_writer.writelines(str(record[i][0])+","+str(record[i][1])+"\n")
 if int(record[i][0]) == int(score):
  index=i
 file_writer.close()
 if index >3:
 index=3
 return record[0][0],index
 
 
while not running:
 clock.tick(60) 
 screen.fill(0)
 screen.blit(get_start_image, (0, 0)) 
 pygame.display.update()
 x, y=pygame.mouse.get_pos() 
 for event in pygame.event.get():
 if event.type ==pygame.QUIT:
  pygame.quit()
  exit()
 elif event.type == pygame.MOUSEBUTTONDOWN:
  if y<380 and y>300 and x>180 and x <210:
  running=True
 
while True:
 clock.tick(60) 
 pilar_frequency +=1 
 #生成柱子
 if pilar_frequency %100==0:
 pilar_pos=[384,random.randint(130, 250)]
 new_pilar=Pilar(pilar_image_up, pilar_image_down, pilar_pos)
 pilar_set.add(new_pilar) 
 if pilar_frequency >=1000:
 pilar_frequency=0 
 flag=(-1)*flag 
 #移动柱子
 for pilar in pilar_set:
 pilar.move()
 if collide_circle(pilar, mybird): #碰撞检测代码
  mybird.is_hit=True 
  for pilar in pilar_set:
  pilar.stop()
 if pilar.pilar1_rect.right <0:
  pilar_set.remove(pilar) 
 #小鸟降落
 mybird.SelfMoveDown() 
 # 绘制背景
 screen.fill(0)
 
 if flag==1:
 screen.blit(background_day, (0, 0)) 
 else:
 screen.blit(background_night, (0, 0))
 #绘制柱子
 for pilar in pilar_set:
 screen.blit(pilar.pilar1_image,pilar.pilar1_rect)
 screen.blit(pilar.pilar2_image,pilar.pilar2_rect)
 #绘制地面 
 screen.blit(ground,(0,384))
 #绘制玩家小鸟
 bird_frequency +=1 
 if not mybird.is_hit: #未发生碰撞
 score +=10
 screen.blit(mybird.image[mybird.image_index],mybird.rect)
 mybird.image_index=bird_frequency % 3 
 else: #发生碰撞
 running=False 
 mybird.SelfDiedDown()
 screen.blit(mybird.image[0],mybird.rect)
 has_log=False
 while not running and mybird.is_downtoground: #画面切换到结束界面  
  screen.blit(gameover_image,(64,30))
  screen.blit(medal_blackball_image,(42,100))
  screen.blit(restart_image,(122,270))
  if not has_log:   
  bestscore,index=get_history_record(score/100) #获取历史记录情况
  print score/100
  print bestscore,index
  has_log=True
  screen.blit(medal_images[index],(75,160)) #要读取之前保存的信息,
  x, y=pygame.mouse.get_pos() 
  
  #目前得分
  score_font = pygame.font.Font(None, 36)
  score_text = score_font.render(str(score/100), True, (255,255,255))
  text_rect = score_text.get_rect()
  text_rect.midtop = [290, 145]
  screen.blit(score_text, text_rect)
  #历史最佳得分
  score_font = pygame.font.Font(None, 36)
  score_text = score_font.render(str(bestscore), True, (255,255,255))
  text_rect = score_text.get_rect()
  text_rect.midtop = [290,200]
  screen.blit(score_text, text_rect)
  
  for event in pygame.event.get():
  if event.type ==pygame.QUIT:
   pygame.quit()
   exit()
  elif event.type == pygame.MOUSEBUTTONDOWN:
   if y<360 and y>280 and x>150 and x <240: #重新开始
   pilar_set = pygame.sprite.Group()
   mybird=Bird(bird_images,bird_pos)
   score=0
   running=True
  pygame.display.update()  
 
 # 绘制得分 
 score_font = pygame.font.Font(None, 36)
 score_text = score_font.render(str(score/100), True, (255,255,255))
 text_rect = score_text.get_rect()
 text_rect.midtop = [185, 30]
 screen.blit(score_text, text_rect)

 #屏幕更新
 pygame.display.update()
 #绘制按键执行代码
 key_pressed=pygame.key.get_pressed()
 if not mybird.is_hit:
 if key_pressed[K_w] or key_pressed[K_UP]:
  mybird.moveUp()
 if key_pressed[K_s] or key_pressed[K_DOWN]:
  mybird.moveDown()
 
 for event in pygame.event.get():
 if event.type ==pygame.QUIT:
  pygame.quit()
  exit()

gamerole.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Created on Thu Dec 25 2016
@author: LINJUNJI 
@mail: ljj6@mail2.sysu.edu.cn 
"""

import pygame
import random

SCREEN_WIDTH =384
SCREEN_HEIGHT=448
INTERVEL=120  #两个障碍之间的间隔
UP_LIMIT=60
DOWN_LIMIT=360

#小鸟类
class Bird(pygame.sprite.Sprite):
 def __init__(self,bird_imgs,init_pos):
 pygame.sprite.Sprite.__init__(self)
 self.image=bird_imgs
 self.rect=self.image[0].get_rect()
 self.rect.midbottom=init_pos
 self.up_speed = 5
 self.down_speed=2
 self.selfdown_speed=2
 self.image_index=0  #图片索引参数,控制小鸟飞行姿态变化
 self.is_hit=False 
 self.is_downtoground=False
 
 def SelfMoveDown(self):
 self.rect.top += self.selfdown_speed
 
 def SelfDiedDown(self):
 self.up_speed = 0
 self.down_speed=0
 self.rect.bottom +=self.selfdown_speed*2
 if self.rect.bottom >=400:
  self.rect.bottom =400
  self.is_downtoground=True
 
 def moveUp(self):
 if self.rect.top<=0:
  self.rect.top=0
 else:
  self.rect.top -=self.up_speed
  
 def moveDown(self):
 if self.rect.top>=SCREEN_HEIGHT-self.rect.height:
  self.rect.top = SCREEN_HEIGHT-self.rect.height
 else:
  self.rect.top += self.down_speed
 ''' 
 def moveLeft(self):
 if self.rect.left <= 0:
  self.rect.left = 0
 else:
  self.rect.left -= self.speed

 def moveRight(self):
 if self.rect.left >= SCREEN_WIDTH - self.rect.width:
  self.rect.left = SCREEN_WIDTH - self.rect.width
 else:
  self.rect.left += self.speed
 '''
#柱子类
class Pilar(pygame.sprite.Sprite):
 def __init__(self,pilar_image_up,pilar_image_down,init_pos):
 pygame.sprite.Sprite.__init__(self)
 self.pilar1_image=pilar_image_up
 self.pilar2_image=pilar_image_down
 self.pilar1_rect=self.pilar1_image.get_rect()
 self.pilar2_rect=self.pilar2_image.get_rect()
 self.pilar1_rect.bottomleft=init_pos
 self.pilar2_rect.topleft=[init_pos[0],init_pos[1]+INTERVEL]
 self.horizontal_speed=2 #柱子平移的速度
 self.vertical_speed=0.3 #柱子上下移动的速度
 self.direction=random.randint(0,1) #柱子上下移动的方向
 
 def move(self):
 self.pilar1_rect.left -=self.horizontal_speed #柱子左右移动
 self.pilar2_rect.left -=self.horizontal_speed
 if self.direction == 1:    #控制柱子上下移动
  self.pilar1_rect.bottom +=self.vertical_speed 
  self.pilar2_rect.top +=self.vertical_speed
  if self.pilar2_rect.top > DOWN_LIMIT:
  self.direction=0
 else:
  self.pilar1_rect.bottom -=self.vertical_speed 
  self.pilar2_rect.top -=self.vertical_speed
  if self.pilar1_rect.bottom < UP_LIMIT:
  self.direction=1
 def stop(self):
 self.horizontal_speed=0
 self.vertical_speed=0

源码下载:python实现flappy bird游戏

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
树莓派中python获取GY-85九轴模块信息示例
Dec 05 Python
Python中集合类型(set)学习小结
Jan 28 Python
Python编程之列表操作实例详解【创建、使用、更新、删除】
Jul 22 Python
动态规划之矩阵连乘问题Python实现方法
Nov 27 Python
Python图像处理之识别图像中的文字(实例讲解)
May 10 Python
Python装饰器的执行过程实例分析
Jun 04 Python
numpy.ndarray 交换多维数组(矩阵)的行/列方法
Aug 02 Python
python数据处理 根据颜色对图片进行分类的方法
Dec 08 Python
pytorch如何冻结某层参数的实现
Jan 10 Python
运行tensorflow python程序,限制对GPU和CPU的占用操作
Feb 06 Python
python scatter函数用法实例详解
Feb 11 Python
使用Python提取文本中含有特定字符串的方法示例
Dec 09 Python
python实现Flappy Bird源码
Dec 24 #Python
python3安装speech语音模块的方法
Dec 24 #Python
对Python 语音识别框架详解
Dec 24 #Python
python抓取网页内容并进行语音播报的方法
Dec 24 #Python
解决pyttsx3无法封装的问题
Dec 24 #Python
pyttsx3实现中文文字转语音的方法
Dec 24 #Python
python实现flappy bird游戏
Dec 24 #Python
You might like
超神学院:天使彦公认最美的三个视角,网友:我的天使快下凡吧!
2020/03/02 国漫
PHP在字符串中查找指定字符串并删除的代码
2008/10/02 PHP
php 生成静态页面的办法与实现代码详细版
2010/02/15 PHP
PHP中的多种加密技术及代码示例解析
2016/10/20 PHP
PHP后端银联支付及退款实例代码
2017/06/23 PHP
PHP+JS实现的实时搜索提示功能
2018/03/13 PHP
PHP利用缓存处理用户注册时的邮箱验证,成功后用户数据存入数据库操作示例
2019/12/31 PHP
一些相见恨晚的 JavaScript 技巧
2010/04/25 Javascript
js删除所有的cookie的代码
2010/11/25 Javascript
javascript实现可改变滚动方向的无缝滚动实例
2013/06/17 Javascript
基于promise.js实现nodejs的promises库
2014/07/06 NodeJs
jQuery插件bxSlider实现响应式焦点图
2015/04/12 Javascript
表单中单选框添加选项和移除选项
2016/07/04 Javascript
JS实现获取当前URL和来源URL的方法
2016/08/24 Javascript
微信小程序使用swiper组件实现类3D轮播图
2018/08/29 Javascript
Vue实现美团app的影院推荐选座功能【推荐】
2018/08/29 Javascript
axios+Vue实现上传文件显示进度功能
2019/04/14 Javascript
vue中$refs, $emit, $on, $once, $off的使用详解
2019/05/26 Javascript
JavaScript基础之this和箭头函数详析
2019/09/05 Javascript
[35:26]DOTA2上海特级锦标赛B组小组赛#2 VG VS Fnatic第三局
2016/02/26 DOTA
[01:21]DOTA2 新英雄 森海飞霞
2020/12/18 DOTA
python实现教务管理系统
2018/03/12 Python
用python打印1~20的整数实例讲解
2019/07/01 Python
Python缓存技术实现过程详解
2019/09/25 Python
Python列表原理与用法详解【创建、元素增加、删除、访问、计数、切片、遍历等】
2019/10/30 Python
python创建ArcGIS shape文件的实现
2019/12/06 Python
基于HTML5+CSS3实现简单的时钟效果
2017/09/11 HTML / CSS
Skyscanner加拿大:全球旅行搜索平台
2018/11/19 全球购物
德国50岁以上交友网站:Lebensfreunde
2020/03/18 全球购物
数据库的约束含义
2012/09/09 面试题
学生党员思想汇报
2013/12/28 职场文书
材料专业大学毕业生自荐书
2014/07/02 职场文书
2014年保安个人工作总结
2014/11/13 职场文书
2014年财务经理工作总结
2014/12/08 职场文书
见习期个人总结
2015/03/05 职场文书
vue/cli 配置动态代理无需重启服务的方法
2022/05/20 Vue.js