首页 > 编程语言 >python——小游戏(ball,bird)

python——小游戏(ball,bird)

时间:2023-12-13 12:55:50浏览次数:43  
标签:ball ballrect python self bird 小鸟 小游戏 pygame event

 

 

ball

 

# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 09:19:38 2023

@author: kabuqinuo
"""

import sys    # 导入sys模块
import pygame   # 导入pygame模块

pygame.init()     # 初始化pygame
size = width, height = 640, 480   # 设置窗口
screen  = pygame.display.set_mode(size)   # 显示窗口
color = (0, 0, 0)   # 设置颜色

ball = pygame.image.load("ball1.png")  #加载图片
ballrect = ball.get_rect()    # 获取矩形区域

speed = [5, 5]     # 设置移动的X轴、Y轴距离
clock = pygame.time.Clock()     # 设置时钟
# 执行死循环,确保窗口一直显示
while True:
    clock.tick(60)    # 每秒执行60次
    # 检查事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:     # 如果单击关闭窗口,则退出
            sys.exit()
    ballrect = ballrect.move(speed)    # 移动小球
    # 碰到左右边缘
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    # 碰到上下边缘
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]
    screen.fill(color)     # 用指定的颜色填充整个窗口
    screen.blit(ball, ballrect)     # 将图片画到窗口上
    screen.blit(ball, ballrect)     # 将图片画到窗口上
    pygame.display.flip()    # 更新全部显示
pygame.quit()      # 退出pygame

 

 

 bird

背景

 

小鸟

 

 

 

 

# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 08:39:08 2023

@author: kabuqinuo
"""
""""1. 游戏简介
Flappy Bird是一款鸟类飞行游戏,由越南河内独立游戏开发者阮哈东(DongNguyen)开发。在Flappy Bird这款游戏中,玩家只需要用一根手指来操控,单击触摸手机屏幕,小鸟就会往上飞,不断地单击就会不断地往高处飞。放松手指,则会快速下降。所以玩家要控制小鸟一直向前飞行,然后注意躲避途中高低不平的管子。如果小鸟碰到了障碍物,游戏就会结束。每当小鸟飞过一组管道,玩家就会获得一分。
2. 游戏分析
在Flappy Bird中,主要有两个对象:小鸟和管道。可以创建Bird类和Pineline类来分别表示这两个对象。小鸟可以通过上下移动来躲避管道,所以在Bird类中创建一个birdUpdate()方法,实现小鸟的上下移动。为了体现小鸟向前飞行的特征,可以让管道一直向左侧移动,这样在窗口中就好像小鸟在向前飞行。所以,在Pineline类中也创建了一个updatePipline()方法,实现管道的向左移动。此外,还创建了3个函数:createMap()函数用于绘制地图;checkDead()函数用于判断小鸟的生命状态;getResult()函数用于获取最终分数。最后在主逻辑中实例化类并调用相关方法,实现相应功能。
3. 搭建主框架
通过前面分析,我们可以搭建起Flappy Bird游戏的主框架。Flappy Bird游戏有两个对象:小鸟和管道。先来创建这两个类,类中的具体方法可以先使用pass语句替代。然后创建一个绘制地图的函数createMap()。最后,在主逻辑中绘制背景图片。
"""
import pygame
from pygame.locals import *
import random as rd
import sys
import copy
 
path="D:\\Ptycode\\class ex\\classtest\\game\\"
COUNTDOWN=USEREVENT+1
NEWTUBE=USEREVENT+2
 
class Game:
    def __init__(self):
        pygame.init()
        self.W,self.H=500,700
        self.screen=pygame.display.set_mode((self.W,self.H))
        pygame.display.set_caption("FlappyBird Classic")
        pygame.display.set_icon(pygame.image.load(path+"assets1.png"))
 
        self.bg=pygame.transform.smoothscale(pygame.image.load(path+"assets_background.png"),(self.W,self.H))
        self.player=Player()
        self.tubes=[]
        self.tubeWidth=45
        self.counter=0
        self.toUpdate=2
        self.tubeSpeed=2
        self.state="countdown"
        self.countdown=3
        self.score=0
        pygame.time.set_timer(COUNTDOWN,1000)
    
    def listen(self):
        for event in pygame.event.get():
            if event.type==QUIT:
                sys.exit()
            if event.type==KEYDOWN:
                if event.key==K_SPACE and self.state=="play":
                    self.player.jump()
            if event.type==COUNTDOWN:
                self.countdown-=1
                if self.countdown<=0:
                    self.state="play"
                    pygame.time.set_timer(COUNTDOWN,0)
                    pygame.time.set_timer(NEWTUBE,2200)
            if event.type==NEWTUBE:
                self.newTube()
 
    def draw(self):
        self.screen.blit(self.bg,(0,0))
        if self.state=="lose":
            t=self.print_text("simhei",128,str(self.score),(255,0,0))
            tr=t.get_rect()
            tr.center=self.W/2,self.H/2
            self.screen.blit(t,tr)
        if self.state=="play":
            self.player.update()
        self.screen.blit(self.player.image,self.player.rect)
        if self.state=="play":
            self.updateTube()
            for tube in self.tubes:
                x,y=tube[0],tube[1]
                height=tube[2]
                rect=pygame.draw.rect(self.screen,(0,255,0),(x,y,self.tubeWidth,height))
                if self.player.rect.colliderect(rect):
                    self.state="lose"
                    while self.player.rect.top<self.H:
                        self.screen.blit(self.bg,(0,0))
                        self.player.update()
                        self.screen.blit(self.player.image,self.player.rect)
                        pygame.display.update()
                    return
            t=self.print_text("simhei",35,str(self.score),(255,0,0))
            self.screen.blit(t,(25,25))
            self.check()
        if self.state=="countdown":
            t=self.print_text("simhei",72,str(self.countdown),(255,0,0))
            tr=t.get_rect()
            tr.center=self.W/2,self.H/2
            self.screen.blit(t,tr)
 
    def check(self):
        if self.player.rect.bottom>=self.H or self.player.rect.top<=0:
            self.state="lose"
            while self.player.rect.top<self.H:
                self.screen.blit(self.bg,(0,0))
                self.player.update()
                self.screen.blit(self.player.image,self.player.rect)
                pygame.display.update()
 
    def updateTube(self):
        self.counter+=1
        if self.counter>=self.toUpdate:
            for i,tube in enumerate(self.tubes):
                tube[0]-=self.tubeSpeed
            self.counter=0
            for i,tube in enumerate(copy.copy(self.tubes)):
                if tube[0]+self.tubeWidth<=0:
                    self.tubes.pop(i)
                    if tube[1]<1:
                        self.score+=1
                    break
 
    def run(self):
        while True:
            self.listen()
            self.draw()
            pygame.display.update()
 
    @staticmethod
    def print_text(name,size,text,color):
        font=pygame.font.SysFont(name,size)
        image=font.render(text,True,color)
        return image
 
    def newTube(self):
        spacing=200
        t1h=rd.randint(50,self.H-spacing)
        t2h=self.H-spacing-t1h
        self.tubes.append([self.W,0,t1h])
        self.tubes.append([self.W,t1h+spacing,t2h])
  

class Player:
    def __init__(self):
        self.images=[pygame.image.load(path+"assets1.png"),
                     pygame.image.load(path+"assets2.png"),
                     pygame.image.load(path+"assets3.png")]
        self.item=0
        self.image=self.images[self.item]
        self.rect=self.image.get_rect()
        try:
            self.rect.center=90,game.H/2
        except NameError:
            self.rect.center=90,800/2
        self.fallSpeed=0
        self.counter=0
        self.toUpdate=4
 
    def jump(self):
        self.fallSpeed=-10
 
    def fall(self):
        self.rect.y+=self.fallSpeed
        self.fallSpeed+=1
 
    def change(self):
        self.item+=1
        if self.item>2:
            self.item=0
        self.image=self.images[self.item]
 
    def update(self):
        self.counter+=1
        if self.counter>=self.toUpdate:
            self.fall()
            self.change()
            self.counter=0

 
if __name__ == '__main__':
    game=Game()
    game.run()

 

 

 

 

标签:ball,ballrect,python,self,bird,小鸟,小游戏,pygame,event
From: https://www.cnblogs.com/qinuoqwq/p/17898819.html

相关文章

  • Python——第五章:hashlib模块
    hashlib模块hashlib模块是Python中用于加密散列(hash)算法的模块。它提供了对常见的哈希算法(如MD5、SHA-1、SHA-256等)的支持,使得开发者可以轻松地在其应用中进行数据的安全散列。以下是hashlib模块中一些常用的哈希算法:MD5(MessageDigestAlgorithm5):产生128位的哈......
  • 【python】文件锁模块fcntl
      #!/usr/bin/python#coding:utf8importosimportsysimporttimeimportfcntl#导入模块classFLOCK(ojbect):def__init__(self,name):""":paramname:文件名"""self.fobj=open(name,'......
  • Python报错:performance hint: av/logging.pyx:232:5: the GIL to be acquired
     参考:https://stackoverflow.com/questions/77410272/problems-installing-python-av-in-windows-11https://github.com/PyAV-Org/PyAV/issues/1177  ================================  报错信息:C:\Windows.old\Users\chris>pipinstallavDefaultingtouserinstallatio......
  • Python报错:pkg-config could not find libraries ['avformat', 'avcodec', 'av
    参考:https://github.com/PyAV-Org/PyAV/issues/238https://pyav.org/docs/6.1.2/installation.html#mac-os-x  =====================  报错信息:C:\Users\liuxue>pipinstallavCollectingavUsingcachedav-0.3.3.tar.gzInstallingcollectedpackages:avRunning......
  • Python学习多线程、多进程、多协程记录
    一、多线程应用于请求和IO#1.Python中关于使用多线程多进程的库/模块#2.选择并发编程方式(多线程Thread、多进程Process、多协程Coroutine)前置知识: 一、三种有各自的应用场景 1.一个进程中可以启动多个线程 2.一个线程中可以启动多个协程 二、各自优缺点 1......
  • Python各种奇奇怪怪的写法以及常用案例
    工具类common#####工具类commonimportrequestsimporttimeimportjsonimportrandomimportosfromlxmlimportetreeimportconcurrent.futuresfromurllib.parseimportunquote,quotefromPILimportImagedefstrClear_v1(str):try:returnst......
  • 用python实现电子公文传输系统中遇到的数据库连接问题
    在实现电子公文传输系统时,数据库连接是一个重要的问题。Python中有多种库可以用于数据库连接,比如SQLite、MySQL、PostgreSQL等。下面是一个简单的示例,演示如何使用Python连接MySQL数据库:importmysql.connector#连接数据库conn=mysql.connector.connect(host="localhos......
  • python 报错应对列表
    =========================RESTART:D:/Python37/ziti1.py========================Traceback(mostrecentcalllast):File"D:/Python37/ziti1.py",line1,in<module>importdocxModuleNotFoundError:Nomodulenamed'docx'>>......
  • python123——西游记相关的分词,出现次数最高的20个
       #统计西游记人物出场次数,(去除冠词,代词等干扰)并降序排列p173importjiebaexcludes={"一个","那里","怎么","我们","不知","两个","甚么","不是","只见","原来","如何","这个","不曾&q......
  • python hash
    python中的hash我的博客程序源码原书:《Python全栈安全》这里使用python3.8,使用哈希函数计算消息的摘要信息,得到其哈希值(散列值)。在python下可以使用如下语句得到消息的哈希值:message='message'hash(message)哈希具有如下特性:确定性,相同的消息使用同一个哈希函数......