火遍全网的15个Python的实战项目,你该不会还不知道怎么用吧!

宇宙大豹发 2024-10-06 16:05:04 阅读 53

经常听到有朋友说,学习编程是一件非常枯燥无味的事情。其实,大家有没有认真想过,可能是我们的学习方法不对?

比方说,你有没有想过,可以通过打游戏来学编程?

今天我想跟大家分享几个Python小游戏,教你如何通过边打游戏边学编程!

今天给大家带来15个Py小游戏,一定要收藏!

飞扬的小鸟

Python简易时钟

Python中国象棋

Python吃豆豆小游戏

Python幸运大转盘

Python简易植物大战僵尸

Python2048小游戏

Python俄罗斯方块

Python 烟花

Python 贪吃蛇

Python 数字游戏

拼图游戏

滑雪小游戏

数独游戏

飞机大战

1.飞扬的小鸟

①游戏介绍:

《flappy bird》是一款由来自越南的独立游戏开发者Dong Nguyen所开发的作品,游戏于2013年5月24日上线,并在2014年2月突然暴红。

游戏规则:

游戏玩法非常简单,通过点击屏幕,使小鸟一直飞并穿过水管的空隙。虽然玩法简单,但是却具有一定的难度,因为要一直控制小鸟飞在适合的高度,以避开障碍。

这篇文章呢,就来分析这个游戏的原理,以及用python做一个简易版的FlappyBird。

②源码分享:

<code>

#itbaizhan

import pygame

import sys

import random

class Bird(object):

"""定义一个鸟类"""

def __init__(self):

"""定义初始化方法"""

self.birdRect = pygame.Rect(65, 50, 50, 50) # 鸟的矩形

# 定义鸟的3种状态列表

self.birdStatus = [pygame.image.load("images/0.png"),

pygame.image.load("images/2.png"),

pygame.image.load("images/dead.png")]

self.status = 0 # 默认飞行状态

self.birdX = 120 # 鸟所在X轴坐标,即是向右飞行的速度

self.birdY = 350 # 鸟所在Y轴坐标,即上下飞行高度

self.jump = False # 默认情况小鸟自动降落

self.jumpSpeed = 10 # 跳跃高度

self.gravity = 5 # 重力

self.dead = False # 默认小鸟生命状态为活着

def birdUpdate(self):

if self.jump:

# 小鸟跳跃

self.jumpSpeed -= 1 # 速度递减,上升越来越慢

self.birdY -= self.jumpSpeed # 鸟Y轴坐标减小,小鸟上升

else:

# 小鸟坠落

self.gravity += 0.1 # 重力递增,下降越来越快

self.birdY += self.gravity # 鸟Y轴坐标增加,小鸟下降

self.birdRect[1] = self.birdY # 更改Y轴位置

class Pipeline(object):

"""定义一个管道类"""

def __init__(self):

"""定义初始化方法"""

self.wallx = 400 # 管道所在X轴坐标

self.pineUp = pygame.image.load("images/top.png")

self.pineDown = pygame.image.load("images/bottom.png")

def updatePipeline(self):

""""管道移动方法"""

self.wallx -= 5 # 管道X轴坐标递减,即管道向左移动

# 当管道运行到一定位置,即小鸟飞越管道,分数加1,并且重置管道

if self.wallx < -80:

global score

score += 1

self.wallx = 400

def createMap():

"""定义创建地图的方法"""

screen.fill((255, 255, 255)) # 填充颜色

screen.blit(background, (0, 0)) # 填入到背景

# 显示管道

screen.blit(Pipeline.pineUp, (Pipeline.wallx, -300)) # 上管道坐标位置

screen.blit(Pipeline.pineDown, (Pipeline.wallx, 500)) # 下管道坐标位置

Pipeline.updatePipeline() # 管道移动

# 显示小鸟

if Bird.dead: # 撞管道状态

Bird.status = 2

elif Bird.jump: # 起飞状态

Bird.status = 1

screen.blit(Bird.birdStatus[Bird.status], (Bird.birdX, Bird.birdY)) # 设置小鸟的坐标

Bird.birdUpdate() # 鸟移动

# 显示分数

screen.blit(font.render('Score:' + str(score), -1, (255, 255, 255)), (100, 50)) # 设置颜色及坐标位置

pygame.display.update() # 更新显示

def checkDead():

# 上方管子的矩形位置

upRect = pygame.Rect(Pipeline.wallx, -300,

Pipeline.pineUp.get_width() - 10,

Pipeline.pineUp.get_height())

# 下方管子的矩形位置

downRect = pygame.Rect(Pipeline.wallx, 500,

Pipeline.pineDown.get_width() - 10,

Pipeline.pineDown.get_height())

# 检测小鸟与上下方管子是否碰撞

if upRect.colliderect(Bird.birdRect) or downRect.colliderect(Bird.birdRect):

Bird.dead = True

# 检测小鸟是否飞出上下边界

if not 0 < Bird.birdRect[1] < height:

Bird.dead = True

return True

else:

return False

def getResutl():

final_text1 = "Game Over"

final_text2 = "Your final score is: " + str(score)

ft1_font = pygame.font.SysFont("Arial", 70) # 设置第一行文字字体

ft1_surf = font.render(final_text1, 1, (242, 3, 36)) # 设置第一行文字颜色

ft2_font = pygame.font.SysFont("Arial", 50) # 设置第二行文字字体

ft2_surf = font.render(final_text2, 1, (253, 177, 6)) # 设置第二行文字颜色

screen.blit(ft1_surf, [screen.get_width() / 2 - ft1_surf.get_width() / 2, 100]) # 设置第一行文字显示位置

screen.blit(ft2_surf, [screen.get_width() / 2 - ft2_surf.get_width() / 2, 200]) # 设置第二行文字显示位置

pygame.display.flip() # 更新整个待显示的Surface对象到屏幕上

if __name__ == '__main__':

"""主程序"""

pygame.init() # 初始化pygame

pygame.font.init() # 初始化字体

font = pygame.font.SysFont("ziti.ttf", 50) # 设置字体和大小

size = width, height = 400, 650 # 设置窗口

screen = pygame.display.set_mode(size) # 显示窗口

clock = pygame.time.Clock() # 设置时钟

Pipeline = Pipeline() # 实例化管道类

Bird = Bird() # 实例化鸟类

score = 0

while True:

clock.tick(30) # 每秒执行30次

# 轮询事件

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not Bird.dead:

Bird.jump = True # 跳跃

Bird.gravity = 5 # 重力

Bird.jumpSpeed = 5 # 跳跃速度,可以自己设置,控制速度

background = pygame.image.load("images/background.png") # 加载背景图片

if checkDead(): # 检测小鸟生命状态

getResutl() # 如果小鸟死亡,显示游戏总分数

else:

createMap() # 创建地图

pygame.quit()

2.Python简易时钟

源码分享:

'''

itbaizhan

'''

import turtle

import datetime

'''悬空移动'''

def move(distance):

turtle.penup()

turtle.forward(distance)

turtle.pendown()

'''创建表针turtle'''

def createHand(name, length):

turtle.reset()

move(-length * 0.01)

turtle.begin_poly()

turtle.forward(length * 1.01)

turtle.end_poly()

hand = turtle.get_poly()

turtle.register_shape(name, hand)

'''创建时钟'''

def createClock(radius):

turtle.reset()

turtle.pensize(7)

for i in range(60):

move(radius)

if i % 5 == 0:

turtle.forward(20)

move(-radius-20)

else:

turtle.dot(5)

move(-radius)

turtle.right(6)

'''获得今天是星期几'''

def getWeekday(today):

return ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'][today.weekday()]

'''获得今天的日期'''

def getDate(today):

return '%s年%s月%s日' % (today.year, today.month, today.day)

'''动态显示表针'''

def startTick(second_hand, minute_hand, hour_hand, printer):

today = datetime.datetime.today()

second = today.second + today.microsecond * 1e-6

minute = today.minute + second / 60.

hour = (today.hour + minute / 60) % 12

# 设置朝向

second_hand.setheading(6 * second)

minute_hand.setheading(6 * minute)

hour_hand.setheading(12 * hour)

turtle.tracer(False)

printer.forward(65)

printer.write(getWeekday(today), align='center', font=("Courier", 14, "bold"))code>

printer.forward(120)

printer.write('12', align='center', font=("Courier", 14, "bold"))code>

printer.back(250)

printer.write(getDate(today), align='center', font=("Courier", 14, "bold"))code>

printer.back(145)

printer.write('6', align='center', font=("Courier", 14, "bold"))code>

printer.home()

printer.right(92.5)

printer.forward(200)

printer.write('3', align='center', font=("Courier", 14, "bold"))code>

printer.left(2.5)

printer.back(400)

printer.write('9', align='center', font=("Courier", 14, "bold"))code>

printer.home()

turtle.tracer(True)

# 100ms调用一次

turtle.ontimer(lambda: startTick(second_hand, minute_hand, hour_hand, printer), 100)

'''开始运行时钟'''

def start():

# 不显示绘制时钟的过程

turtle.tracer(False)

turtle.mode('logo')

createHand('second_hand', 150)

createHand('minute_hand', 125)

createHand('hour_hand', 85)

# 秒, 分, 时

second_hand = turtle.Turtle()

second_hand.shape('second_hand')

minute_hand = turtle.Turtle()

minute_hand.shape('minute_hand')

hour_hand = turtle.Turtle()

hour_hand.shape('hour_hand')

for hand in [second_hand, minute_hand, hour_hand]:

hand.shapesize(1, 1, 3)

hand.speed(0)

# 用于打印日期等文字

printer = turtle.Turtle()

printer.hideturtle()

printer.penup()

createClock(160)

# 开始显示轨迹

turtle.tracer(True)

startTick(second_hand, minute_hand, hour_hand, printer)

turtle.mainloop()

if __name__ == '__main__':

start()

3.Python中国象棋

源码分享(部分源码):

#itbaizhan

import pygame

import time

import constants

from button import Button

import pieces

import computer

class MainGame():

window = None

Start_X = constants.Start_X

Start_Y = constants.Start_Y

Line_Span = constants.Line_Span

Max_X = Start_X + 8 * Line_Span

Max_Y = Start_Y + 9 * Line_Span

player1Color = constants.player1Color

player2Color = constants.player2Color

Putdownflag = player1Color

piecesSelected = None

button_go = None

piecesList = []

def start_game(self):

MainGame.window = pygame.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT])

pygame.display.set_caption("天青-中国象棋")

MainGame.button_go = Button(MainGame.window, "重新开始", constants.SCREEN_WIDTH - 100, 300) # 创建开始按钮

self.piecesInit()

while True:

time.sleep(0.1)

# 获取事件

MainGame.window.fill(constants.BG_COLOR)

self.drawChessboard()

#MainGame.button_go.draw_button()

self.piecesDisplay()

self.VictoryOrDefeat()

self.Computerplay()

self.getEvent()

pygame.display.update()

pygame.display.flip()

def drawChessboard(self):

mid_end_y = MainGame.Start_Y + 4 * MainGame.Line_Span

min_start_y = MainGame.Start_Y + 5 * MainGame.Line_Span

for i in range(0, 9):

x = MainGame.Start_X + i * MainGame.Line_Span

if i==0 or i ==8:

y = MainGame.Start_Y + i * MainGame.Line_Span

pygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, MainGame.Max_Y], 1)

else:

pygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, mid_end_y], 1)

pygame.draw.line(MainGame.window, constants.BLACK, [x, min_start_y], [x, MainGame.Max_Y], 1)

for i in range(0, 10):

x = MainGame.Start_X + i * MainGame.Line_Span

y = MainGame.Start_Y + i * MainGame.Line_Span

pygame.draw.line(MainGame.window, constants.BLACK, [MainGame.Start_X, y], [MainGame.Max_X, y], 1)

speed_dial_start_x = MainGame.Start_X + 3 * MainGame.Line_Span

speed_dial_end_x = MainGame.Start_X + 5 * MainGame.Line_Span

speed_dial_y1 = MainGame.Start_Y + 0 * MainGame.Line_Span

speed_dial_y2 = MainGame.Start_Y + 2 * MainGame.Line_Span

speed_dial_y3 = MainGame.Start_Y + 7 * MainGame.Line_Span

speed_dial_y4 = MainGame.Start_Y + 9 * MainGame.Line_Span

pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y1], [speed_dial_end_x, speed_dial_y2], 1)

pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y2],

[speed_dial_end_x, speed_dial_y1], 1)

pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y3],

[speed_dial_end_x, speed_dial_y4], 1)

pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y4],

[speed_dial_end_x, speed_dial_y3], 1)

def piecesInit(self):

MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color, 0,0))

MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color, 8, 0))

MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color, 2, 0))

MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color, 6, 0))

MainGame.piecesList.append(pieces.King(MainGame.player2Color, 4, 0))

MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color, 1, 0))

MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color, 7, 0))

MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color, 1, 2))

MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color, 7, 2))

MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color, 3, 0))

MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color, 5, 0))

MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 0, 3))

MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 2, 3))

MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 4, 3))

MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 6, 3))

MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 8, 3))

MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color, 0, 9))

MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color, 8, 9))

MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 2, 9))

MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 6, 9))

MainGame.piecesList.append(pieces.King(MainGame.player1Color, 4, 9))

MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 1, 9))

MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 7, 9))

MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color, 1, 7))

MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color, 7, 7))

MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color, 3, 9))

MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color, 5, 9))

MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 0, 6))

MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 2, 6))

MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 4, 6))

MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 6, 6))

MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 8, 6))

def piecesDisplay(self):

for item in MainGame.piecesList:

item.displaypieces(MainGame.window)

#MainGame.window.blit(item.image, item.rect)

def getEvent(self):

# 获取所有的事件

eventList = pygame.event.get()

for event in eventList:

if event.type == pygame.QUIT:

self.endGame()

elif event.type == pygame.MOUSEBUTTONDOWN:

pos = pygame.mouse.get_pos()

mouse_x = pos[0]

mouse_y = pos[1]

if (

mouse_x > MainGame.Start_X - MainGame.Line_Span / 2 and mouse_x < MainGame.Max_X + MainGame.Line_Span / 2) and (

mouse_y > MainGame.Start_Y - MainGame.Line_Span / 2 and mouse_y < MainGame.Max_Y + MainGame.Line_Span / 2):

# print( str(mouse_x) + "" + str(mouse_y))

# print(str(MainGame.Putdownflag))

if MainGame.Putdownflag != MainGame.player1Color:

return

click_x = round((mouse_x - MainGame.Start_X) / MainGame.Line_Span)

click_y = round((mouse_y - MainGame.Start_Y) / MainGame.Line_Span)

click_mod_x = (mouse_x - MainGame.Start_X) % MainGame.Line_Span

click_mod_y = (mouse_y - MainGame.Start_Y) % MainGame.Line_Span

if abs(click_mod_x - MainGame.Line_Span / 2) >= 5 and abs(

click_mod_y - MainGame.Line_Span / 2) >= 5:

# print("有效点:x="+str(click_x)+" y="+str(click_y))

# 有效点击点

self.PutdownPieces(MainGame.player1Color, click_x, click_y)

else:

print("out")code>

if MainGame.button_go.is_click():

#self.restart()

print("button_go click")

else:

print("button_go click out")

def PutdownPieces(self, t, x, y):

selectfilter=list(filter(lambda cm: cm.x == x and cm.y == y and cm.player == MainGame.player1Color,MainGame.piecesList))

if len(selectfilter):

MainGame.piecesSelected = selectfilter[0]

return

if MainGame.piecesSelected :

#print("1111")

arr = pieces.listPiecestoArr(MainGame.piecesList)

if MainGame.piecesSelected.canmove(arr, x, y):

self.PiecesMove(MainGame.piecesSelected, x, y)

MainGame.Putdownflag = MainGame.player2Color

else:

fi = filter(lambda p: p.x == x and p.y == y, MainGame.piecesList)

listfi = list(fi)

if len(listfi) != 0:

MainGame.piecesSelected = listfi[0]

def PiecesMove(self,pieces, x , y):

for item in MainGame.piecesList:

if item.x ==x and item.y == y:

MainGame.piecesList.remove(item)

pieces.x = x

pieces.y = y

print("move to " +str(x) +" "+str(y))

return True

def Computerplay(self):

if MainGame.Putdownflag == MainGame.player2Color:

print("轮到电脑了")

computermove = computer.getPlayInfo(MainGame.piecesList)

#if computer==None:

#return

piecemove = None

for item in MainGame.piecesList:

if item.x == computermove[0] and item.y == computermove[1]:

piecemove= item

self.PiecesMove(piecemove, computermove[2], computermove[3])

MainGame.Putdownflag = MainGame.player1Color

#判断游戏胜利

def VictoryOrDefeat(self):

txt =""

result = [MainGame.player1Color,MainGame.player2Color]

for item in MainGame.piecesList:

if type(item) ==pieces.King:

if item.player == MainGame.player1Color:

result.remove(MainGame.player1Color)

if item.player == MainGame.player2Color:

result.remove(MainGame.player2Color)

if len(result)==0:

return

if result[0] == MainGame.player1Color :

txt = "失败!"

else:

txt = "胜利!"

MainGame.window.blit(self.getTextSuface("%s" % txt), (constants.SCREEN_WIDTH - 100, 200))

MainGame.Putdownflag = constants.overColor

def getTextSuface(self, text):

pygame.font.init()

# print(pygame.font.get_fonts())

font = pygame.font.SysFont('kaiti', 18)

txt = font.render(text, True, constants.TEXT_COLOR)

return txt

def endGame(self):

print("exit")

exit()

if __name__ == '__main__':

MainGame().start_game()

4.Python吃豆豆小游戏

源码分享(部分源码):

'''

itbaizhan

'''

import os

import sys

import pygame

import Levels

'''定义一些必要的参数'''

BLACK = (0, 0, 0)

WHITE = (255, 255, 255)

BLUE = (0, 0, 255)

GREEN = (0, 255, 0)

RED = (255, 0, 0)

YELLOW = (255, 255, 0)

PURPLE = (255, 0, 255)

SKYBLUE = (0, 191, 255)

BGMPATH = os.path.join(os.getcwd(), 'resources/sounds/bg.mp3')

ICONPATH = os.path.join(os.getcwd(), 'resources/images/icon.png')

FONTPATH = os.path.join(os.getcwd(), 'resources/font/ALGER.TTF')

HEROPATH = os.path.join(os.getcwd(), 'resources/images/pacman.png')

BlinkyPATH = os.path.join(os.getcwd(), 'resources/images/Blinky.png')

ClydePATH = os.path.join(os.getcwd(), 'resources/images/Clyde.png')

InkyPATH = os.path.join(os.getcwd(), 'resources/images/Inky.png')

PinkyPATH = os.path.join(os.getcwd(), 'resources/images/Pinky.png')

'''开始某一关游戏'''

def startLevelGame(level, screen, font):

clock = pygame.time.Clock()

SCORE = 0

wall_sprites = level.setupWalls(SKYBLUE)

gate_sprites = level.setupGate(WHITE)

hero_sprites, ghost_sprites = level.setupPlayers(HEROPATH, [BlinkyPATH, ClydePATH, InkyPATH, PinkyPATH])

food_sprites = level.setupFood(YELLOW, WHITE)

is_clearance = False

while True:

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit(-1)

pygame.quit()

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_LEFT:

for hero in hero_sprites:

hero.changeSpeed([-1, 0])

hero.is_move = True

elif event.key == pygame.K_RIGHT:

for hero in hero_sprites:

hero.changeSpeed([1, 0])

hero.is_move = True

elif event.key == pygame.K_UP:

for hero in hero_sprites:

hero.changeSpeed([0, -1])

hero.is_move = True

elif event.key == pygame.K_DOWN:

for hero in hero_sprites:

hero.changeSpeed([0, 1])

hero.is_move = True

if event.type == pygame.KEYUP:

if (event.key == pygame.K_LEFT) or (event.key == pygame.K_RIGHT) or (event.key == pygame.K_UP) or (event.key == pygame.K_DOWN):

hero.is_move = False

screen.fill(BLACK)

for hero in hero_sprites:

hero.update(wall_sprites, gate_sprites)

hero_sprites.draw(screen)

for hero in hero_sprites:

food_eaten = pygame.sprite.spritecollide(hero, food_sprites, True)

SCORE += len(food_eaten)

wall_sprites.draw(screen)

gate_sprites.draw(screen)

food_sprites.draw(screen)

for ghost in ghost_sprites:

# 幽灵随机运动()

'''

res = ghost.update(wall_sprites, None)

while not res:

ghost.changeSpeed(ghost.randomDirection())

res = ghost.update(wall_sprites, None)

'''

# 指定幽灵运动路径

if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:

ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])

ghost.tracks_loc[1] += 1

else:

if ghost.tracks_loc[0] < len(ghost.tracks) - 1:

ghost.tracks_loc[0] += 1

elif ghost.role_name == 'Clyde':

ghost.tracks_loc[0] = 2

else:

ghost.tracks_loc[0] = 0

ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])

ghost.tracks_loc[1] = 0

if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:

ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])

else:

if ghost.tracks_loc[0] < len(ghost.tracks) - 1:

loc0 = ghost.tracks_loc[0] + 1

elif ghost.role_name == 'Clyde':

loc0 = 2

else:

loc0 = 0

ghost.changeSpeed(ghost.tracks[loc0][0: 2])

ghost.update(wall_sprites, None)

ghost_sprites.draw(screen)

score_text = font.render("Score: %s" % SCORE, True, RED)

screen.blit(score_text, [10, 10])

if len(food_sprites) == 0:

is_clearance = True

break

if pygame.sprite.groupcollide(hero_sprites, ghost_sprites, False, False):

is_clearance = False

break

pygame.display.flip()

clock.tick(10)

return is_clearance

'''显示文字'''

def showText(screen, font, is_clearance, flag=False):

clock = pygame.time.Clock()

msg = 'Game Over!' if not is_clearance else 'Congratulations, you won!'

positions = [[235, 233], [65, 303], [170, 333]] if not is_clearance else [[145, 233], [65, 303], [170, 333]]

surface = pygame.Surface((400, 200))

surface.set_alpha(10)

surface.fill((128, 128, 128))

screen.blit(surface, (100, 200))

texts = [font.render(msg, True, WHITE),

font.render('Press ENTER to continue or play again.', True, WHITE),

font.render('Press ESCAPE to quit.', True, WHITE)]

while True:

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

pygame.quit()

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_RETURN:

if is_clearance:

if not flag:

return

else:

main(initialize())

else:

main(initialize())

elif event.key == pygame.K_ESCAPE:

sys.exit()

pygame.quit()

for idx, (text, position) in enumerate(zip(texts, positions)):

screen.blit(text, position)

pygame.display.flip()

clock.tick(10)

'''初始化'''

def initialize():

pygame.init()

icon_image = pygame.image.load(ICONPATH)

pygame.display.set_icon(icon_image)

screen = pygame.display.set_mode([606, 606])

pygame.display.set_caption('吃豆人')

return screen

'''主函数'''

def main(screen):

pygame.mixer.init()

pygame.mixer.music.load(BGMPATH)

pygame.mixer.music.play(-1, 0.0)

pygame.font.init()

font_small = pygame.font.Font(FONTPATH, 18)

font_big = pygame.font.Font(FONTPATH, 24)

for num_level in range(1, Levels.NUMLEVELS+1):

if num_level == 1:

level = Levels.Level1()

is_clearance = startLevelGame(level, screen, font_small)

if num_level == Levels.NUMLEVELS:

showText(screen, font_big, is_clearance, True)

else:

showText(screen, font_big, is_clearance)

'''test'''

if __name__ == '__main__':

main(initialize())

5.Python幸运大转盘

源码分享(部分源码):

#itbaizhan

import pygame,sys

import math

import random

pygame.init() # 初始化pygame类

screen = pygame.display.set_mode((600, 600)) # 设置窗口大小

pygame.display.set_caption('幸运大转盘') # 设置窗口标题

tick = pygame.time.Clock()

fps = 10 # 设置刷新率,数字越大刷新率越高

picture = pygame.transform.scale(pygame.image.load("./幸运大转盘.png"), (600, 600))

bg=picture.convert()

picture = pygame.transform.scale(pygame.image.load("./1.png"), (30, 230))

hand = picture.convert_alpha()

rewardDict = {

'first level': (0, 0.03),

'second level': (0.03, 0.2),

'third level': (0.2, 1)

}

def rewardFun():

"""用户的得奖等级"""

# 生成一个0~1之间的随机数

number = random.random()

# 判断随机转盘是几等奖

for k, v in rewardDict.items():

if v[0] <= number < v[1]:

return k

def start():

while True:

for event in pygame.event.get():

# 处理退出事件

if event.type == pygame.QUIT:

pygame.quit()

sys.exit()

elif event.type == pygame.KEYDOWN:

if (event.key == pygame.K_ESCAPE):

pygame.quit()

sys.exit()

else:

return

screen.blit(bg,(0,0))

newRect = hand.get_rect(center=(300,150))

screen.blit(hand,newRect)

pygame.draw.circle(screen,(255,255,0),(300,300),50)

textFont = pygame.font.Font("./font.ttf", 80)

textSurface = textFont.render("go", True, (110, 55, 155))

screen.blit(textSurface, (270, 230))

pygame.display.update()

def middle():

angle = 0

while True:

posx = 300 + int(150 * math.sin(angle * math.pi / 180))

posy = 300 - int(150 * math.cos(angle * math.pi / 180))

print(posx, posy, math.sin(angle * math.pi / 180))

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

screen.blit(bg,(0,0))

newhand = pygame.transform.rotate(hand, -angle)

newRect = newhand.get_rect(center=(posx,posy))

screen.blit(newhand,newRect)

pygame.draw.circle(screen,(255,255,0),(300,300),50)

angle += 10

if angle > 500:

k = rewardFun()

end(k)

break

tick.tick(fps)

pygame.display.flip() # 刷新窗口

def end(k):

textFont = pygame.font.Font("./font.ttf", 50)

print("恭喜你,你抽中了"+k)

textSurface = textFont.render("your awards is :%s" % k, True, (110, 55, 155))

screen.fill((155, 155, 0))

screen.blit(textSurface, (30, 230))

if __name__ == '__main__':

start()

middle()

由于文章篇幅有限,文档资料内容较多,需要这些文档的朋友,可以加小助手微信免费获取,【保证100%免费】,中国人不骗中国人。

在这里插入图片描述

(扫码立即免费领取)

其他实战案例

在这里插入图片描述

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

在这里插入图片描述

在这里插入图片描述



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。