当前位置:   article > 正文

python简单小游戏代码100行,python小游戏代码能用的

python简单小游戏代码100行,python小游戏代码能用的

大家好,本文将围绕python简单小游戏代码100行展开说明,python小游戏代码能用的是一个很多人都想弄明白的事情,想搞清楚python小游戏程序源代码需要先了解以下几个事情。


前言

在学习Python的过程中,不妨给自己增添一点乐趣,博主分享了几个小游戏的代码,欢迎大家边学边玩~
在这里插入图片描述


1.愤怒的墙

在这里插入图片描述

代码如下(示例):

  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 = 288, 512
  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 = (255, 0, 0)
  17. WHITE = (255, 255, 255)
  18. BLACK = (0, 0, 0)
  19. GRAY = (54, 69, 79)
  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(140, 40, 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 [(40, 120), (WIDTH - 20, 240), (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(134, 90, 100, "Angry",title_font, WHITE, win)
  65. walls = Message(164, 145, 80, "Walls",title_font, WHITE, win)
  66. tap_to_play_font = "Fonts/DebugFreeTrial-MVdYB.otf"
  67. tap_to_play = Message(144, 400, 32, "TAP TO PLAY",tap_to_play_font, WHITE, win)
  68. tap_to_replay = Message(144, 400, 30, "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+3, 0, 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, 10, 1, 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(144, 60, 55, "Score",font, WHITE, win)
  213. else:
  214. score_msg = Message(144, 60, 55, "New High",font, WHITE, win)
  215. score_point = Message(144, 110, 45, 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()

2.弹跳的球

在这里插入图片描述

代码如下(示例):

  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 = 288, 512
  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 = (255, 0, 0)
  17. WHITE = (255, 255, 255)
  18. BLACK = (0, 0, 0)
  19. GRAY = (54, 69, 79)
  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(140, 40, 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 [(40, 120), (WIDTH - 20, 240), (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(134, 90, 100, "Angry",title_font, WHITE, win)
  65. walls = Message(164, 145, 80, "Walls",title_font, WHITE, win)
  66. tap_to_play_font = "Fonts/DebugFreeTrial-MVdYB.otf"
  67. tap_to_play = Message(144, 400, 32, "TAP TO PLAY",tap_to_play_font, WHITE, win)
  68. tap_to_replay = Message(144, 400, 30, "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+3, 0, 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, 10, 1, 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(144, 60, 55, "Score",font, WHITE, win)
  213. else:
  214. score_msg = Message(144, 60, 55, "New High",font, WHITE, win)
  215. score_point = Message(144, 110, 45, 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.行星游戏

在这里插入图片描述

代码如下(示例):

  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 = 500, 500
  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, (340, 10))
  129. pygame.display.flip()
  130. clock.tick(30)
  131. pygame.quit()

4.汽车避障

在这里插入图片描述

  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 = 288, 512
  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 = [50, 95, 142, 190]
  17. # COLORS **********************************************************************
  18. WHITE = (255, 255, 255)
  19. BLUE = (30, 144,255)
  20. RED = (255, 0, 0)
  21. GREEN = (0, 255, 0)
  22. BLACK = (0, 0, 20)
  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, (220, 220))
  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(1, 9):
  45. img = pygame.image.load(f'Assets/cars/{i}.png')
  46. img = pygame.transform.scale(img, (59, 101))
  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, (18, 36))
  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, (100, 34), center(play_img)+10, HEIGHT-80)
  60. la_btn = Button(left_arrow, (32, 42), 40, 180)
  61. ra_btn = Button(right_arrow, (32, 42), WIDTH-60, 180)
  62. home_btn = Button(home_btn_img, (24, 24), 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, (24, 24), 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 = 0, 0.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, (80, 240))
  176. win.blit(dodge_img, (50, 280))
  177. win.blit(num_coin_img, (180, 250))
  178. win.blit(num_dodge_img, (180, 300))
  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 = 0, 0.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 = 0, 0.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([1, 2], weights=[6, 4], k=1)[0]
  219. x = random.choice(lane_pos)+10
  220. if type == 1:
  221. count = random.randint(1, 3)
  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([1, 2, 3], 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, (20, 20, cfuel, 15), border_radius=5)
  257. pygame.draw.rect(win, WHITE, (20, 20, 100, 15), 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, (0, 0, WIDTH, HEIGHT), 3)
  283. clock.tick(FPS)
  284. pygame.display.update()
  285. pygame.quit()

5.洞窟物语

在这里插入图片描述

  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 = 288, 512
  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, (60, 150), 30, 170)
  26. quit_img = pygame.transform.rotate(pygame.image.load("Assets/quit.png"), -90)
  27. quit_btn = Button(quit_img, (60, 150), 140, 170)
  28. replay_img = pygame.transform.rotate(pygame.image.load("Assets/replay.png"), -90)
  29. replay_btn = Button(replay_img, (40, 40), 100, 190)
  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, (40, 40), 100, 260)
  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(5, 27, 35, 50),
  40. 'Down' : pygame.Rect(5, 160, 35, 50),
  41. 'Left' : pygame.Rect(5, 320, 35, 50),
  42. 'Right' : pygame.Rect(5, 450, 35, 50)
  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, (255, 0, 0), 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()

总结

祝大家边学边玩,游玩愉快~
在这里插入图片描述

关于Python技术储备

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

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