当前位置:   article > 正文

python小游戏————兔子_python小兔子代码

python小兔子代码

♥️作者:小刘在这里

♥️每天分享云计算网络运维课堂笔记,疫情之下,你我素未谋面,但你一定要平平安安,一  起努力,共赴美好人生!

♥️夕阳下,是最美的,绽放,愿所有的美好,再疫情结束后如约而至。

目录

一.游戏效果呈现

二.游戏代码

1.主代码

2.cfg

3.README


一.游戏效果呈现

二.游戏代码

1.主代码

  1. '''
  2. Author: 顾木子吖
  3. 微信公众号: Python顾木子吖
  4. 源码领取裙:806965976
  5. '''
  6. import sys
  7. import cfg
  8. import math
  9. import random
  10. import pygame
  11. from modules import *
  12. '''游戏初始化'''
  13. def initGame():
  14. # 初始化pygame, 设置展示窗口
  15. pygame.init()
  16. pygame.mixer.init()
  17. screen = pygame.display.set_mode(cfg.SCREENSIZE)
  18. pygame.display.set_caption('Bunnies and Badgers —— Charles的皮卡丘')
  19. # 加载必要的游戏素材
  20. game_images = {}
  21. for key, value in cfg.IMAGE_PATHS.items():
  22. game_images[key] = pygame.image.load(value)
  23. game_sounds = {}
  24. for key, value in cfg.SOUNDS_PATHS.items():
  25. if key != 'moonlight':
  26. game_sounds[key] = pygame.mixer.Sound(value)
  27. return screen, game_images, game_sounds
  28. '''主函数'''
  29. def main():
  30. # 初始化
  31. screen, game_images, game_sounds = initGame()
  32. # 播放背景音乐
  33. pygame.mixer.music.load(cfg.SOUNDS_PATHS['moonlight'])
  34. pygame.mixer.music.play(-1, 0.0)
  35. # 字体加载
  36. font = pygame.font.Font(None, 24)
  37. # 定义兔子
  38. bunny = BunnySprite(image=game_images.get('rabbit'), position=(100, 100))
  39. # 跟踪玩家的精度变量, 记录了射出的箭头数和被击中的獾的数量.
  40. acc_record = [0., 0.]
  41. # 生命值
  42. healthvalue = 194
  43. # 弓箭
  44. arrow_sprites_group = pygame.sprite.Group()
  45. # 獾
  46. badguy_sprites_group = pygame.sprite.Group()
  47. badguy = BadguySprite(game_images.get('badguy'), position=(640, 100))
  48. badguy_sprites_group.add(badguy)
  49. # 定义了一个定时器, 使得游戏里经过一段时间后就新建一支獾
  50. badtimer = 100
  51. badtimer1 = 0
  52. # 游戏主循环, running变量会跟踪游戏是否结束, exitcode变量会跟踪玩家是否胜利.
  53. running, exitcode = True, False
  54. clock = pygame.time.Clock()
  55. while running:
  56. # --在给屏幕画任何东西之前用黑色进行填充
  57. screen.fill(0)
  58. # --添加的风景也需要画在屏幕上
  59. for x in range(cfg.SCREENSIZE[0]//game_images['grass'].get_width()+1):
  60. for y in range(cfg.SCREENSIZE[1]//game_images['grass'].get_height()+1):
  61. screen.blit(game_images['grass'], (x*100, y*100))
  62. for i in range(4): screen.blit(game_images['castle'], (0, 30+105*i))
  63. # --倒计时信息
  64. countdown_text = font.render(str((90000-pygame.time.get_ticks())//60000)+":"+str((90000-pygame.time.get_ticks())//1000%60).zfill(2), True, (0, 0, 0))
  65. countdown_rect = countdown_text.get_rect()
  66. countdown_rect.topright = [635, 5]
  67. screen.blit(countdown_text, countdown_rect)
  68. # --按键检测
  69. # ----退出与射击
  70. for event in pygame.event.get():
  71. if event.type == pygame.QUIT:
  72. pygame.quit()
  73. sys.exit()
  74. elif event.type == pygame.MOUSEBUTTONDOWN:
  75. game_sounds['shoot'].play()
  76. acc_record[1] += 1
  77. mouse_pos = pygame.mouse.get_pos()
  78. angle = math.atan2(mouse_pos[1]-(bunny.rotated_position[1]+32), mouse_pos[0]-(bunny.rotated_position[0]+26))
  79. arrow = ArrowSprite(game_images.get('arrow'), (angle, bunny.rotated_position[0]+32, bunny.rotated_position[1]+26))
  80. arrow_sprites_group.add(arrow)
  81. # ----移动兔子
  82. key_pressed = pygame.key.get_pressed()
  83. if key_pressed[pygame.K_w]:
  84. bunny.move(cfg.SCREENSIZE, 'up')
  85. elif key_pressed[pygame.K_s]:
  86. bunny.move(cfg.SCREENSIZE, 'down')
  87. elif key_pressed[pygame.K_a]:
  88. bunny.move(cfg.SCREENSIZE, 'left')
  89. elif key_pressed[pygame.K_d]:
  90. bunny.move(cfg.SCREENSIZE, 'right')
  91. # --更新弓箭
  92. for arrow in arrow_sprites_group:
  93. if arrow.update(cfg.SCREENSIZE):
  94. arrow_sprites_group.remove(arrow)
  95. # --更新獾
  96. if badtimer == 0:
  97. badguy = BadguySprite(game_images.get('badguy'), position=(640, random.randint(50, 430)))
  98. badguy_sprites_group.add(badguy)
  99. badtimer = 100 - (badtimer1 * 2)
  100. badtimer1 = 20 if badtimer1>=20 else badtimer1+2
  101. badtimer -= 1
  102. for badguy in badguy_sprites_group:
  103. if badguy.update():
  104. game_sounds['hit'].play()
  105. healthvalue -= random.randint(4, 8)
  106. badguy_sprites_group.remove(badguy)
  107. # --碰撞检测
  108. for arrow in arrow_sprites_group:
  109. for badguy in badguy_sprites_group:
  110. if pygame.sprite.collide_mask(arrow, badguy):
  111. game_sounds['enemy'].play()
  112. arrow_sprites_group.remove(arrow)
  113. badguy_sprites_group.remove(badguy)
  114. acc_record[0] += 1
  115. # --画出弓箭
  116. arrow_sprites_group.draw(screen)
  117. # --画出獾
  118. badguy_sprites_group.draw(screen)
  119. # --画出兔子
  120. bunny.draw(screen, pygame.mouse.get_pos())
  121. # --画出城堡健康值, 首先画了一个全红色的生命值条, 然后根据城堡的生命值往生命条里面添加绿色.
  122. screen.blit(game_images.get('healthbar'), (5, 5))
  123. for i in range(healthvalue):
  124. screen.blit(game_images.get('health'), (i+8, 8))
  125. # --判断游戏是否结束
  126. if pygame.time.get_ticks() >= 90000:
  127. running, exitcode = False, True
  128. if healthvalue <= 0:
  129. running, exitcode = False, False
  130. # --更新屏幕
  131. pygame.display.flip()
  132. clock.tick(cfg.FPS)
  133. # 计算准确率
  134. accuracy = acc_record[0] / acc_record[1] * 100 if acc_record[1] > 0 else 0
  135. accuracy = '%.2f' % accuracy
  136. showEndGameInterface(screen, exitcode, accuracy, game_images)
  137. '''run'''
  138. if __name__ == '__main__':
  139. main()

2.cfg

'''配置文件'''
import os


# FPS
FPS = 100
# 屏幕大小
SCREENSIZE = (640, 480)
# 游戏图片路径
IMAGE_PATHS = {
    'rabbit': os.path.join(os.getcwd(), 'resources/images/dude.png'),
    'grass': os.path.join(os.getcwd(), 'resources/images/grass.png'),
    'castle': os.path.join(os.getcwd(), 'resources/images/castle.png'),
    'arrow': os.path.join(os.getcwd(), 'resources/images/bullet.png'),
    'badguy': os.path.join(os.getcwd(), 'resources/images/badguy.png'),
    'healthbar': os.path.join(os.getcwd(), 'resources/images/healthbar.png'),
    'health': os.path.join(os.getcwd(), 'resources/images/health.png'),
    'gameover': os.path.join(os.getcwd(), 'resources/images/gameover.png'),
    'youwin': os.path.join(os.getcwd(), 'resources/images/youwin.png')
}
# 游戏声音路径
SOUNDS_PATHS = {
    'hit': os.path.join(os.getcwd(), 'resources/audio/explode.wav'),
    'enemy': os.path.join(os.getcwd(), 'resources/audio/enemy.wav'),
    'shoot': os.path.join(os.getcwd(), 'resources/audio/shoot.wav'),
    'moonlight': os.path.join(os.getcwd(), 'resources/audio/moonlight.wav')
}

3.README

  1. # Introduction
  2. https://mp.weixin.qq.com/s/_-AChGldQzdwXN-ljcCMFQ
  3. # Environment
  4. ```
  5. OS: Windows10
  6. Python: Python3.5+(have installed necessary dependencies)
  7. ```
  8. # Usage
  9. ```
  10. Step1:
  11. pip install -r requirements.txt
  12. Step2:
  13. run "python Game1.py"
  14. ```
  15. # Reference
  16. https://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python
  17. # Game Display
  18. ![giphy](demonstration/running.gif)

requirements:pygame

♥️关注,就是我创作的动力

♥️点赞,就是对我最大的认可

♥️这里是小刘,励志用心做好每一篇文章,谢谢大家

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

闽ICP备14008679号