Py学习  »  Python

用Python写了一个水果忍者小游戏

马哥Linux运维 • 3 年前 • 532 次点击  

水果忍者的玩法很简单,尽可能的切开抛出的水果就行。
今天小五就用python简单的模拟一下这个游戏。在这个简单的项目中,我们用鼠标选择水果来切割,同时炸弹也会隐藏在水果中,如果切开了三次炸弹,玩家就会失败。

一、需要导入的包

  1. import pygame, sys
  2. import os
  3. import random

二、窗口界面设置

  1. # 游戏窗口
  2. WIDTH = 800
  3. HEIGHT = 500
  4. FPS = 15             # gameDisplay的帧率,1/12秒刷新一次
  5. pygame.init()
  6. pygame.display.set_caption('水果忍者') # 标题
  7. gameDisplay = pygame. display.set_mode((WIDTH, HEIGHT)) # 固定窗口大小
  8. clock = pygame.time.Clock()
  9.  
  10. # 用到的颜色
  11. WHITE = (255,255,255)
  12. BLACK =  (0,0,0)
  13. RED = (255,0,0)
  14. GREEN = (0,255,0)
  15. BLUE = (0,0 ,255)
  16.  
  17. background = pygame.image.load('背景.jpg') # 背景
  18. font = pygame.font.Font(os.path.join(os.getcwd(),  'comic.ttf'), 42) # 字体
  19. score_text = font.render('Score : ' + str(score), True, (255, 255, 255)) # 得分字体样式

三、随机生成水果位置

  1. def generate_random_fruits(fruit):
  2.     fruit_path = "images/" + fruit + ".png"
  3.     data[fruit] = {
  4.         'img': pygame.image. load(fruit_path),
  5.         'x' : random.randint(100,500),
  6.         'y' : 800,
  7.         'speed_x': random.randint(-10,10),
  8.         'speed_y': random.randint(-80, -60),
  9.         'throw': False,
  10.         't': 0,
  11.         'hit': False,
  12.     }
  13.  
  14.     if random.random() >= 0.75:
  15.         data[fruit]['throw'] = True
  16.     else:
  17.         data[fruit]['throw']  = False
  18.  
  19. data = {}
  20. for fruit in fruits:
  21.     generate_random_fruits(fruit)
  • 这个函数用于随机生成水果和保存水果的数据
  • 'x'和'y'存储水果在x坐标和y坐标上的位置。
  • Speed_x和speed_y是存储水果在x和y方向的移动速度。它也控制水果的对角线移动。
  • throw,用于判断生成的水果坐标是否在游戏之外。如果在外面,那么将被丢弃。
  • data字典用于存放随机生成的水果的数据。

四、绘制字体

  1. font_name = pygame. font.match_font('comic.ttf')
  2.  
  3. def draw_text(display, text, size, x, y):
  4.     font = pygame.font.Font(font_name, size)
  5.     text_surface  = font.render(text, True, WHITE)
  6.     text_rect = text_surface.get_rect()
  7.     text_rect.midtop = (x, y)
  8.     gameDisplay.blit(text_surface, text_rect )
  • Draw_text函数可以在屏幕上绘制文字。
  • get_rect() 返回 Rect 对象。
  • X和y是X方向和Y方向的位置。
  • blit()在屏幕上的指定位置绘制图像或写入文字。

五、玩家生命的提示

  1. # 绘制玩家的生命
  2. def draw_lives(display, x, y, lives, image) :
  3. for i in range(lives)  :
  4. img = pygame.image.load(image)
  5. img_rect = img.get_rect()
  6. img_rect.= int(+ 35 * i)
  7. img_rect .= y
  8. display.blit(img, img_rect)
  1. def hide_cross_lives(x, y):
  2. gameDisplay.blit(pygame.image.load("images/red_lives.png"),  (x, y))
  • img_rect获取十字图标的(x,y)坐标(位于最右上方)
  • img_rect .x 设置下一个十字图标距离前一个图标35像素。
  • img_rect.y负责确定十字图标从屏幕顶部开始的位置。

六、游戏开始与结束的画面

  1. def show_gameover_screen():
  2.     gameDisplay.blit(background, (0,0))
  3.     draw_text(gameDisplay,  "FRUIT NINJA!", 90, WIDTH / 2, HEIGHT / 4)
  4.     if not game_over :
  5.         draw_text(gameDisplay,"Score : " + str(score), 50, WIDTH  / 2, HEIGHT /2)
  6.  
  7.     draw_text(gameDisplay, "Press a key to begin!", 64, WIDTH / 2, HEIGHT * 3 / 4)
  8.     pygame. display.flip()
  9.     waiting = True
  10.     while waiting:
  11.         clock.tick(FPS)
  12.         for event in pygame.event.get():
  13.             if  event.type == pygame.QUIT:
  14.                 pygame.quit()
  15.             if event.type == pygame.KEYUP:
  16.                 waiting = False
  • show_gameover_screen()函数显示初始游戏画面和游戏结束画面。
  • pygame.display.flip()将只更新屏幕的一部分,但如果没有参数传递,则会更新整个屏幕。
  • pygame.event.get()将返回存储在pygame事件队列中的所有事件。
  • 如果事件类型等于quit,那么pygame将退出。
  • event.KEYUP事件,当按键被按下和释放时发生的事件。

七、游戏主循环

  1. first_round = True
  2. game_over = True        
  3. game_running = True    
  4. while game_running :
  5.     if game_over :
  6.         if first_round :
  7.             show_gameover_screen()
  8.             first_round = False
  9.         game_over = False
  10.         player_lives = 3
  11.         draw_lives(gameDisplay, 690, 5, player_lives, 'images/red_lives.png')
  12.         score  = 0
  13.  
  14.     for event in pygame.event.get():
  15.  
  16.         if event.type == pygame.QUIT:
  17.             game_running = False
  18.  
  19.     gameDisplay.blit(background, (0, 0))
  20.     gameDisplay.blit(score_text, (0, 0))
  21.     draw_lives(gameDisplay, 690,  5, player_lives, 'images/red_lives.png')
  22.  
  23.     for key, value in data.items():
  24.         if value['throw']:
  25.             value['x'] += value[ 'speed_x']
  26.             value['y'] += value['speed_y']
  27.             value['speed_y'] += (1 * value['t'])
  28.             value['t'] += 1
  29.  
  30.             if value['y'] <= 800:
  31.                 gameDisplay.blit(value['img'], (value['x'], value['y']))
  32.             else:
  33.                 generate_random_fruits(key)
  34.  
  35.             current_position = pygame.mouse.get_pos()
  36.  
  37.             if not value['hit'] and current_position[0] > value['x' ] and current_position[0] < value['x']+60 \
  38.                     and current_position[1] > value['y'] and current_position[1] < value['y' ]+60:
  39.                 if key == 'bomb':
  40.                     player_lives -= 1
  41.                     if player_lives == 0:
  42.                         hide_cross_lives(690, 15)
  43.                     elif player_lives  == 1 :
  44.                         hide_cross_lives(725, 15)
  45.                     elif player_lives == 2 :
  46.                         hide_cross_lives(760, 15)
  47.                   
  48.                     if player_lives <  0 :
  49.                         show_gameover_screen()
  50.                         game_over = True
  51.  
  52.                     half_fruit_path = "images/explosion.png"
  53.                 else:
  54.                     half_fruit_path = "images/" + "half_" + key +  ".png"
  55.  
  56.                 value['img'] = pygame.image.load(half_fruit_path)
  57.                 value['speed_x'] += 10
  58.                 if key != 'bomb' :
  59.                     score += 1
  60.                 score_text = font.render('Score : ' + str(score), True, (255, 255, 255))
  61.                 value['hit']  = True
  62.         else:
  63.             generate_random_fruits(key)
  64.  
  65.     pygame.display.update()
  66.     clock.tick(FPS)
  67.  
  68. pygame.quit()
  • 这是游戏的主循环
  • 如果超过3个炸弹被切掉,game_over终止游戏,同时循环。
  • game_running 用于管理游戏循环。
  • 如果事件类型是退出,那么游戏窗口将被关闭。
  • 在这个游戏循环中,我们动态显示屏幕内的水果。
  • 如果一个水果没有被切开,那么它将不会发生任何事情。如果水果被切开,那么一个半切开的水果图像应该出现在该水果的地方
  • 如果用户点击了三次炸弹,将显示GAME OVER信息,并重置窗口。
  • clock.tick()将保持循环以正确的速度运行。循环应该在每1/12秒后更新一次

文章转载:Python编程学习圈

(版权归原作者所有,侵删)


点击下方“阅读原文”查看更多

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129702