当前位置: 首页 > 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个物品…...

C++catch (...)陈述

catch (...)陈述 例外处理可以有多个catch&#xff0c;如果catch后的小括弧里面放...&#xff0c;就表示不限型态种类的任何例外。 举例如下 #include <iostream>int main() {int i -1;try {if (i > 0) {throw 0;}throw 2.0;}catch (const int e) {std::cout <…...

Redis实践

Redis实践 使用复杂度高的命令 如果在使用Redis时&#xff0c;发现访问延迟突然增大&#xff0c;如何进行排查&#xff1f; 首先&#xff0c;第一步&#xff0c;建议你去查看一下Redis的慢日志。Redis提供了慢日志命令的统计功能&#xff0c;我们通过以下设置&#xff0c;就…...

【Lora模型推荐】Stable Diffusion创作具有玉石翡翠质感的图标设计

站长素材AI教程是站长之家旗下AI绘图教程平台 海量AI免费教程&#xff0c;每日更新干货内容 想要深入学习更多AI绘图教程&#xff0c;请访问站长素材AI教程网&#xff1a; AI教程_深度学习入门指南 - 站长素材 (chinaz.com) logo版权归各公司所有&#xff01;本笔记仅供AIGC…...

vscode 远程开发

目录 vscode 远程连接 选择 Python 环境 vscode 远程连接 按 CtrlShiftP 打开命令面板。输入并选择 Remote-SSH: Open SSH Configuration File...。选择 ~/.ssh/config 文件&#xff08;如果有多个选项&#xff09;。在打开的文件中添加或修改你的 SSH 配置。 这个可以右键…...

前端Vue组件化实践:打造灵活可维护的地址管理组件

随着前端技术的不断演进&#xff0c;复杂度和开发难度也随之上升。传统的一体化开发模式使得每次小小的修改或功能增加都可能牵一发而动全身&#xff0c;严重影响了开发效率和维护成本。组件化开发作为一种解决方案&#xff0c;通过模块化、独立化的开发方式&#xff0c;实现了…...

虚幻引擎ue5游戏运行界面白茫茫一片,怎么处理

根剧下图顺序即可调节游戏运行界面光照问题&#xff1a; 在大纲里找到post&#xff0c;然后选中它&#xff0c;找到Exposure 把最低亮度和最高亮度的0改为1即可...

《代理选择与反爬虫策略探究:如何优化网络爬虫效率与稳定性》

代理IP如何选以及常见反爬策略 为什么需要代理&#xff1f; 因为有的网站会封IP&#xff0c;用户如果没有登录&#xff0c;那IP就是身份标识&#xff0c;如果网站发现用户行为异常就非常可能封IP 什么是代理IP 就是让一个人帮你转交请求&#xff0c;帮你转交的人对面不熟&a…...

Kotlin Flow 防抖 节流

防抖和节流是针对响应跟不上触发频率这类问题的两种解决方案。 一:防抖&#xff08;debounce&#xff09;的概念&#xff1a; 防抖是指当持续触发事件时&#xff0c;一定时间段内没有再触发事件&#xff0c;事件处理函数才会执行一次&#xff0c; 如果设定时间到来之前&#x…...

Android Studio下载与安装

Android Studio下载与安装_android studio下载安装-CSDN博客...

【LC刷题】DAY24:122 55 45 1005

122. 买卖股票的最佳时机 II class Solution { public:int maxProfit(vector<int>& prices) {int result 0;for(int i 1; i < prices.size(); i ){result max(prices[i] - prices[ i - 1], 0);}return result;} };55. 跳跃游戏 link class Solution { public…...

个人网站能 做淘客吗/怎么自己创建网站

进大厂本来就很难了&#xff0c;不过做足了准备&#xff0c;你会发现很多问题都迎刃而解了&#xff0c;当然有时候运气也占了一部分&#xff0c;除了运气以外&#xff0c;当然与我自身的努力也是分不开的。运气也是实力的一部分&#xff0c;毕竟天助自助者~ 每次到年底做总结的…...

ps个人主页设计/百度搜索引擎优化方式

一、在canvas画布中如何加载图片---用drawImage( )方法drawImage用法的三种情况&#xff1a;1、在画布指定位置定义图像ctx.drawImage(img,x,y);注&#xff1a;此时画布上显示的图片大小是图片的默认大小2、在画布上定位图像&#xff0c;并规定图像的宽度和高度&#xff1a;ctx…...

温州网站制作费用/星巴克网络营销案例分析

[NOIP2017 普及组] 棋盘 题目背景 NOIP2017 普及组 T3 题目描述 有一个mmm \times mmm的棋盘&#xff0c;棋盘上每一个格子可能是红色、黄色或没有任何颜色的。你现在要从棋盘的最左上角走到棋盘的最右下角。 任何一个时刻&#xff0c;你所站在的位置必须是有颜色的&#…...

网络外贸平台有哪些/win10系统优化

每一个TCP套接口有一个发送缓冲区&#xff0c;可以用SO_SNDBUF套接口选项来改变这个缓冲区的大小。当应用进程调用write时&#xff0c;内核从应用进程的缓冲区中拷贝所有数据到套接口的发送缓冲区。如果套接口的发送缓冲区容不下应用程序的所有数据(或是应用进程的缓冲区大于套…...

腾博会的网站是什么/百度关键词seo推广

基础知识 jwt是由三部分构成的&#xff0c;第一部分是头部&#xff08;header&#xff09;&#xff0c;第二部分是载荷&#xff08;payload&#xff09;&#xff0c;第三部分为签证&#xff08;signature&#xff09; 头部 头部声明了类型和加密方法&#xff0c;如下 {typ:…...

网站备案到期了怎么办/网站需要怎么优化比较好

文章目录类适配器代码对象适配器代码类适配器 SDCard 是一个接口&#xff0c;代表了 SD 卡本身具有的功能SDCardImpl 是一个具体的实现类&#xff0c;代表了 SDCard 一种具体的实现形式TFCard 是一个接口&#xff0c;代表了 TF 卡本身具有的功能TFCardImpl 是一个具体的实现类…...