当前位置: 首页 > news >正文

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

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

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

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

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

  1. 飞扬的小鸟

  2. Python简易时钟

  3. Python中国象棋

  4. Python吃豆豆小游戏

  5. Python幸运大转盘

  6. Python简易植物大战僵尸

  7. Python2048小游戏

  8. Python俄罗斯方块

  9. Python 烟花

  10. Python 贪吃蛇

  11. Python 数字游戏

  12. 拼图游戏

  13. 滑雪小游戏

  14. 数独游戏

  15. 飞机大战

1.飞扬的小鸟

①游戏介绍:

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

游戏规则:

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

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

②源码分享:


#itbaizhan
import pygame
import sys
import randomclass 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 scorescore += 1self.wallx = 400def 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 = 2elif Bird.jump:            # 起飞状态Bird.status = 1screen.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 = Truereturn Trueelse:return Falsedef 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()                            # 初始化pygamepygame.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 = 0while 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-6minute = 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"))printer.forward(120)printer.write('12', align='center', font=("Courier", 14, "bold"))printer.back(250)printer.write(getDate(today), align='center', font=("Courier", 14, "bold"))printer.back(145)printer.write('6', align='center', font=("Courier", 14, "bold"))printer.home()printer.right(92.5)printer.forward(200)printer.write('3', align='center', font=("Courier", 14, "bold"))printer.left(2.5)printer.back(400)printer.write('9', align='center', font=("Courier", 14, "bold"))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 piecesimport computerclass MainGame():window = NoneStart_X = constants.Start_XStart_Y = constants.Start_YLine_Span = constants.Line_SpanMax_X = Start_X + 8 * Line_SpanMax_Y = Start_Y + 9 * Line_Spanplayer1Color = constants.player1Colorplayer2Color = constants.player2ColorPutdownflag = player1ColorpiecesSelected = Nonebutton_go = NonepiecesList = []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_Spanmin_start_y = MainGame.Start_Y + 5 * MainGame.Line_Spanfor i in range(0, 9):x = MainGame.Start_X + i * MainGame.Line_Spanif i==0 or i ==8:y = MainGame.Start_Y + i * MainGame.Line_Spanpygame.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_Spany = MainGame.Start_Y + i * MainGame.Line_Spanpygame.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_Spanspeed_dial_end_x =  MainGame.Start_X + 5 * MainGame.Line_Spanspeed_dial_y1 = MainGame.Start_Y + 0 * MainGame.Line_Spanspeed_dial_y2 = MainGame.Start_Y + 2 * MainGame.Line_Spanspeed_dial_y3 = MainGame.Start_Y + 7 * MainGame.Line_Spanspeed_dial_y4 = MainGame.Start_Y + 9 * MainGame.Line_Spanpygame.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:returnclick_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_Spanclick_mod_y = (mouse_y - MainGame.Start_Y) % MainGame.Line_Spanif 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")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]returnif 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.player2Colorelse: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 = xpieces.y = yprint("move to " +str(x) +" "+str(y))return Truedef Computerplay(self):if MainGame.Putdownflag == MainGame.player2Color:print("轮到电脑了")computermove = computer.getPlayInfo(MainGame.piecesList)#if computer==None:#returnpiecemove = Nonefor item in MainGame.piecesList:if item.x == computermove[0] and item.y == computermove[1]:piecemove= itemself.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:returnif result[0] == MainGame.player1Color :txt = "失败!"else:txt = "胜利!"MainGame.window.blit(self.getTextSuface("%s" % txt), (constants.SCREEN_WIDTH - 100, 200))MainGame.Putdownflag = constants.overColordef 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 txtdef 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 = 0wall_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 = Falsewhile 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 = Trueelif event.key == pygame.K_RIGHT:for hero in hero_sprites:hero.changeSpeed([1, 0])hero.is_move = Trueelif event.key == pygame.K_UP:for hero in hero_sprites:hero.changeSpeed([0, -1])hero.is_move = Trueelif event.key == pygame.K_DOWN:for hero in hero_sprites:hero.changeSpeed([0, 1])hero.is_move = Trueif 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 = Falsescreen.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] += 1else:if ghost.tracks_loc[0] < len(ghost.tracks) - 1:ghost.tracks_loc[0] += 1elif ghost.role_name == 'Clyde':ghost.tracks_loc[0] = 2else:ghost.tracks_loc[0] = 0ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])ghost.tracks_loc[1] = 0if 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] + 1elif ghost.role_name == 'Clyde':loc0 = 2else:loc0 = 0ghost.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 = Truebreakif pygame.sprite.groupcollide(hero_sprites, ghost_sprites, False, False):is_clearance = Falsebreakpygame.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:returnelse: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 randompygame.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 kdef 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:returnscreen.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 = 0while 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 += 10if angle > 500:k = rewardFun()end(k)breaktick.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%免费】,中国人不骗中国人。
在这里插入图片描述
(扫码立即免费领取)

其他实战案例

在这里插入图片描述

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

在这里插入图片描述
在这里插入图片描述

相关文章:

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

经常听到有朋友说&#xff0c;学习编程是一件非常枯燥无味的事情。其实&#xff0c;大家有没有认真想过&#xff0c;可能是我们的学习方法不对&#xff1f; 比方说&#xff0c;你有没有想过&#xff0c;可以通过打游戏来学编程&#xff1f; 今天我想跟大家分享几个Python小游…...

快速使用BRTR公式出具的大模型Prompt提示语

Role:文章模仿大师 Background: 你是一位文章模仿大师&#xff0c;擅长分析文章风格并进行模仿创作。老板常让你学习他人文章后进行模仿创作。 Attention: 请专注在文章模仿任务上&#xff0c;提供高质量的输出。 Profile: Author: 一博Version: 1.0Language: 中文Descri…...

Xilinx FPGA DDR4 接口的 PCB 准则

目录 1. 简介 1.1 FPGA-MIG 与 DDR4 介绍 1.2 DDR4 信号介绍 1.2.1 Clock Signals 1.2.2 Address and Command Signals 1.2.3 Control Signals 1.2.4 Data Signals 1.2.5 Other Signals 2. 通用存储器布线准则 3. Xilinx FPGA-MIG 的 PCB 准则 3.1 引脚配置 3.1.1 …...

神经网络 | Transformer 基本原理

目录 1 为什么使用 Transformer&#xff1f;2 Attention 注意力机制2.1 什么是 Q、K、V 矩阵&#xff1f;2.2 Attention Value 计算流程2.3 Self-Attention 自注意力机制2.3 Multi-Head Attention 多头注意力机制 3 Transformer 模型架构3.1 Positional Encoding 位置编…...

浅析 VO、DTO、DO、PO 的概念

文章目录 I 浅析 VO、DTO、DO、PO1.1 概念1.2 模型1.3 VO与DTO的区别I 浅析 VO、DTO、DO、PO 1.1 概念 VO(View Object) 视图对象,用于展示层,它的作用是把某个指定页面(或组件)的所有数据封装起来。DTO(Data Transfer Object): 数据传输对象,这个概念来源于J2EE的设…...

7.8 CompletableFuture

Future 接口理论知识复习 Future 接口&#xff08;FutureTask 实现类&#xff09;定义了操作异步任务执行的一些方法&#xff0c;如获取异步任务的执行结果、取消任务的执行、判断任务是否被取消、判断任务执行是否完毕等。 比如主线程让一个子线程去执行任务&#xff0c;子线…...

iPad锁屏密码忘记怎么办?有什么方法可以解锁?

当我们在日常使用iPad时&#xff0c;偶尔可能会遇到忘记锁屏密码的尴尬情况。这时&#xff0c;不必过于担心&#xff0c;因为有多种方法可以帮助您解锁iPad。接下来&#xff0c;小编将为您详细介绍这些解决方案。 一、使用iCloud的“查找我的iPhone”功能 如果你曾经启用了“查…...

了解并缓解 IP 欺骗攻击

欺骗是黑客用来未经授权访问计算机或网络的一种网络攻击&#xff0c;IP 欺骗是其他欺骗方法中最常见的欺骗类型。通过 IP 欺骗&#xff0c;攻击者可以隐藏 IP 数据包的真实来源&#xff0c;使攻击来源难以知晓。一旦访问网络或设备/主机&#xff0c;网络犯罪分子通常会挖掘其中…...

java LogUtil输出日志打日志的class文件内具体方法和行号

最近琢磨怎么把日志打的更清晰&#xff0c;方便查找问题&#xff0c;又不需要在每个class内都创建Logger对象&#xff0c;还带上不同的颜色做区分&#xff0c;简直不要太爽。利用堆栈的方向顺序拿到日志的class问题。看效果&#xff0c;直接上代码。 1、demo test 2、输出效果…...

02. Hibernate 初体验之持久化对象

1. 前言 本节课程让我们一起体验 Hibernate 的魅力&#xff01;编写第一个基于 Hibernate 的实例程序。 在本节课程中&#xff0c;你将学到 &#xff1a; Hibernate 的版本发展史&#xff1b;持久化对象的特点。 为了更好地讲解这个内容&#xff0c;这个初体验案例分上下 2…...

MySQL超详细学习教程,2023年硬核学习路线

文章目录 前言1. 数据库的相关概念1.1 数据1.2 数据库1.3 数据库管理系统1.4 数据库系统1.5 SQL 2. MySQL数据库2.1 MySQL安装2.2 MySQL配置2.2.1 添加环境变量2.2.2 新建配置文件2.2.3 初始化MySQL2.2.4 注册MySQL服务2.2.5 启动MySQL服务 2.3 MySQL登录和退出2.4 MySQL卸载2.…...

初识SpringBoot

1.Maven Maven是⼀个项⽬管理⼯具, 通过pom.xml⽂件的配置获取jar包&#xff0c;⽽不⽤⼿动去添加jar包 主要功能 项⽬构建管理依赖 构建Maven项目 1.1项目构建 Maven 提供了标准的,跨平台(Linux, Windows, MacOS等)的⾃动化项⽬构建⽅式 当我们开发了⼀个项⽬之后, 代…...

Qt之元对象系统

Qt的元对象系统提供了信号和槽机制&#xff08;用于对象间的通信&#xff09;、运行时类型信息和动态属性系统。 元对象系统基于三个要素&#xff1a; 1、QObject类为那些可以利用元对象系统的对象提供了一个基类。 2、在类声明中使用Q_OBJECT宏用于启用元对象特性&#xff0c…...

Provider(1)- 什么是AudioBufferProvider

什么是AudioBufferProvider&#xff1f; 顾名思义&#xff0c;Audio音频数据缓冲提供&#xff0c;就是提供音频数据的缓冲类&#xff0c;而且这个AudioBufferProvider派生出许多子类&#xff0c;每个子类有不同的用途&#xff0c;至关重要&#xff1b;那它在Android哪个地方使…...

加密与安全_密钥体系的三个核心目标之完整性解决方案

文章目录 Pre机密性完整性1. 哈希函数&#xff08;Hash Function&#xff09;定义特征常见算法应用散列函数常用场景散列函数无法解决的问题 2. 消息认证码&#xff08;MAC&#xff09;概述定义常见算法工作原理如何使用 MACMAC 的问题 不可否认性数字签名&#xff08;Digital …...

【C++】:继承[下篇](友元静态成员菱形继承菱形虚拟继承)

目录 一&#xff0c;继承与友元二&#xff0c;继承与静态成员三&#xff0c;复杂的菱形继承及菱形虚拟继承四&#xff0c;继承的总结和反思 点击跳转上一篇文章&#xff1a; 【C】&#xff1a;继承(定义&&赋值兼容转换&&作用域&&派生类的默认成员函数…...

昇思25天学习打卡营第13天|基于MindNLP+MusicGen生成自己的个性化音乐

关于MindNLP MindNLP是一个依赖昇思MindSpore向上生长的NLP&#xff08;自然语言处理&#xff09;框架&#xff0c;旨在利用MindSpore的优势特性&#xff0c;如函数式融合编程、动态图功能、数据处理引擎等&#xff0c;致力于提供高效、易用的NLP解决方案。通过全面拥抱Huggin…...

nigix的下载使用

1、官网&#xff1a;https://nginx.org/en/download.html 双击打开 nginx的默认端口是80 配置文件 默认访问页面 在目录下新建pages&#xff0c;放入图片 在浏览器中输入地址进行访问 可以在电脑中配置本地域名 Windows设置本地DNS域名解析hosts文件配置 文件地址&#xf…...

nginx+lua 实现URL重定向(根据传入的参数条件)

程序版本说明 程序版本URLnginx1.27.0https://nginx.org/download/nginx-1.27.0.tar.gzngx_devel_kitv0.3.3https://github.com/simpl/ngx_devel_kit/archive/v0.3.3.tar.gzluajitv2.1https://github.com/openresty/luajit2/archive/refs/tags/v2.1-20240626.tar.gzlua-nginx-m…...

算法学习笔记(8.4)-完全背包问题

目录 Question&#xff1a; 图例&#xff1a; 动态规划思路 2 代码实现&#xff1a; 3 空间优化&#xff1a; 代码实现&#xff1a; 下面是0-1背包和完全背包具体的例题&#xff1a; 代码实现&#xff1a; 图例&#xff1a; 空间优化代码示例 Question&#xff1a; 给定n个物品…...

vscode里如何用git

打开vs终端执行如下&#xff1a; 1 初始化 Git 仓库&#xff08;如果尚未初始化&#xff09; git init 2 添加文件到 Git 仓库 git add . 3 使用 git commit 命令来提交你的更改。确保在提交时加上一个有用的消息。 git commit -m "备注信息" 4 …...

python打卡day49

知识点回顾&#xff1a; 通道注意力模块复习空间注意力模块CBAM的定义 作业&#xff1a;尝试对今天的模型检查参数数目&#xff0c;并用tensorboard查看训练过程 import torch import torch.nn as nn# 定义通道注意力 class ChannelAttention(nn.Module):def __init__(self,…...

突破不可导策略的训练难题:零阶优化与强化学习的深度嵌合

强化学习&#xff08;Reinforcement Learning, RL&#xff09;是工业领域智能控制的重要方法。它的基本原理是将最优控制问题建模为马尔可夫决策过程&#xff0c;然后使用强化学习的Actor-Critic机制&#xff08;中文译作“知行互动”机制&#xff09;&#xff0c;逐步迭代求解…...

MongoDB学习和应用(高效的非关系型数据库)

一丶 MongoDB简介 对于社交类软件的功能&#xff0c;我们需要对它的功能特点进行分析&#xff1a; 数据量会随着用户数增大而增大读多写少价值较低非好友看不到其动态信息地理位置的查询… 针对以上特点进行分析各大存储工具&#xff1a; mysql&#xff1a;关系型数据库&am…...

通过Wrangler CLI在worker中创建数据库和表

官方使用文档&#xff1a;Getting started Cloudflare D1 docs 创建数据库 在命令行中执行完成之后&#xff0c;会在本地和远程创建数据库&#xff1a; npx wranglerlatest d1 create prod-d1-tutorial 在cf中就可以看到数据库&#xff1a; 现在&#xff0c;您的Cloudfla…...

大型活动交通拥堵治理的视觉算法应用

大型活动下智慧交通的视觉分析应用 一、背景与挑战 大型活动&#xff08;如演唱会、马拉松赛事、高考中考等&#xff09;期间&#xff0c;城市交通面临瞬时人流车流激增、传统摄像头模糊、交通拥堵识别滞后等问题。以演唱会为例&#xff0c;暖城商圈曾因观众集中离场导致周边…...

Day131 | 灵神 | 回溯算法 | 子集型 子集

Day131 | 灵神 | 回溯算法 | 子集型 子集 78.子集 78. 子集 - 力扣&#xff08;LeetCode&#xff09; 思路&#xff1a; 笔者写过很多次这道题了&#xff0c;不想写题解了&#xff0c;大家看灵神讲解吧 回溯算法套路①子集型回溯【基础算法精讲 14】_哔哩哔哩_bilibili 完…...

【CSS position 属性】static、relative、fixed、absolute 、sticky详细介绍,多层嵌套定位示例

文章目录 ★ position 的五种类型及基本用法 ★ 一、position 属性概述 二、position 的五种类型详解(初学者版) 1. static(默认值) 2. relative(相对定位) 3. absolute(绝对定位) 4. fixed(固定定位) 5. sticky(粘性定位) 三、定位元素的层级关系(z-i…...

使用van-uploader 的UI组件,结合vue2如何实现图片上传组件的封装

以下是基于 vant-ui&#xff08;适配 Vue2 版本 &#xff09;实现截图中照片上传预览、删除功能&#xff0c;并封装成可复用组件的完整代码&#xff0c;包含样式和逻辑实现&#xff0c;可直接在 Vue2 项目中使用&#xff1a; 1. 封装的图片上传组件 ImageUploader.vue <te…...

在Ubuntu中设置开机自动运行(sudo)指令的指南

在Ubuntu系统中&#xff0c;有时需要在系统启动时自动执行某些命令&#xff0c;特别是需要 sudo权限的指令。为了实现这一功能&#xff0c;可以使用多种方法&#xff0c;包括编写Systemd服务、配置 rc.local文件或使用 cron任务计划。本文将详细介绍这些方法&#xff0c;并提供…...