当前位置:   article > 正文

python游戏代码大全可复制,python超简单小游戏代码

游戏代码大全可复制

大家好,小编来为大家解答以下问题,python游戏编程入门游戏代码,python游戏代码大全可复制,现在让我们一起来看看吧!

大家好,小编为大家解答简单的python小游戏代码的问题。很多人还不知道python简单的小游戏代码,现在让我们一起来看看吧!

e89e28975f5d25088ec4795f49fa9e5d.gif

大家好,我是小F~

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

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

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

相关文件及代码都已上传,公众号回复【游戏】即可获取python一级证书有用吗

接下来就一起来看看吧~

1、飞机大战

42eafd0d93328ca02763f59f398701ac.png

源码分享:

  1. import random
  2. import pygame
  3. from objects import Background, Player, Enemy, Bullet, Explosion, Fuel, \
  4.                     Powerup, Button, Message, BlinkingText
  5. pygame.init()
  6. SCREEN = WIDTH, HEIGHT = 288512
  7. info = pygame.display.Info()
  8. width = info.current_w
  9. height = info.current_h
  10. if width >= height:
  11.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
  12. else:
  13.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)
  14. clock = pygame.time.Clock()
  15. FPS = 60
  16. # COLORS **********************************************************************
  17. WHITE = (255255255)
  18. BLUE = (30144,255)
  19. RED = (25500)
  20. GREEN = (02550)
  21. BLACK = (0020)
  22. # IMAGES **********************************************************************
  23. plane_img = pygame.image.load('Assets/plane.png')
  24. logo_img = pygame.image.load('Assets/logo.png')
  25. fighter_img = pygame.image.load('Assets/fighter.png')
  26. clouds_img = pygame.image.load('Assets/clouds.png')
  27. clouds_img = pygame.transform.scale(clouds_img, (WIDTH, 350))
  28. home_img = pygame.image.load('Assets/Buttons/homeBtn.png')
  29. replay_img = pygame.image.load('Assets/Buttons/replay.png')
  30. sound_off_img = pygame.image.load("Assets/Buttons/soundOffBtn.png")
  31. sound_on_img = pygame.image.load("Assets/Buttons/soundOnBtn.png")
  32. # BUTTONS *********************************************************************
  33. home_btn = Button(home_img, (2424), WIDTH // 4 - 18, HEIGHT//2 + 120)
  34. replay_btn = Button(replay_img, (36,36), WIDTH // 2  - 18, HEIGHT//2 + 115)
  35. sound_btn = Button(sound_on_img, (2424), WIDTH - WIDTH // 4 - 18, HEIGHT//2 + 120)
  36. # FONTS ***********************************************************************
  37. game_over_font = 'Fonts/ghostclan.ttf'
  38. tap_to_play_font = 'Fonts/BubblegumSans-Regular.ttf'
  39. score_font = 'Fonts/DalelandsUncialBold-82zA.ttf'
  40. final_score_font = 'Fonts/DroneflyRegular-K78LA.ttf'
  41. game_over_msg = Message(WIDTH//2, 230, 30, 'Game Over', game_over_font, WHITE, win)
  42. score_msg = Message(WIDTH-502830'0', final_score_font, RED, win)
  43. final_score_msg = Message(WIDTH//2, 280, 30, '0', final_score_font, RED, win)
  44. tap_to_play_msg = tap_to_play = BlinkingText(WIDTH//2, HEIGHT-60, 25, "Tap To Play",
  45.                  tap_to_play_font, WHITE, win)
  46. # SOUNDS **********************************************************************
  47. player_bullet_fx = pygame.mixer.Sound('Sounds/gunshot.wav')
  48. click_fx = pygame.mixer.Sound('Sounds/click.mp3')
  49. collision_fx = pygame.mixer.Sound('Sounds/mini_exp.mp3')
  50. blast_fx = pygame.mixer.Sound('Sounds/blast.wav')
  51. fuel_fx = pygame.mixer.Sound('Sounds/fuel.wav')
  52. pygame.mixer.music.load('Sounds/Defrini - Spookie.mp3')
  53. pygame.mixer.music.play(loops=-1)
  54. pygame.mixer.music.set_volume(0.1)
  55. # GROUPS & OBJECTS ************************************************************
  56. bg = Background(win)
  57. p = Player(144, HEIGHT - 100)
  58. enemy_group = pygame.sprite.Group()
  59. player_bullet_group = pygame.sprite.Group()
  60. enemy_bullet_group = pygame.sprite.Group()
  61. explosion_group = pygame.sprite.Group()
  62. fuel_group = pygame.sprite.Group()
  63. powerup_group = pygame.sprite.Group()
  64. # FUNCTIONS *******************************************************************
  65. def shoot_bullet():
  66.     x, y = p.rect.center[0], p.rect.y
  67.     if p.powerup > 0:
  68.         for dx in range(-34):
  69.             b = Bullet(x, y, 4, dx)
  70.             player_bullet_group.add(b)
  71.         p.powerup -= 1
  72.     else:
  73.         b = Bullet(x-30, y, 6)
  74.         player_bullet_group.add(b)
  75.         b = Bullet(x+30, y, 6)
  76.         player_bullet_group.add(b)
  77.     player_bullet_fx.play()
  78. def reset():
  79.     enemy_group.empty()
  80.     player_bullet_group.empty()
  81.     enemy_bullet_group.empty()
  82.     explosion_group.empty()
  83.     fuel_group.empty()
  84.     powerup_group.empty()
  85.     p.reset(p.x, p.y)
  86. # VARIABLES *******************************************************************
  87. level = 1
  88. plane_destroy_count = 0
  89. plane_frequency = 5000
  90. start_time = pygame.time.get_ticks()
  91. moving_left = False
  92. moving_right = False
  93. home_page = True
  94. game_page = False
  95. score_page = False
  96. score = 0
  97. sound_on = True
  98. running = True
  99. while running:
  100.     for event in pygame.event.get():
  101.         if event.type == pygame.QUIT:
  102.             running = False
  103.         if event.type == pygame.KEYDOWN:
  104.             if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
  105.                 running = False
  106.         if event.type == pygame.KEYDOWN and game_page:
  107.             if event.key == pygame.K_LEFT:
  108.                 moving_left = True
  109.             if event.key == pygame.K_RIGHT:
  110.                 moving_right = True
  111.             if event.key == pygame.K_SPACE:
  112.                 shoot_bullet()
  113.         if event.type == pygame.MOUSEBUTTONDOWN:
  114.             if home_page:
  115.                 home_page = False
  116.                 game_page = True
  117.                 click_fx.play()
  118.             elif game_page:
  119.                 x, y = event.pos
  120.                 if p.rect.collidepoint((x,y)):
  121.                     shoot_bullet()
  122.                 elif x <= WIDTH // 2:
  123.                     moving_left = True
  124.                 elif x > WIDTH // 2:
  125.                     moving_right = True
  126.         if event.type == pygame.KEYUP:
  127.             moving_left = False
  128.             moving_right = False
  129.         if event.type == pygame.MOUSEBUTTONUP:
  130.             moving_left = False
  131.             moving_right = False
  132.     if home_page:
  133.         win.fill(BLACK)
  134.         win.blit(logo_img, (3080))
  135.         win.blit(fighter_img, (WIDTH//2 - 50, HEIGHT//2))
  136.         pygame.draw.circle(win, WHITE, (WIDTH//2, HEIGHT//2 + 50), 50, 4)
  137.         tap_to_play_msg.update()
  138.     if score_page:
  139.         win.fill(BLACK)
  140.         win.blit(logo_img, (3050))
  141.         game_over_msg.update()
  142.         final_score_msg.update(score)
  143.         if home_btn.draw(win):
  144.             home_page = True
  145.             game_page = False
  146.             score_page = False
  147.             reset()
  148.             click_fx.play()
  149.             plane_destroy_count = 0
  150.             level = 1
  151.             score = 0
  152.         if replay_btn.draw(win):
  153.             score_page = False
  154.             game_page = True
  155.             reset()
  156.             click_fx.play()
  157.             plane_destroy_count = 0
  158.             score = 0
  159.         if sound_btn.draw(win):
  160.             sound_on = not sound_on
  161.             if sound_on:
  162.                 sound_btn.update_image(sound_on_img)
  163.                 pygame.mixer.music.play(loops=-1)
  164.             else:
  165.                 sound_btn.update_image(sound_off_img)
  166.                 pygame.mixer.music.stop()
  167.     if game_page:
  168.         current_time = pygame.time.get_ticks()
  169.         delta_time = current_time - start_time
  170.         if delta_time >= plane_frequency:
  171.             if level == 1:
  172.                 type = 1
  173.             elif level == 2:
  174.                 type = 2
  175.             elif level == 3:
  176.                 type = 3
  177.             elif level == 4:
  178.                 type = random.randint(45)
  179.             elif level == 5:
  180.                 type = random.randint(15)
  181.             x = random.randint(10, WIDTH - 100)
  182.             e = Enemy(x, -150type)
  183.             enemy_group.add(e)
  184.             start_time = current_time
  185.         if plane_destroy_count:
  186.             if plane_destroy_count % 5 == 0 and level < 5:
  187.                 level += 1
  188.                 plane_destroy_count = 0
  189.         p.fuel -= 0.05
  190.         bg.update(1)
  191.         win.blit(clouds_img, (070))
  192.         p.update(moving_left, moving_right, explosion_group)
  193.         p.draw(win)
  194.         player_bullet_group.update()
  195.         player_bullet_group.draw(win)
  196.         enemy_bullet_group.update()
  197.         enemy_bullet_group.draw(win)
  198.         explosion_group.update()
  199.         explosion_group.draw(win)
  200.         fuel_group.update()
  201.         fuel_group.draw(win)
  202.         powerup_group.update()
  203.         powerup_group.draw(win)
  204.         enemy_group.update(enemy_bullet_group, explosion_group)
  205.         enemy_group.draw(win)
  206.         if p.alive:
  207.             player_hit = pygame.sprite.spritecollide(p, enemy_bullet_group, False)
  208.             for bullet in player_hit:
  209.                 p.health -= bullet.damage
  210.                 x, y = bullet.rect.center
  211.                 explosion = Explosion(x, y, 1)
  212.                 explosion_group.add(explosion)
  213.                 bullet.kill()
  214.                 collision_fx.play()
  215.             for bullet in player_bullet_group:
  216.                 planes_hit = pygame.sprite.spritecollide(bullet, enemy_group, False)
  217.                 for plane in planes_hit:
  218.                     plane.health -= bullet.damage
  219.                     if plane.health <= 0:
  220.                         x, y = plane.rect.center
  221.                         rand = random.random()
  222.                         if rand >= 0.9:
  223.                             power = Powerup(x, y)
  224.                             powerup_group.add(power)
  225.                         elif rand >= 0.3:
  226.                             fuel = Fuel(x, y)
  227.                             fuel_group.add(fuel)
  228.                         plane_destroy_count += 1
  229.                         blast_fx.play()
  230.                     x, y = bullet.rect.center
  231.                     explosion = Explosion(x, y, 1)
  232.                     explosion_group.add(explosion)
  233.                     bullet.kill()
  234.                     collision_fx.play()
  235.             player_collide = pygame.sprite.spritecollide(p, enemy_group, True)
  236.             if player_collide:
  237.                 x, y = p.rect.center
  238.                 explosion = Explosion(x, y, 2)
  239.                 explosion_group.add(explosion)
  240.                 x, y = player_collide[0].rect.center
  241.                 explosion = Explosion(x, y, 2)
  242.                 explosion_group.add(explosion)
  243.                 p.health = 0
  244.                 p.alive = False
  245.             if pygame.sprite.spritecollide(p, fuel_group, True):
  246.                 p.fuel += 25
  247.                 if p.fuel >= 100:
  248.                     p.fuel = 100
  249.                 fuel_fx.play()
  250.             if pygame.sprite.spritecollide(p, powerup_group, True):
  251.                 p.powerup += 2
  252.                 fuel_fx.play()
  253.         if not p.alive or p.fuel <= -10:
  254.             if len(explosion_group) == 0:
  255.                 game_page = False
  256.                 score_page = True
  257.                 reset()
  258.         score += 1
  259.         score_msg.update(score)
  260.         fuel_color = RED if p.fuel <= 40 else GREEN
  261.         pygame.draw.rect(win, fuel_color, (3020, p.fuel, 10), border_radius=4)
  262.         pygame.draw.rect(win, WHITE, (302010010), 2, border_radius=4)
  263.         pygame.draw.rect(win, BLUE, (3032, p.health, 10), border_radius=4)
  264.         pygame.draw.rect(win, WHITE, (303210010), 2, border_radius=4)
  265.         win.blit(plane_img, (1015))
  266.     pygame.draw.rect(win, WHITE, (0,0, WIDTH, HEIGHT), 5, border_radius=4)
  267.     clock.tick(FPS)
  268.     pygame.display.update()
  269. pygame.quit()
2、愤怒的墙
7d7c9eaa34401b50ca051a06b15d0a5b.png

源码分享:

  1. import pygame
  2. import random
  3. from objects import Player, Bar, Ball, Block, ScoreCard, Message, Particle, generate_particles
  4. pygame.init()
  5. SCREEN = WIDTH, HEIGHT = 288512
  6. info = pygame.display.Info()
  7. width = info.current_w
  8. height = info.current_h
  9. if width >= height:
  10.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
  11. else:
  12.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)
  13. clock = pygame.time.Clock()
  14. FPS = 45
  15. # COLORS
  16. RED = (25500)
  17. WHITE = (255255255)
  18. BLACK = (000)
  19. GRAY = (546979)
  20. c_list = [RED, BLACK, WHITE]
  21. # Fonts
  22. pygame.font.init()
  23. score_font = pygame.font.Font('Fonts/BubblegumSans-Regular.ttf'50)
  24. # Sounds
  25. coin_fx = pygame.mixer.Sound('Sounds/coin.mp3')
  26. death_fx = pygame.mixer.Sound('Sounds/death.mp3')
  27. move_fx = pygame.mixer.Sound('Sounds/move.mp3')
  28. # backgrounds
  29. bg_list = []
  30. for i in range(1,5):
  31.     if i == 2:
  32.         ext = "jpeg"
  33.     else:
  34.         ext = "jpg"
  35.     img = pygame.image.load(f"Assets/Backgrounds/bg{i}.{ext}")
  36.     img = pygame.transform.scale(img, (WIDTH, HEIGHT))
  37.     bg_list.append(img)
  38. home_bg = pygame.image.load(f"Assets/Backgrounds/home.jpeg")
  39. bg = home_bg
  40. # objects
  41. bar_group = pygame.sprite.Group()
  42. ball_group = pygame.sprite.Group()
  43. block_group = pygame.sprite.Group()
  44. destruct_group = pygame.sprite.Group()
  45. win_particle_group = pygame.sprite.Group()
  46. bar_gap = 120
  47. particles = []
  48. p = Player(win)
  49. score_card = ScoreCard(14040, win)
  50. # Functions
  51. def destroy_bird():
  52.     x, y = p.rect.center
  53.     for i in range (50):
  54.         c = random.choice(c_list)
  55.         particle = Particle(x,y, 1,c, win)
  56.         destruct_group.add(particle)
  57. def win_particles():
  58.     for x,y in [(40120), (WIDTH - 20240), (15, HEIGHT - 30)]:
  59.         for i in range(10):
  60.             particle = Particle (x,y, 2, WHITE, win)
  61.             win_particle_group.add(particle)
  62. # Messages
  63. title_font = "Fonts/Robus-BWqOd.otf"
  64. dodgy = Message(13490100"Angry",title_font, WHITE, win)
  65. walls = Message(16414580"Walls",title_font, WHITE, win)
  66. tap_to_play_font = "Fonts/DebugFreeTrial-MVdYB.otf"
  67. tap_to_play = Message(14440032"TAP TO PLAY",tap_to_play_font, WHITE, win)
  68. tap_to_replay = Message(14440030"Tap to Replay",tap_to_play_font, WHITE, win)
  69. # Variables
  70. bar_width_list = [i for i in range (40,150,10)]
  71. bar_frequency = 1200
  72. bar_speed = 4
  73. touched = False
  74. pos = None
  75. home_page = True
  76. score_page = False
  77. bird_dead = False
  78. score = 0
  79. high_score = 0
  80. move_left = False
  81. move_right = True
  82. prev_x = 0
  83. p_count = 0
  84. running = True
  85. while running:
  86.     win.blit(bg, (0,0))
  87.     for event in pygame.event.get():
  88.         if event.type == pygame.QUIT:
  89.             running = False
  90.         if event.type == pygame.KEYDOWN:
  91.             if event.key == pygame.K_ESCAPE:
  92.                 running = False
  93.         if event.type == pygame.MOUSEBUTTONDOWN and (home_page or score_page):
  94.             home_page = False
  95.             score_page = False
  96.             win_particle_group.empty()
  97.             bg = random.choice(bg_list)
  98.             particles = []
  99.             last_bar = pygame.time.get_ticks() - bar_frequency
  100.             next_bar = 0
  101.             bar_speed = 4
  102.             bar_frequency = 1200
  103.             bird_dead = False
  104.             score = 0
  105.             p_count = 0
  106.             score_list = []
  107.             for _ in range(15):
  108.                 x = random.randint(30, WIDTH - 30)
  109.                 y = random.randint(60, HEIGHT - 60)
  110.                 max = random.randint(8,16)
  111.                 b = Block(x,y,max, win)
  112.                 block_group.add(b)
  113.         if event.type == pygame.MOUSEBUTTONDOWN and not home_page:
  114.             if p.rect.collidepoint(event.pos):
  115.                 touched = True
  116.                 x, y = event.pos
  117.                 offset_x = p.rect.x - x
  118.         if event.type == pygame.MOUSEBUTTONUP and not home_page:
  119.             touched = False
  120.         if event.type == pygame.MOUSEMOTION and not home_page:
  121.             if touched:
  122.                 x, y = event.pos
  123.                 if move_right and prev_x > x:
  124.                     move_right = False
  125.                     move_left = True
  126.                     move_fx.play()
  127.                 if move_left and  prev_x < x:
  128.                     move_right = True
  129.                     move_left = False
  130.                     move_fx.play()
  131.                 prev_x = x
  132.                 p.rect.x =  x + offset_x
  133.     if home_page:
  134.         bg = home_bg
  135.         particles = generate_particles(p, particles, WHITE, win)
  136.         dodgy.update()
  137.         walls.update()
  138.         tap_to_play.update()
  139.         p.update()
  140.     elif score_page:
  141.         bg = home_bg
  142.         particles = generate_particles(p, particles, WHITE, win)
  143.         tap_to_replay.update()
  144.         p.update()
  145.         score_msg.update()
  146.         score_point.update()
  147.         if p_count % 5 == 0:
  148.             win_particles()
  149.         p_count += 1
  150.         win_particle_group.update()
  151.     else:
  152.         next_bar = pygame.time.get_ticks()
  153.         if next_bar - last_bar >= bar_frequency and not bird_dead:
  154.             bwidth = random.choice(bar_width_list)
  155.             b1prime = Bar(0,0,bwidth+3,GRAY, win)
  156.             b1 = Bar(0,-3,bwidth,WHITE,win)
  157.             b2prime = Bar(bwidth+bar_gap+30, WIDTH - bwidth - bar_gap, GRAY, win)
  158.             b2 = Bar(bwidth+bar_gap, -3, WIDTH - bwidth - bar_gap, WHITE, win)
  159.             bar_group.add(b1prime)
  160.             bar_group.add(b1)
  161.             bar_group.add(b2prime)
  162.             bar_group.add(b2)
  163.             color = random.choice(["red""white"])
  164.             pos = random.choice([0,1])
  165.             if pos == 0:
  166.                 x = bwidth + 12
  167.             elif pos == 1:
  168.                 x = bwidth + bar_gap - 12
  169.             ball = Ball(x, 101, color, win)
  170.             ball_group.add(ball)
  171.             last_bar = next_bar
  172.         for ball in ball_group:
  173.             if ball.rect.colliderect(p):
  174.                 if ball.color == "white":
  175.                     ball.kill()
  176.                     coin_fx.play()
  177.                     score += 1
  178.                     if score > high_score:
  179.                         high_score += 1
  180.                     score_card.animate = True
  181.                 elif ball.color == "red":
  182.                     if not bird_dead:
  183.                         death_fx.play()
  184.                         destroy_bird()
  185.                     bird_dead = True
  186.                     bar_speed = 0
  187.         if pygame.sprite.spritecollide(p, bar_group, False):
  188.             if not bird_dead:
  189.                 death_fx.play()
  190.                 destroy_bird()
  191.             bird_dead = True
  192.             bar_speed = 0
  193.         block_group.update()
  194.         bar_group.update(bar_speed)
  195.         ball_group.update(bar_speed)
  196.         if bird_dead:
  197.                 destruct_group.update()
  198.         score_card.update(score)
  199.         if not bird_dead:
  200.             particles = generate_particles(p, particles, WHITE, win)
  201.             p.update()
  202.         if score and score % 10 == 0:
  203.             rem = score // 10
  204.             if rem not in score_list:
  205.                 score_list.append(rem)
  206.                 bar_speed += 1
  207.                 bar_frequency -= 200
  208.         if bird_dead and len(destruct_group) == 0:
  209.             score_page = True
  210.             font =  "Fonts/BubblegumSans-Regular.ttf"
  211.             if score < high_score:
  212.                 score_msg = Message(1446055"Score",font, WHITE, win)
  213.             else:
  214.                 score_msg = Message(1446055"New High",font, WHITE, win)
  215.             score_point = Message(14411045, f"{score}", font, WHITE, win)
  216.         if score_page:
  217.             block_group.empty()
  218.             bar_group.empty()
  219.             ball_group.empty()
  220.             p.reset()
  221.     clock.tick(FPS)
  222.     pygame.display.update()
  223. pygame.quit()
3、圆弧冲刺
86f717c40518946ebaf62710004defa1.png

源码分享:

  1. import random
  2. import pygame
  3. from objects import Player, Balls, Dot, Shadow, Particle, Message, BlinkingText, Button
  4. pygame.init()
  5. SCREEN = WIDTH, HEIGHT = 288512
  6. CENTER = WIDTH //2, HEIGHT // 2
  7. info = pygame.display.Info()
  8. width = info.current_w
  9. height = info.current_h
  10. if width >= height:
  11.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
  12. else:
  13.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)
  14. clock = pygame.time.Clock()
  15. FPS = 60
  16. # COLORS **********************************************************************
  17. RED = (255,0,0)
  18. GREEN = (0,177,64)
  19. BLUE = (30144,255)
  20. ORANGE = (252,76,2)
  21. YELLOW = (254,221,0)
  22. PURPLE = (155,38,182)
  23. AQUA = (0,103,127)
  24. WHITE = (255,255,255)
  25. BLACK = (0,0,0)
  26. color_list = [RED, GREEN, BLUE, ORANGE, YELLOW, PURPLE]
  27. color_index = 0
  28. color = color_list[color_index]
  29. # FONTS ***********************************************************************
  30. title_font = "Fonts/Aladin-Regular.ttf"
  31. tap_to_play_font = "Fonts/BubblegumSans-Regular.ttf"
  32. score_font = "Fonts/DalelandsUncialBold-82zA.ttf"
  33. game_over_font = "Fonts/ghostclan.ttf"
  34. # MESSAGES ********************************************************************
  35. arc = Message(WIDTH-9020080"Arc", title_font, WHITE, win)
  36. dash = Message(8030060"Dash", title_font, WHITE, win)
  37. tap_to_play = BlinkingText(WIDTH//2, HEIGHT-60, 20, "Tap To Play", tap_to_play_font, WHITE, win)
  38. game_msg = Message(8015040"GAME", game_over_font, BLACK, win)
  39. over_msg = Message(21015040"OVER!", game_over_font, WHITE, win)
  40. score_text = Message(9023020"SCORE", None, BLACK, win)
  41. best_text = Message(20023020"BEST", None, BLACK, win)
  42. score_msg = Message(WIDTH-605050"0", score_font, WHITE, win)
  43. final_score_msg = Message(9028040"0", tap_to_play_font, BLACK, win)
  44. high_score_msg = Message(20028040"0", tap_to_play_font, BLACK, win)
  45. # SOUNDS **********************************************************************
  46. score_fx = pygame.mixer.Sound('Sounds/point.mp3')
  47. death_fx = pygame.mixer.Sound('Sounds/dead.mp3')
  48. score_page_fx = pygame.mixer.Sound('Sounds/score_page.mp3')
  49. pygame.mixer.music.load('Sounds/hk.mp3')
  50. pygame.mixer.music.play(loops=-1)
  51. pygame.mixer.music.set_volume(0.5)
  52. # Button images
  53. home_img = pygame.image.load('Assets/homeBtn.png')
  54. replay_img = pygame.image.load('Assets/replay.png')
  55. sound_off_img = pygame.image.load("Assets/soundOffBtn.png")
  56. sound_on_img = pygame.image.load("Assets/soundOnBtn.png")
  57. # Buttons
  58. home_btn = Button(home_img, (2424), WIDTH // 4 - 18, 390)
  59. replay_btn = Button(replay_img, (36,36), WIDTH // 2  - 18, 382)
  60. sound_btn = Button(sound_on_img, (2424), WIDTH - WIDTH // 4 - 18, 390)
  61. # GAME VARIABLES **************************************************************
  62. MAX_RAD = 120
  63. rad_delta = 50
  64. # OBJECTS *********************************************************************
  65. ball_group = pygame.sprite.Group()
  66. dot_group = pygame.sprite.Group()
  67. shadow_group = pygame.sprite.Group()
  68. particle_group = pygame.sprite.Group()
  69. p = Player(win)
  70. ball_positions = [(CENTER[0]-105, CENTER[1]), (CENTER[0]+105, CENTER[1]),
  71.                     (CENTER[0]-45, CENTER[1]), (CENTER[0]+45, CENTER[1]),
  72.                     (CENTER[0], CENTER[1]-75), (CENTER[0], CENTER[1]+75)]
  73. for index, pos in enumerate(ball_positions):
  74.     if index in (0,1):
  75.         type_ = 1
  76.         inverter = 5
  77.     if index in (2,3):
  78.         type_ = 1
  79.         inverter = 3
  80.     if index in (4,5):
  81.         type_ = 2
  82.         inverter = 1
  83.     ball = Balls(pos, type_, inverter, win)
  84.     ball_group.add(ball)
  85. dot_list = [(CENTER[0], CENTER[1]-MAX_RAD+3), (CENTER[0]+MAX_RAD-3, CENTER[1]),
  86.             (CENTER[0], CENTER[1]+MAX_RAD-3), (CENTER[0]-MAX_RAD+3, CENTER[1])]
  87. dot_index = random.choice([1,2,3,4])
  88. dot_pos = dot_list[dot_index-1]
  89. dot = Dot(*dot_pos, win)
  90. dot_group.add(dot)
  91. shadow = Shadow(dot_index, win)
  92. shadow_group.add(shadow)
  93. # VARIABLES *******************************************************************
  94. clicked = False
  95. num_clicks = 0
  96. player_alive = True
  97. sound_on = True
  98. score = 0
  99. highscore = 0
  100. home_page = True
  101. game_page = False
  102. score_page = False
  103. running = True
  104. while running:
  105.     win.fill(color)
  106.     for event in pygame.event.get():
  107.         if event.type == pygame.QUIT:
  108.             running = False
  109.         if event.type == pygame.KEYDOWN:
  110.             if event.key == pygame.K_ESCAPE or \
  111.                 event.key == pygame.K_q:
  112.                 running = False
  113.         if event.type == pygame.MOUSEBUTTONDOWN and home_page:
  114.             home_page = False
  115.             game_page = True
  116.             score_page = False
  117.             rad_delta = 50
  118.             clicked = True
  119.             score = 0
  120.             num_clicks = 0
  121.             player_alive = True
  122.         if event.type == pygame.MOUSEBUTTONDOWN and game_page:
  123.             if not clicked:
  124.                 clicked = True
  125.                 for ball in ball_group:
  126.                     if num_clicks % ball.inverter == 0:
  127.                         ball.dtheta *= -1
  128.                 p.set_move(dot_index)
  129.                 num_clicks += 1
  130.                 if num_clicks % 5 == 0:
  131.                     color_index += 1
  132.                     if color_index > len(color_list) - 1:
  133.                         color_index = 0
  134.                     color = color_list[color_index]
  135.         if event.type == pygame.MOUSEBUTTONDOWN and game_page:
  136.             clicked = False
  137.     if home_page:
  138.         for radius in [306090120]:
  139.             pygame.draw.circle(win, (0,0,0), CENTER, radius, 8)
  140.             pygame.draw.circle(win, (255,255,255), CENTER, radius, 5)
  141.         pygame.draw.rect(win, color, [CENTER[0]-10, CENTER[1]-MAX_RAD, MAX_RAD+50, MAX_RAD])
  142.         pygame.draw.rect(win, color, [CENTER[0]-MAX_RAD, CENTER[1]-10, MAX_RAD, MAX_RAD+50])
  143.         arc.update()
  144.         dash.update()
  145.         tap_to_play.update()
  146.     if score_page:
  147.         game_msg.update()
  148.         over_msg.update()
  149.         score_text.update(shadow=False)
  150.         best_text.update(shadow=False)
  151.         final_score_msg.update(score, shadow=False)
  152.         high_score_msg.update(highscore, shadow=False)
  153.         if home_btn.draw(win):
  154.             home_page = True
  155.             score_page = False
  156.             game_page = False
  157.             score = 0
  158.             score_msg = Message(WIDTH-605050"0", score_font, WHITE, win)
  159.         if replay_btn.draw(win):
  160.             home_page = False
  161.             score_page = False
  162.             game_page = True
  163.             player_alive = True
  164.             score = 0
  165.             score_msg = Message(WIDTH-605050"0", score_font, WHITE, win)
  166.             p = Player(win)
  167.         if sound_btn.draw(win):
  168.             sound_on = not sound_on
  169.             if sound_on:
  170.                 sound_btn.update_image(sound_on_img)
  171.                 pygame.mixer.music.play(loops=-1)
  172.             else:
  173.                 sound_btn.update_image(sound_off_img)
  174.                 pygame.mixer.music.stop()
  175.     if game_page:
  176.         for radius in [30 + rad_delta, 60 + rad_delta, 90 + rad_delta, 120 + rad_delta]:
  177.             if rad_delta > 0:
  178.                 radius -= 1
  179.                 rad_delta -= 1
  180.             pygame.draw.circle(win, (0,0,0), CENTER, radius, 5)
  181.         pygame.draw.rect(win, color, [CENTER[0]-10, CENTER[1]-MAX_RAD, 20, MAX_RAD*2])
  182.         pygame.draw.rect(win, color, [CENTER[0]-MAX_RAD, CENTER[1]-10, MAX_RAD*220])
  183.         if rad_delta <= 0:
  184.             p.update(player_alive, color, shadow_group)
  185.             shadow_group.update()
  186.             ball_group.update()
  187.             dot_group.update()
  188.             particle_group.update()
  189.             score_msg.update(score)
  190.             for dot in dot_group:
  191.                 if dot.rect.colliderect(p):
  192.                     dot.kill()
  193.                     score_fx.play()
  194.                     score += 1
  195.                     if highscore <= score:
  196.                         highscore = score
  197.             if pygame.sprite.spritecollide(p, ball_group, False) and player_alive:
  198.                 death_fx.play()
  199.                 x, y = p.rect.center
  200.                 for i in range(20):
  201.                     particle = Particle(x, y, WHITE, win)
  202.                     particle_group.add(particle)
  203.                 player_alive = False
  204.                 p.reset()
  205.             if p.can_move and len(dot_group) == 0 and player_alive:
  206.                 dot_index = random.randint(1,4)
  207.                 dot_pos = dot_list[dot_index-1]
  208.                 dot = Dot(*dot_pos, win)
  209.                 dot_group.add(dot)
  210.                 shadow_group.empty()
  211.                 shadow = Shadow(dot_index, win)
  212.                 shadow_group.add(shadow)
  213.             if not player_alive and len(particle_group) == 0:
  214.                 game_page = False
  215.                 score_page = True
  216.                 dot_group.empty()
  217.                 shadow_group.empty()
  218.                 for ball in ball_group:
  219.                     ball.reset()
  220.                 score_page_fx.play()
  221.     pygame.draw.rect(win, WHITE, (00, WIDTH, HEIGHT), 5, border_radius=10)
  222.     clock.tick(FPS)
  223.     pygame.display.update()
  224. pygame.quit()
4、行星游戏

bf8f4cedab9e0b8358b3815b54f75343.png

源码分享:

  1. import random
  2. import pygame
  3. from pygame.locals import KEYDOWN, QUIT, K_ESCAPE, K_SPACE, K_q, K_e
  4. from objects import Rocket, Asteroid, Bullet, Explosion
  5. ### SETUP *********************************************************************
  6. SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 500500
  7. pygame.mixer.init()
  8. pygame.init()
  9. clock = pygame.time.Clock()
  10. win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
  11. pygame.display.set_caption('Asteroids')
  12. gunshot_sound = pygame.mixer.Sound("music/laser.wav")
  13. explosion_sound = pygame.mixer.Sound("music/explosion.mp3")
  14. font = pygame.font.Font('freesansbold.ttf'32)
  15. # text = font.render('', True, green, blue)
  16. ### Objects & Events **********************************************************
  17. ADDAST1 = pygame.USEREVENT + 1
  18. ADDAST2 = pygame.USEREVENT + 2
  19. ADDAST3 = pygame.USEREVENT + 3
  20. ADDAST4 = pygame.USEREVENT + 4
  21. ADDAST5 = pygame.USEREVENT + 5
  22. pygame.time.set_timer(ADDAST1, 2000)
  23. pygame.time.set_timer(ADDAST2, 6000)
  24. pygame.time.set_timer(ADDAST3, 10000)
  25. pygame.time.set_timer(ADDAST4, 15000)
  26. pygame.time.set_timer(ADDAST5, 20000)
  27. rocket = Rocket(SIZE)
  28. asteroids = pygame.sprite.Group()
  29. bullets = pygame.sprite.Group()
  30. explosions = pygame.sprite.Group()
  31. all_sprites = pygame.sprite.Group()
  32. all_sprites.add(rocket)
  33. backgrounds = [f'assets/background/bg{i}s.png' for i in range(1,5)]
  34. bg = pygame.image.load(random.choice(backgrounds))
  35. startbg = pygame.image.load('assets/start.jpg')
  36. ### Game **********************************************************************
  37. if __name__ == '__main__':
  38.     score = 0
  39.     running = True
  40.     gameStarted = False
  41.     musicStarted = False
  42.     while running:
  43.         if not gameStarted:
  44.             if not musicStarted:
  45.                 pygame.mixer.music.load('music/Apoxode_-_Electric_1.mp3')
  46.                 pygame.mixer.music.play(loops=-1)
  47.                 musicStarted = True
  48.             for event in pygame.event.get():
  49.                 if event.type == QUIT:
  50.                     running = False
  51.                 if event.type == KEYDOWN:
  52.                     if event.key == K_SPACE:
  53.                         gameStarted = True
  54.                         musicStarted = False
  55.                 win.blit(startbg, (0,0))        
  56.         else:
  57.             if not musicStarted:
  58.                 pygame.mixer.music.load('music/rpg_ambience_-_exploration.ogg')
  59.                 pygame.mixer.music.play(loops=-1)
  60.                 musicStarted = True
  61.             for event in pygame.event.get():
  62.                 if event.type == QUIT:
  63.                     running = False
  64.                 if event.type == KEYDOWN:
  65.                     if event.key == K_ESCAPE:
  66.                         running = False
  67.                     if event.key == K_SPACE:
  68.                         pos = rocket.rect[:2]
  69.                         bullet = Bullet(pos, rocket.dir, SIZE)
  70.                         bullets.add(bullet)
  71.                         all_sprites.add(bullet)
  72.                         gunshot_sound.play()
  73.                     if event.key == K_q:
  74.                         rocket.rotate_left()
  75.                     if event.key == K_e:
  76.                         rocket.rotate_right()
  77.                 elif event.type == ADDAST1:
  78.                     ast = Asteroid(1, SIZE)
  79.                     asteroids.add(ast)
  80.                     all_sprites.add(ast)
  81.                 elif event.type == ADDAST2:
  82.                     ast = Asteroid(2, SIZE)
  83.                     asteroids.add(ast)
  84.                     all_sprites.add(ast)
  85.                 elif event.type == ADDAST3:
  86.                     ast = Asteroid(3, SIZE)
  87.                     asteroids.add(ast)
  88.                     all_sprites.add(ast)
  89.                 elif event.type == ADDAST4:
  90.                     ast = Asteroid(4, SIZE)
  91.                     asteroids.add(ast)
  92.                     all_sprites.add(ast)
  93.                 elif event.type == ADDAST5:
  94.                     ast = Asteroid(5, SIZE)
  95.                     asteroids.add(ast)
  96.                     all_sprites.add(ast)
  97.             pressed_keys = pygame.key.get_pressed()
  98.             rocket.update(pressed_keys)
  99.             asteroids.update()
  100.             bullets.update()
  101.             explosions.update()
  102.             win.blit(bg, (0,0))
  103.             explosions.draw(win)
  104.             for sprite in all_sprites:
  105.                 win.blit(sprite.surf, sprite.rect)
  106.             win.blit(rocket.surf, rocket.rect)
  107.             if pygame.sprite.spritecollideany(rocket, asteroids):
  108.                 rocket.kill()
  109.                 score = 0
  110.                 for sprite in all_sprites:
  111.                     sprite.kill()
  112.                 all_sprites.empty()
  113.                 rocket = Rocket(SIZE)
  114.                 all_sprites.add(rocket)
  115.                 gameStarted = False
  116.                 musicStarted = False
  117.             for bullet in bullets:
  118.                 collision = pygame.sprite.spritecollide(bullet, asteroids, True)
  119.                 if collision:
  120.                     pos = bullet.rect[:2]
  121.                     explosion = Explosion(pos)
  122.                     explosions.add(explosion)
  123.                     score += 1
  124.                     explosion_sound.play()
  125.                     bullet.kill()
  126.                     bullets.remove(bullet)
  127.             text = font.render('Score : ' + str(score), 1, (200,255,0))
  128.             win.blit(text, (34010))
  129.         pygame.display.flip()
  130.         clock.tick(30)
  131.     pygame.quit()
5、弹跳的球

b64cce1c70ece4bcf927fd2d0f755ae5.png

源码分享:

  1. import os
  2. import pygame
  3. from player import Ball
  4. from world import World, load_level
  5. from texts import Text, Message
  6. from button import Button, LevelButton
  7. pygame.init()
  8. WIDTH, HEIGHT = 192212
  9. win = pygame.display.set_mode((WIDTH, HEIGHT), pygame.NOFRAME)
  10. pygame.display.set_caption('Bounce')
  11. clock = pygame.time.Clock()
  12. FPS = 30
  13. # GAME VARIABLES **************************************************************
  14. ROWS = 12
  15. MAX_COLS = 150
  16. TILE_SIZE = 16
  17. MAX_LEVEL = 8
  18. # COLORS **********************************************************************
  19. BLUE = (175207240)
  20. BLUE2 = (00255)
  21. WHITE = (255255255)
  22. # FONTS ***********************************************************************
  23. health_font = "Fonts/ARCADECLASSIC.TTF"
  24. level_text = Text(health_font, 24)
  25. health_text = Message(40, WIDTH + 1019"x3", health_font, WHITE, win)
  26. select_level_text = Message(WIDTH//2, 20, 24, "Select  Level", health_font, BLUE2, win)
  27. current_level_text = Message(WIDTH - 40, WIDTH + 1020"Level 1", health_font, WHITE, win)
  28. you_win = Message(WIDTH //2, HEIGHT//2, 40, "You  Win", health_font, BLUE2, win)
  29. # SOUNDS **********************************************************************
  30. click_fx = pygame.mixer.Sound('Sounds/click.mp3')
  31. life_fx = pygame.mixer.Sound('Sounds/gate.mp3')
  32. checkpoint_fx = pygame.mixer.Sound('Sounds/checkpoint.mp3')
  33. pygame.mixer.music.load('Sounds/track1.wav')
  34. pygame.mixer.music.play(loops=-1)
  35. pygame.mixer.music.set_volume(0.4)
  36. # LOADING IMAGES **************************************************************
  37. ball_image = pygame.image.load('Assets/ball.png')
  38. splash_img = pygame.transform.scale(pygame.image.load('Assets/splash_logo.png'),
  39.              (2*WIDTH, HEIGHT))
  40. bounce_img = pygame.image.load('Assets/menu_logo.png')
  41. game_lost_img = pygame.image.load('Assets/lose.png')
  42. game_lost_img = pygame.transform.scale(game_lost_img, (WIDTH//2, 80))
  43. level_locked_img = pygame.image.load('Assets/level_locked.png')
  44. level_locked_img = pygame.transform.scale(level_locked_img, (4040))
  45. level_unlocked_img = pygame.image.load('Assets/level_unlocked.png')
  46. level_unlocked_img = pygame.transform.scale(level_unlocked_img, (4040))
  47. play_img = pygame.image.load('Assets/play.png')
  48. restart_img = pygame.image.load('Assets/restart.png')
  49. menu_img = pygame.image.load('Assets/menu.png')
  50. sound_on_img = pygame.image.load('Assets/SoundOnBtn.png')
  51. sound_off_img = pygame.image.load('Assets/SoundOffBtn.png')
  52. game_won_img = pygame.image.load('Assets/game won.png')
  53. # BUTTONS *********************************************************************
  54. play_btn = Button(play_img, False, 45130)
  55. sound_btn = Button(sound_on_img, False, 45170)
  56. restart_btn = Button(restart_img, False, 45130)
  57. menu_btn = Button(menu_img, False, 45170)
  58. # LEVEL TEXT & BUTTONS ********************************************************
  59. level_btns = []
  60. for level in range(MAX_LEVEL):
  61.     text = level_text.render(f'{level+1}', (255255255))
  62.     r = level // 3
  63.     c = level % 3
  64.     btn = LevelButton(level_locked_img, (4040), 20 + c * 5550 + r * 55, text)
  65.     level_btns.append(btn)
  66. # GROUPS **********************************************************************
  67. spikes_group = pygame.sprite.Group()
  68. inflator_group = pygame.sprite.Group()
  69. deflator_group = pygame.sprite.Group()
  70. enemy_group = pygame.sprite.Group()
  71. exit_group = pygame.sprite.Group()
  72. checkpoint_group = pygame.sprite.Group()
  73. health_group = pygame.sprite.Group()
  74. objects_groups = [spikes_group, inflator_group, deflator_group, enemy_group, exit_group, 
  75.                     checkpoint_group, health_group]
  76. collision_groups = [inflator_group, deflator_group]
  77. # RESET ***********************************************************************
  78. def reset_level_data(level):
  79.     for group in objects_groups:
  80.         group.empty()
  81.     # LOAD LEVEL WORLD
  82.     world_data, level_length = load_level(level)
  83.     w = World(objects_groups)
  84.     w.generate_world(world_data, win)
  85.     return world_data, level_length, w
  86. def reset_player_data(level):
  87.     if level == 1:
  88.         x, y = 6450
  89.     if level == 2:
  90.         x, y = 6550
  91.     if level == 3:
  92.         x, y = 6450
  93.     if level == 4:
  94.         x, y = 6350
  95.     if level == 5:
  96.         x, y = 6450
  97.     if level == 6:
  98.         x, y = 4850
  99.     if level == 7:
  100.         x, y = 7880
  101.     if level == 8:
  102.         x, y = 112,100
  103.     p = Ball(x, y)
  104.     moving_left = False
  105.     moving_right = False
  106.     return p, moving_left, moving_right
  107. # VARIABLES *******************************************************************
  108. moving_left = False
  109. moving_right = False
  110. SCROLL_THRES = 80
  111. screen_scroll = 0
  112. level_scroll = 0
  113. level = 1
  114. next_level = False
  115. reset_level = False
  116. checkpoint = None
  117. health = 3
  118. splash_count = 0
  119. sound_on = True
  120. logo_page = True
  121. home_page = False
  122. level_page = False
  123. game_page = False
  124. restart_page = False
  125. win_page = False
  126. running = True
  127. while running:
  128.     win.fill(BLUE)
  129.     pygame.draw.rect(win, (255255,255), (00, WIDTH, HEIGHT), 1, border_radius=5)
  130.     for event in pygame.event.get():
  131.         if event.type == pygame.QUIT:
  132.             running = False
  133.         if event.type == pygame.KEYDOWN:
  134.             if event.key == pygame.K_ESCAPE or \
  135.                 event.key == pygame.K_q:
  136.                 running = False
  137.         if event.type == pygame.KEYDOWN:
  138.             if event.key == pygame.K_LEFT:
  139.                 moving_left = True
  140.             if event.key == pygame.K_RIGHT:
  141.                 moving_right = True
  142.             if event.key == pygame.K_UP:
  143.                 if not p.jump:
  144.                     p.jump = True
  145.         if event.type == pygame.KEYUP:
  146.             if event.key == pygame.K_LEFT:
  147.                 moving_left = False
  148.             if event.key == pygame.K_RIGHT:
  149.                 moving_right = False
  150.     if logo_page:
  151.         win.blit(splash_img, (-100,0))
  152.         splash_count += 1
  153.         if splash_count % 50 == 0:
  154.             logo_page = False
  155.             home_page = True
  156.     if home_page:
  157.         win.blit(bounce_img, (10,10))
  158.         if play_btn.draw(win):
  159.             click_fx.play()
  160.             home_page = False
  161.             level_page = True
  162.         if sound_btn.draw(win):
  163.             click_fx.play()
  164.             sound_on = not sound_on
  165.             if sound_on:
  166.                 sound_btn.update_image(sound_on_img)
  167.                 pygame.mixer.music.play(loops=-1)
  168.             else:
  169.                 sound_btn.update_image(sound_off_img)
  170.                 pygame.mixer.music.stop()
  171.     if level_page:
  172.         select_level_text.update(shadow=False)
  173.         for index, btn in enumerate(level_btns):
  174.             if index < level:
  175.                 if not btn.unlocked:
  176.                     btn.unlocked = True
  177.                     btn.update_image(level_unlocked_img)
  178.             if btn.draw(win):
  179.                 if index < level:
  180.                     click_fx.play()
  181.                     level_page = False
  182.                     game_page = True
  183.                     level = index + 1
  184.                     screen_scroll = 0
  185.                     level_scroll = 0
  186.                     health = 3
  187.                     world_data, level_length, w = reset_level_data(level)
  188.                     p, moving_left, moving_right = reset_player_data(level)
  189.     if restart_page:
  190.         win.blit(game_lost_img, (45,20))
  191.         if restart_btn.draw(win):
  192.             click_fx.play()
  193.             world_data, level_length, w = reset_level_data(level)
  194.             p, moving_left, moving_right = reset_player_data(level)
  195.             level_scroll = 0
  196.             screen_scroll = 0
  197.             health = 3
  198.             checkpoint = None
  199.             restart_page = False
  200.             game_page = True
  201.         if menu_btn.draw(win):
  202.             click_fx.play()
  203.             home_page = True
  204.             restart_page = False
  205.     if win_page:
  206.         win.blit(game_won_img, (4520))
  207.         you_win.update()
  208.         if menu_btn.draw(win):
  209.             click_fx.play()
  210.             home_page = True
  211.             win_page = False
  212.             restart_page = False
  213.     if game_page:
  214.         w.update(screen_scroll)
  215.         w.draw(win)
  216.         spikes_group.update(screen_scroll)
  217.         spikes_group.draw(win)
  218.         health_group.update(screen_scroll)
  219.         health_group.draw(win)
  220.         inflator_group.update(screen_scroll)
  221.         inflator_group.draw(win)
  222.         deflator_group.update(screen_scroll)
  223.         deflator_group.draw(win)
  224.         exit_group.update(screen_scroll)
  225.         exit_group.draw(win)
  226.         checkpoint_group.update(screen_scroll)
  227.         checkpoint_group.draw(win)
  228.         enemy_group.update(screen_scroll)
  229.         enemy_group.draw(win)
  230.         screen_scroll = 0
  231.         p.update(moving_left, moving_right, w, collision_groups)
  232.         p.draw(win)
  233.         if ((p.rect.right >= WIDTH - SCROLL_THRES) and level_scroll < (level_length * 16) - WIDTH) \
  234.                 or ((p.rect.left <= SCROLL_THRES) and level_scroll > 0):
  235.                 dx = p.dx
  236.                 p.rect.x -= dx
  237.                 screen_scroll = -dx
  238.                 level_scroll += dx
  239.         if len(exit_group) > 0:
  240.             exit = exit_group.sprites()[0]
  241.             if not exit.open:
  242.                 if abs(p.rect.x - exit.rect.x) <= 80 and len(health_group) == 0:
  243.                     exit.open = True
  244.             if p.rect.colliderect(exit.rect) and exit.index == 11:
  245.                 checkpoint = None
  246.                 checkpoint_fx.play()
  247.                 level += 1
  248.                 if level < MAX_LEVEL:
  249.                     checkpoint = False
  250.                     reset_level = True
  251.                     next_level = True
  252.                 else:
  253.                     checkpoint = None
  254.                     win_page = True
  255.         cp = pygame.sprite.spritecollide(p, checkpoint_group, False)
  256.         if cp:
  257.             checkpoint = cp[0]
  258.             if not checkpoint.catched:
  259.                 checkpoint_fx.play()
  260.                 checkpoint.catched = True
  261.                 checkpoint_pos = p.rect.center
  262.                 checkpoint_screen_scroll = screen_scroll
  263.                 checkpoint_level_scroll = level_scroll
  264.         if pygame.sprite.spritecollide(p, spikes_group, False):
  265.             reset_level = True
  266.         if pygame.sprite.spritecollide(p, health_group, True):
  267.             health += 1
  268.             life_fx.play()
  269.         if pygame.sprite.spritecollide(p, enemy_group, False):
  270.             reset_level = True
  271.         if reset_level:
  272.             if health > 0:
  273.                 if next_level:
  274.                     world_data, level_length, w = reset_level_data(level)
  275.                     p, moving_left, moving_right = reset_player_data(level)
  276.                     level_scroll = 0
  277.                     health = 3
  278.                     checkpoint = None
  279.                     next_level = False
  280.                 elif checkpoint:
  281.                     checkpoint_dx = level_scroll - checkpoint_level_scroll
  282.                     w.update(checkpoint_dx)
  283.                     for group in objects_groups:
  284.                         group.update(checkpoint_dx)
  285.                     p.rect.center = checkpoint_pos
  286.                     level_scroll = checkpoint_level_scroll
  287.                 else:
  288.                     w.update(level_scroll)
  289.                     for group in objects_groups:
  290.                         group.update(level_scroll)
  291.                     p, moving_left, moving_right = reset_player_data(level)
  292.                     level_scroll = 0
  293.                 screen_scroll = 0
  294.                 reset_level = False
  295.                 health -= 1
  296.             else:
  297.                 restart_page = True
  298.                 game_page = False
  299.                 reset_level = False
  300.         # Drawing info bar
  301.         pygame.draw.rect(win, (252525), (0, HEIGHT-20, WIDTH, 20))
  302.         pygame.draw.rect(win, (255255,255), (00, WIDTH, WIDTH), 2, border_radius=5)
  303.         win.blit(ball_image, (5, WIDTH + 2))
  304.         health_text.update(f'x{health}', shadow=False)
  305.         current_level_text.update(f'Level {level}', shadow=False)
  306.     clock.tick(FPS)
  307.     pygame.display.update()
  308. pygame.quit()
6、汽车避障

80e18062fd663585128e3071b72ebfb4.png

源码分享:

  1. import pygame
  2. import random
  3. from objects import Road, Player, Nitro, Tree, Button, \
  4.                     Obstacle, Coins, Fuel
  5. pygame.init()
  6. SCREEN = WIDTH, HEIGHT = 288512
  7. info = pygame.display.Info()
  8. width = info.current_w
  9. height = info.current_h
  10. if width >= height:
  11.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
  12. else:
  13.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)
  14. clock = pygame.time.Clock()
  15. FPS = 30
  16. lane_pos = [5095142190]
  17. # COLORS **********************************************************************
  18. WHITE = (255255255)
  19. BLUE = (30144,255)
  20. RED = (25500)
  21. GREEN = (02550)
  22. BLACK = (0020)
  23. # FONTS ***********************************************************************
  24. font = pygame.font.SysFont('cursive'32)
  25. select_car = font.render('Select Car', True, WHITE)
  26. # IMAGES **********************************************************************
  27. bg = pygame.image.load('Assets/bg.png')
  28. home_img = pygame.image.load('Assets/home.png')
  29. play_img = pygame.image.load('Assets/buttons/play.png')
  30. end_img = pygame.image.load('Assets/end.jpg')
  31. end_img = pygame.transform.scale(end_img, (WIDTH, HEIGHT))
  32. game_over_img = pygame.image.load('Assets/game_over.png')
  33. game_over_img = pygame.transform.scale(game_over_img, (220220))
  34. coin_img = pygame.image.load('Assets/coins/1.png')
  35. dodge_img = pygame.image.load('Assets/car_dodge.png')
  36. left_arrow = pygame.image.load('Assets/buttons/arrow.png')
  37. right_arrow = pygame.transform.flip(left_arrow, True, False)
  38. home_btn_img = pygame.image.load('Assets/buttons/home.png')
  39. replay_img = pygame.image.load('Assets/buttons/replay.png')
  40. sound_off_img = pygame.image.load("Assets/buttons/soundOff.png")
  41. sound_on_img = pygame.image.load("Assets/buttons/soundOn.png")
  42. cars = []
  43. car_type = 0
  44. for i in range(19):
  45.     img = pygame.image.load(f'Assets/cars/{i}.png')
  46.     img = pygame.transform.scale(img, (59101))
  47.     cars.append(img)
  48. nitro_frames = []
  49. nitro_counter = 0
  50. for i in range(6):
  51.     img = pygame.image.load(f'Assets/nitro/{i}.gif')
  52.     img = pygame.transform.flip(img, False, True)
  53.     img = pygame.transform.scale(img, (1836))
  54.     nitro_frames.append(img)
  55. # FUNCTIONS *******************************************************************
  56. def center(image):
  57.     return (WIDTH // 2) - image.get_width() // 2
  58. # BUTTONS *********************************************************************
  59. play_btn = Button(play_img, (10034), center(play_img)+10, HEIGHT-80)
  60. la_btn = Button(left_arrow, (3242), 40180)
  61. ra_btn = Button(right_arrow, (3242), WIDTH-60180)
  62. home_btn = Button(home_btn_img, (2424), WIDTH // 4 - 18, HEIGHT - 80)
  63. replay_btn = Button(replay_img, (36,36), WIDTH // 2  - 18, HEIGHT - 86)
  64. sound_btn = Button(sound_on_img, (2424), WIDTH - WIDTH // 4 - 18, HEIGHT - 80)
  65. # SOUNDS **********************************************************************
  66. click_fx = pygame.mixer.Sound('Sounds/click.mp3')
  67. fuel_fx = pygame.mixer.Sound('Sounds/fuel.wav')
  68. start_fx = pygame.mixer.Sound('Sounds/start.mp3')
  69. restart_fx = pygame.mixer.Sound('Sounds/restart.mp3')
  70. coin_fx = pygame.mixer.Sound('Sounds/coin.mp3')
  71. pygame.mixer.music.load('Sounds/mixkit-tech-house-vibes-130.mp3')
  72. pygame.mixer.music.play(loops=-1)
  73. pygame.mixer.music.set_volume(0.6)
  74. # OBJECTS *********************************************************************
  75. road = Road()
  76. nitro = Nitro(WIDTH-80, HEIGHT-80)
  77. p = Player(100, HEIGHT-120, car_type)
  78. tree_group = pygame.sprite.Group()
  79. coin_group = pygame.sprite.Group()
  80. fuel_group = pygame.sprite.Group()
  81. obstacle_group = pygame.sprite.Group()
  82. # VARIABLES *******************************************************************
  83. home_page = True
  84. car_page = False
  85. game_page = False
  86. over_page = False
  87. move_left = False
  88. move_right = False
  89. nitro_on = False
  90. sound_on = True
  91. counter = 0
  92. counter_inc = 1
  93. # speed = 3
  94. speed = 10
  95. dodged = 0
  96. coins = 0
  97. cfuel = 100
  98. endx, enddx = 00.5
  99. gameovery = -50
  100. running = True
  101. while running:
  102.     win.fill(BLACK)
  103.     for event in pygame.event.get():
  104.         if event.type == pygame.QUIT:
  105.             running = False
  106.         if event.type == pygame.KEYDOWN:
  107.             if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
  108.                 running = False
  109.             if event.key == pygame.K_LEFT:
  110.                 move_left = True
  111.             if event.key == pygame.K_RIGHT:
  112.                 move_right = True
  113.             if event.key == pygame.K_n:
  114.                 nitro_on = True
  115.         if event.type == pygame.KEYUP:
  116.             if event.key == pygame.K_LEFT:
  117.                 move_left = False
  118.             if event.key == pygame.K_RIGHT:
  119.                 move_right = False
  120.             if event.key == pygame.K_n:
  121.                 nitro_on = False
  122.                 speed = 3
  123.                 counter_inc = 1
  124.         if event.type == pygame.MOUSEBUTTONDOWN:
  125.             x, y = event.pos
  126.             if nitro.rect.collidepoint((x, y)):
  127.                 nitro_on = True
  128.             else:
  129.                 if x <= WIDTH // 2:
  130.                     move_left = True
  131.                 else:
  132.                     move_right = True
  133.         if event.type == pygame.MOUSEBUTTONUP:
  134.             move_left = False
  135.             move_right = False
  136.             nitro_on = False
  137.             speed = 3
  138.             counter_inc = 1
  139.     if home_page:
  140.         win.blit(home_img, (0,0))
  141.         counter += 1
  142.         if counter % 60 == 0:
  143.             home_page = False
  144.             car_page = True
  145.     if car_page:
  146.         win.blit(select_car, (center(select_car), 80))
  147.         win.blit(cars[car_type], (WIDTH//2-30, 150))
  148.         if la_btn.draw(win):
  149.             car_type -= 1
  150.             click_fx.play()
  151.             if car_type < 0:
  152.                 car_type = len(cars) - 1
  153.         if ra_btn.draw(win):
  154.             car_type += 1
  155.             click_fx.play()
  156.             if car_type >= len(cars):
  157.                 car_type = 0
  158.         if play_btn.draw(win):
  159.             car_page = False
  160.             game_page = True
  161.             start_fx.play()
  162.             p = Player(100, HEIGHT-120, car_type)
  163.             counter = 0
  164.     if over_page:
  165.         win.blit(end_img, (endx, 0))
  166.         endx += enddx
  167.         if endx >= 10 or endx<=-10:
  168.             enddx *= -1
  169.         win.blit(game_over_img, (center(game_over_img), gameovery))
  170.         if gameovery < 16:
  171.             gameovery += 1
  172.         num_coin_img = font.render(f'{coins}', True, WHITE)
  173.         num_dodge_img = font.render(f'{dodged}', True, WHITE)
  174.         distance_img = font.render(f'Distance : {counter/1000:.2f} km', True, WHITE)
  175.         win.blit(coin_img, (80240))
  176.         win.blit(dodge_img, (50280))
  177.         win.blit(num_coin_img, (180250))
  178.         win.blit(num_dodge_img, (180300))
  179.         win.blit(distance_img, (center(distance_img), (350)))
  180.         if home_btn.draw(win):
  181.             over_page = False
  182.             home_page = True
  183.             coins = 0
  184.             dodged = 0
  185.             counter = 0
  186.             nitro.gas = 0
  187.             cfuel = 100
  188.             endx, enddx = 00.5
  189.             gameovery = -50
  190.         if replay_btn.draw(win):
  191.             over_page = False
  192.             game_page = True
  193.             coins = 0
  194.             dodged = 0
  195.             counter = 0
  196.             nitro.gas = 0
  197.             cfuel = 100
  198.             endx, enddx = 00.5
  199.             gameovery = -50
  200.             restart_fx.play()
  201.         if sound_btn.draw(win):
  202.             sound_on = not sound_on
  203.             if sound_on:
  204.                 sound_btn.update_image(sound_on_img)
  205.                 pygame.mixer.music.play(loops=-1)
  206.             else:
  207.                 sound_btn.update_image(sound_off_img)
  208.                 pygame.mixer.music.stop()
  209.     if game_page:
  210.         win.blit(bg, (0,0))
  211.         road.update(speed)
  212.         road.draw(win)
  213.         counter += counter_inc
  214.         if counter % 60 == 0:
  215.             tree = Tree(random.choice([-5, WIDTH-35]), -20)
  216.             tree_group.add(tree)
  217.         if counter % 270 == 0:
  218.             type = random.choices([12], weights=[64], k=1)[0]
  219.             x = random.choice(lane_pos)+10
  220.             if type == 1:
  221.                 count = random.randint(13)
  222.                 for i in range(count):
  223.                     coin = Coins(x,-100 - (25 * i))
  224.                     coin_group.add(coin)
  225.             elif type == 2:
  226.                 fuel = Fuel(x, -100)
  227.                 fuel_group.add(fuel)
  228.         elif counter % 90 == 0:
  229.             obs = random.choices([123], weights=[6,2,2], k=1)[0]
  230.             obstacle = Obstacle(obs)
  231.             obstacle_group.add(obstacle)
  232.         if nitro_on and nitro.gas > 0:
  233.             x, y = p.rect.centerx - 8, p.rect.bottom - 10
  234.             win.blit(nitro_frames[nitro_counter], (x, y))
  235.             nitro_counter = (nitro_counter + 1) % len(nitro_frames)
  236.             speed = 10
  237.             if counter_inc == 1:
  238.                 counter = 0
  239.                 counter_inc = 5
  240.         if nitro.gas <= 0:
  241.             speed = 3
  242.             counter_inc = 1
  243.         nitro.update(nitro_on)
  244.         nitro.draw(win)
  245.         obstacle_group.update(speed)
  246.         obstacle_group.draw(win)
  247.         tree_group.update(speed)
  248.         tree_group.draw(win)
  249.         coin_group.update(speed)
  250.         coin_group.draw(win)
  251.         fuel_group.update(speed)
  252.         fuel_group.draw(win)
  253.         p.update(move_left, move_right)
  254.         p.draw(win)
  255.         if cfuel > 0:
  256.             pygame.draw.rect(win, GREEN, (2020, cfuel, 15), border_radius=5)
  257.         pygame.draw.rect(win, WHITE, (202010015), 2, border_radius=5)
  258.         cfuel -= 0.05
  259.         # COLLISION DETECTION & KILLS
  260.         for obstacle in obstacle_group:
  261.             if obstacle.rect.y >= HEIGHT:
  262.                 if obstacle.type == 1:
  263.                     dodged += 1
  264.                 obstacle.kill() 
  265.             if pygame.sprite.collide_mask(p, obstacle):
  266.                 pygame.draw.rect(win, RED, p.rect, 1)
  267.                 speed = 0
  268.                 game_page = False
  269.                 over_page = True
  270.                 tree_group.empty()
  271.                 coin_group.empty()
  272.                 fuel_group.empty()
  273.                 obstacle_group.empty()
  274.         if pygame.sprite.spritecollide(p, coin_group, True):
  275.             coins += 1
  276.             coin_fx.play()
  277.         if pygame.sprite.spritecollide(p, fuel_group, True):
  278.             cfuel += 25
  279.             fuel_fx.play()
  280.             if cfuel >= 100:
  281.                 cfuel = 100
  282.     pygame.draw.rect(win, BLUE, (00, WIDTH, HEIGHT), 3)
  283.     clock.tick(FPS)
  284.     pygame.display.update()
  285. pygame.quit()
  286. # 今天给大家介绍一款Python制作的汽车避障小游戏
  287. # 主要通过Pygame实现的,运行代码,选择车型,进入游戏
  288. # 可以控制左右移动,点击右下角可以进行加速
  289. # 金币可以增加积分,撞到障碍物则游戏介绍
7、洞窟物语

d06e091f98705592b39171cb91854292.jpeg

源码分享:

  1. import pygame
  2. import pickle
  3. from objects import World, load_level, Button, Player, Portal, game_data
  4. pygame.init()
  5. SCREEN = WIDTH, HEIGHT = 288512
  6. win = pygame.display.set_mode(SCREEN, pygame.SCALED | pygame.FULLSCREEN)
  7. clock = pygame.time.Clock()
  8. FPS = 45
  9. tile_size = 16
  10. # Images
  11. bg = pygame.image.load("Assets/bg.png")
  12. cave_story = pygame.transform.rotate(pygame.image.load("Assets/cave_story.png"), 90)
  13. cave_story = pygame.transform.scale(cave_story, (150,300))
  14. game_won_img = pygame.transform.rotate(pygame.image.load("Assets/win.png"), -90)
  15. game_won_img = pygame.transform.scale(game_won_img, (150,300))
  16. # Sounds
  17. pygame.mixer.music.load('Sounds/goodbyte_sad-rpg-town.mp3')
  18. pygame.mixer.music.play(loops=-1)
  19. replay_fx =  pygame.mixer.Sound('Sounds/replay.wav')
  20. # Buttons
  21. move_btn = pygame.image.load("Assets/movement.jpeg")
  22. move_btn = pygame.transform.rotate(move_btn, -90)
  23. move_btn = pygame.transform.scale(move_btn, (42, HEIGHT))
  24. play_img = pygame.transform.rotate(pygame.image.load("Assets/play.png"), -90)
  25. play_btn = Button(play_img, (60150), 30170)
  26. quit_img = pygame.transform.rotate(pygame.image.load("Assets/quit.png"), -90)
  27. quit_btn = Button(quit_img, (60150), 140170)
  28. replay_img = pygame.transform.rotate(pygame.image.load("Assets/replay.png"), -90)
  29. replay_btn = Button(replay_img, (4040), 100190)
  30. sound_off_img = pygame.transform.rotate(pygame.image.load("Assets/sound_off.png"), -90)
  31. sound_on_img = pygame.transform.rotate(pygame.image.load("Assets/sound_on.png"), -90)
  32. sound_btn = Button(sound_on_img, (4040), 100260)
  33. # Variables
  34. current_level = 1
  35. MAX_LEVEL = 3
  36. show_keys = True
  37. pressed_keys = [False, False, False, False]
  38. dir_dict = {
  39.     'Up' : pygame.Rect(5273550),
  40.     'Down' : pygame.Rect(51603550),
  41.     'Left' :  pygame.Rect(53203550),
  42.     'Right' : pygame.Rect(54503550)
  43. }
  44. # groups 
  45. diamond_group = pygame.sprite.Group()
  46. spike_group = pygame.sprite.Group()
  47. plant_group = pygame.sprite.Group()
  48. board_group = pygame.sprite.Group()
  49. chain_group = pygame.sprite.Group()
  50. groups = [diamond_group, spike_group, plant_group, board_group, chain_group]
  51. data = load_level(current_level)
  52. (player_x, player_y), (portal_x, portal_y) = game_data(current_level)
  53. world = World(win, data, groups)
  54. player = Player(win, (player_x,player_y), world, groups)
  55. portal = Portal(portal_x, portal_y, win)
  56. game_started = False
  57. game_over = False
  58. game_won = False
  59. replay_menu = False
  60. sound_on = True
  61. bgx = 0
  62. bgcounter = 0
  63. bgdx = 1
  64. running = True
  65. while running:
  66.     win.blit(bg, (bgx, 0))
  67.     for group in groups:
  68.         group.draw(win)
  69.     world.draw()
  70.     if not game_started:
  71.         win.blit(cave_story, (100,100))
  72.         if play_btn.draw(win):
  73.             game_started = True
  74.     elif game_won:
  75.         win.blit(game_won_img, (100,100))
  76.     else:
  77.         if show_keys:
  78.             win.blit(move_btn, (0,0))
  79.             bgcounter += 1
  80.             if bgcounter >= 15:
  81.                 bgcounter = 0
  82.                 bgx += bgdx
  83.                 if bgx < 0 or bgx >5 :
  84.                     bgdx *= -1
  85.     #   for rect in dir_dict:
  86.     #       pygame.draw.rect(win, (25500), dir_dict[rect])
  87.         for event in pygame.event.get():
  88.             if event.type == pygame.QUIT:
  89.                 running = False
  90.             if event.type == pygame.MOUSEBUTTONDOWN:
  91.                 pos = event.pos
  92.                 if show_keys:
  93.                     if dir_dict["Up"].collidepoint(pos):
  94.                         pressed_keys[0] = True
  95.                     if dir_dict["Down"].collidepoint(pos):
  96.                         pressed_keys[1] = True
  97.                     if dir_dict["Left"].collidepoint(pos):
  98.                         pressed_keys[2] = True
  99.                     if dir_dict["Right"].collidepoint(pos):
  100.                         pressed_keys[3] = True
  101.             if event.type == pygame.MOUSEBUTTONUP:
  102.                 pressed_keys = [False, False, False, False]
  103.         portal.update()
  104.         if not game_over:
  105.             game_over = player.update(pressed_keys, game_over)
  106.             if game_over:
  107.                 show_keys = False
  108.                 replay_menu = True
  109.         if player.rect.colliderect(portal) and player.rect.top > portal.rect.top and player.rect.bottom < portal.rect.bottom:
  110.             if current_level < MAX_LEVEL:
  111.                 current_level += 1
  112.                 for group in groups:
  113.                     group.empty()
  114.                 data = load_level(current_level)
  115.                 (player_x, player_y), (portal_x, portal_y) = game_data(current_level)
  116.                 world = World(win, data, groups)
  117.                 player = Player(win, (player_x,player_y), world, groups)
  118.                 portal = Portal(portal_x, portal_y, win)
  119.             else:
  120.                 show_keys = False
  121.                 game_won = True
  122.         if replay_menu:
  123.             if quit_btn.draw(win):
  124.                 running = False
  125.             if sound_btn.draw(win):
  126.                 sound_on = not sound_on
  127.                 if sound_on:
  128.                     sound_btn.update_image(sound_on_img)
  129.                     pygame.mixer.music.play(loops=-1)
  130.                 else:
  131.                     sound_btn.update_image(sound_off_img)
  132.                     pygame.mixer.music.stop()
  133.             if replay_btn.draw(win):
  134.                 show_keys = True
  135.                 replay_menu = False
  136.                 game_over = False
  137.                 replay_fx.play()
  138.                 for group in groups:
  139.                     group.empty()
  140.                 data = load_level(current_level)
  141.                 (player_x, player_y), (portal_x, portal_y) = game_data(current_level)
  142.                 world = World(win, data, groups)
  143.                 player = Player(win, (player_x,player_y), world, groups)
  144.                 portal = Portal(portal_x, portal_y, win)
  145.     clock.tick(FPS)
  146.     pygame.display.update()
  147. pygame.quit()
8、联系

7ec4e247ac6a38b936ccaed2fde70ca3.png

源码分享:

  1. # Connected
  2. # Author : Prajjwal Pathak (pyguru)
  3. # Date : Thursday, 8 August, 2021
  4. import random
  5. import pygame
  6. from objects import Balls, Coins, Tiles, Particle, Message, Button
  7. pygame.init()
  8. SCREEN = WIDTH, HEIGHT = 288512
  9. CENTER = WIDTH //2, HEIGHT // 2
  10. info = pygame.display.Info()
  11. width = info.current_w
  12. height = info.current_h
  13. if width >= height:
  14.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
  15. else:
  16.     win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)
  17. pygame.display.set_caption('Connected')
  18. clock = pygame.time.Clock()
  19. FPS = 90
  20. # COLORS **********************************************************************
  21. RED = (255,0,0)
  22. GREEN = (0,177,64)
  23. BLUE = (30144,255)
  24. ORANGE = (252,76,2)
  25. YELLOW = (254,221,0)
  26. PURPLE = (155,38,182)
  27. AQUA = (0,103,127)
  28. WHITE = (255,255,255)
  29. BLACK = (0,0,0)
  30. GRAY = (252525)
  31. color_list = [PURPLE, GREEN, BLUE, ORANGE, YELLOW, RED]
  32. color_index = 0
  33. color = color_list[color_index]
  34. # SOUNDS **********************************************************************
  35. flip_fx = pygame.mixer.Sound('Sounds/flip.mp3')
  36. score_fx = pygame.mixer.Sound('Sounds/point.mp3')
  37. dead_fx = pygame.mixer.Sound('Sounds/dead.mp3')
  38. score_page_fx = pygame.mixer.Sound('Sounds/score_page.mp3')
  39. pygame.mixer.music.load('Sounds/bgm.mp3')
  40. pygame.mixer.music.play(loops=-1)
  41. pygame.mixer.music.set_volume(0.5)
  42. # FONTS ***********************************************************************
  43. title_font = "Fonts/Aladin-Regular.ttf"
  44. score_font = "Fonts/DroneflyRegular-K78LA.ttf"
  45. game_over_font = "Fonts/ghostclan.ttf"
  46. final_score_font = "Fonts/DalelandsUncialBold-82zA.ttf"
  47. new_high_font = "Fonts/BubblegumSans-Regular.ttf"
  48. connected = Message(WIDTH//2, 120, 55, "ConnecteD", title_font, WHITE, win)
  49. score_msg = Message(WIDTH//2, 100, 60, "0", score_font, (150, 150, 150), win)
  50. game_msg = Message(8015040"GAME", game_over_font, BLACK, win)
  51. over_msg = Message(21015040"OVER!", game_over_font, WHITE, win)
  52. final_score = Message(WIDTH//2, HEIGHT//2, 90, "0", final_score_font, RED, win)
  53. new_high_msg = Message(WIDTH//2, HEIGHT//2+60, 20, "New High", None, GREEN, win)
  54. # Button images
  55. home_img = pygame.image.load('Assets/homeBtn.png')
  56. replay_img = pygame.image.load('Assets/replay.png')
  57. sound_off_img = pygame.image.load("Assets/soundOffBtn.png")
  58. sound_on_img = pygame.image.load("Assets/soundOnBtn.png")
  59. easy_img = pygame.image.load("Assets/easy.jpg")
  60. hard_img = pygame.image.load("Assets/hard.jpg")
  61. # Buttons
  62. easy_btn = Button(easy_img, (7024), WIDTH//4-10, HEIGHT-100)
  63. hard_btn = Button(hard_img, (7024), WIDTH//2 + 10, HEIGHT-100)
  64. home_btn = Button(home_img, (2424), WIDTH // 4 - 18, HEIGHT//2 + 120)
  65. replay_btn = Button(replay_img, (36,36), WIDTH // 2  - 18, HEIGHT//2 + 115)
  66. sound_btn = Button(sound_on_img, (2424), WIDTH - WIDTH // 4 - 18, HEIGHT//2 + 120)
  67. # Groups **********************************************************************
  68. RADIUS = 70
  69. ball_group = pygame.sprite.Group()
  70. coin_group = pygame.sprite.Group()
  71. tile_group = pygame.sprite.Group()
  72. particle_group = pygame.sprite.Group()
  73. ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
  74. ball_group.add(ball)
  75. ball = Balls((CENTER[0], CENTER[1]-RADIUS), RADIUS, 270, win)
  76. ball_group.add(ball)
  77. # TIME ************************************************************************
  78. start_time = pygame.time.get_ticks()
  79. current_time = 0
  80. coin_delta = 850
  81. tile_delta = 2000
  82. # VARIABLES *******************************************************************
  83. clicked = False
  84. new_coin = True
  85. num_clicks = 0
  86. score = 0
  87. player_alive = True
  88. score = 0
  89. highscore = 0
  90. sound_on = True
  91. easy_level = True
  92. home_page = True
  93. game_page = False
  94. score_page = False
  95. running = True
  96. while running:
  97.     win.fill(GRAY)
  98.     for event in pygame.event.get():
  99.         if event.type == pygame.QUIT:
  100.             running = False
  101.         if event.type == pygame.KEYDOWN:
  102.             if event.key == pygame.K_ESCAPE or \
  103.                 event.key == pygame.K_q:
  104.                 running = False
  105.         if event.type == pygame.MOUSEBUTTONDOWN and game_page:
  106.             if not clicked:
  107.                 clicked = True
  108.                 for ball in ball_group:
  109.                     ball.dtheta *= -1
  110.                     flip_fx.play()
  111.                 num_clicks += 1
  112.                 if num_clicks % 5 == 0:
  113.                     color_index += 1
  114.                     if color_index > len(color_list) - 1:
  115.                         color_index = 0
  116.                     color = color_list[color_index]
  117.         if event.type == pygame.MOUSEBUTTONDOWN and game_page:
  118.             clicked = False
  119.     if home_page:
  120.         connected.update()
  121.         pygame.draw.circle(win, BLACK, CENTER, 8020)
  122.         ball_group.update(color)
  123.         if easy_btn.draw(win):
  124.             ball_group.empty()
  125.             ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
  126.             ball_group.add(ball)
  127.             home_page = False
  128.             game_page = True
  129.             easy_level = True
  130.         if hard_btn.draw(win):
  131.             ball_group.empty()
  132.             ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
  133.             ball_group.add(ball)
  134.             ball = Balls((CENTER[0], CENTER[1]-RADIUS), RADIUS, 270, win)
  135.             ball_group.add(ball)
  136.             home_page = False
  137.             game_page = True
  138.             easy_level = False
  139.     if score_page:
  140.         game_msg.update()
  141.         over_msg.update()
  142.         if score:
  143.             final_score.update(score, color)
  144.         else:
  145.             final_score.update("0", color)
  146.         if score and (score >= highscore):
  147.             new_high_msg.update(shadow=False)
  148.         if home_btn.draw(win):
  149.             home_page = True
  150.             score_page = False
  151.             game_page = False
  152.             player_alive = True
  153.             score = 0
  154.             score_msg = Message(WIDTH//2, 100, 60, "0", score_font, (150, 150, 150), win)
  155.         if replay_btn.draw(win):
  156.             home_page = False
  157.             score_page = False
  158.             game_page = True
  159.             score = 0
  160.             score_msg = Message(WIDTH//2, 100, 60, "0", score_font, (150, 150, 150), win)
  161.             if easy_level:
  162.                 ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
  163.                 ball_group.add(ball)
  164.             else:
  165.                 ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
  166.                 ball_group.add(ball)
  167.                 ball = Balls((CENTER[0], CENTER[1]-RADIUS), RADIUS, 270, win)
  168.                 ball_group.add(ball)
  169.             player_alive = True
  170.         if sound_btn.draw(win):
  171.             sound_on = not sound_on
  172.             if sound_on:
  173.                 sound_btn.update_image(sound_on_img)
  174.                 pygame.mixer.music.play(loops=-1)
  175.             else:
  176.                 sound_btn.update_image(sound_off_img)
  177.                 pygame.mixer.music.stop()
  178.     if game_page:
  179.         pygame.draw.circle(win, BLACK, CENTER, 8020)
  180.         ball_group.update(color)
  181.         coin_group.update(color)
  182.         tile_group.update()
  183.         score_msg.update(score)
  184.         particle_group.update()
  185.         if player_alive:
  186.             for ball in ball_group:
  187.                 if pygame.sprite.spritecollide(ball, coin_group, True):
  188.                     score_fx.play()
  189.                     score += 1
  190.                     if highscore <= score:
  191.                             highscore = score
  192.                     x, y = ball.rect.center
  193.                     for i in range(10):
  194.                         particle = Particle(x, y, color, win)
  195.                         particle_group.add(particle)
  196.                 if pygame.sprite.spritecollide(ball, tile_group, True):
  197.                     x, y = ball.rect.center
  198.                     for i in range(30):
  199.                         particle = Particle(x, y, color, win)
  200.                         particle_group.add(particle)
  201.                     player_alive = False
  202.                     dead_fx.play()
  203.             current_time = pygame.time.get_ticks()
  204.             delta = current_time- start_time
  205.             if  coin_delta < delta < coin_delta + 100 and new_coin:
  206.                 y = random.randint(CENTER[1]-RADIUS, CENTER[1]+RADIUS)
  207.                 coin = Coins(y, win)
  208.                 coin_group.add(coin)
  209.                 new_coin = False
  210.             if current_time- start_time >= tile_delta:
  211.                 y = random.choice([CENTER[1]-80, CENTER[1], CENTER[1]+80])
  212.                 type_ = random.randint(1,3)
  213.                 t = Tiles(y, type_, win)
  214.                 tile_group.add(t)
  215.                 start_time = current_time
  216.                 new_coin = True
  217.         if not player_alive and len(particle_group) == 0:
  218.             score_page = True
  219.             game_page = False
  220.             score_page_fx.play()
  221.             ball_group.empty()
  222.             tile_group.empty()
  223.             coin_group.empty()
  224.     pygame.draw.rect(win, BLUE, (00, WIDTH, HEIGHT), 5, border_radius=10)
  225.     clock.tick(FPS)
  226.     pygame.display.update()
  227. pygame.quit()
9、恐龙避障

代码太多了,接下来就简单介绍下,有兴趣的在公众号内回复【游戏】即可获取所有的游戏源码。

bdb8284f1276606975cd07c6a395f428.png

10、狡猾的墙

7ba8f83cf6a4b136e7197d86cca4c6e7.png

11、点和盒子

14e19b00380d3f13e80b41bb636d0359.png

12、捉蛋游戏

5f8e4bb8741de73fd5dcadce2d123b32.png

13、愤怒的小鸟

ab1c3f0d79e4f6ddf40b24f8c4dd6282.png

14、捉鬼特工队

22c56fc6b9a4b4ef4d49c4f4de40c161.png

15、绞刑吏

f0a5e453961395d574ae8489266c2fb0.png

16、六角冲

9b1987e5d6d54edefcd6e8db694b676d.png

17、匹配选择

6ad0920678ffe9a60d280db02acd431d.png

18、丛林探险

ca0529194c59c2cddaa7ed0a9deffef2.png

19、关卡设计

d74d13aacf8881999a2834a42f00747c.png

20、记忆拼图

9e3113efdbc45c501af0f8ec31806866.png

21、扫雷

4cde00396ba36ff63b15cae24e96e595.png

22、钢琴砖

f0caa0fd45aa5bba01ee8f0d313c22e8.png

23、图片滑动拼图

2c7911e0304267417fbd368b7e174a80.png

24、乒乓球

2819d5f826ccc562451907ea0409eb50.png

25、冲刺

a57d82cccb3f582fb507d27b87bf1c75.png

26、石头剪刀布

dc740fa6b1b062586e75f0d3f20cd0e1.png

27、旋转冲击

9d5c744eba36fd1415503d6588a906ff.png

28、贪吃蛇

6ef7c818f394a98181d18ef7072788a9.png

29、剪刀

acc09de593d0cd83edd7c7bd67dcdeec.png

30、俄罗斯方块

348bb1d0dabaef400e813af366728909.png

相关文件及代码都已上传,公众号回复【游戏】即可获取。

万水千山总是情,点个 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/115889
推荐阅读
相关标签