用Python实现的水果砍砖块小游戏
水果忍者的玩法很简单,尽可能的切开抛出的水果就行。
今天小五就用python简单的模拟一下这个游戏。在这个简单的项目中,我们用鼠标选择水果来切割,同时炸弹也会隐藏在水果中,如果切开了三次炸弹,玩家就会失败。
一、需要导入的包
import pygame, sysimport osimport random
二、窗口界面设置
# 游戏窗口WIDTH = 800HEIGHT = 500FPS = 15 # gameDisplay的帧率,1/12秒刷新一次pygame.init()pygame.display.set_caption('水果忍者') # 标题gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT)) # 固定窗口大小clock = pygame.time.Clock()# 用到的颜色WHITE = (255,255,255)BLACK = (0,0,0)RED = (255,0,0)GREEN = (0,255,0)BLUE = (0,0,255)background = pygame.image.load('背景.jpg') # 背景font = pygame.font.Font(os.path.join(os.getcwd(), 'comic.ttf'), 42) # 字体score_text = font.render('Score : ' + str(score), True, (255, 255, 255)) # 得分字体样式
三、随机生成水果位置
def generate_random_fruits(fruit):fruit_path = "images/" + fruit + ".png"data[fruit] = {'img': pygame.image.load(fruit_path),'x' : random.randint(100,500),'y' : 800,'speed_x': random.randint(-10,10),'speed_y': random.randint(-80, -60),'throw': False,'t': 0,'hit': False,}if random.random() >= 0.75:data[fruit]['throw'] = Trueelse:data[fruit]['throw'] = Falsedata = {}for fruit in fruits:generate_random_fruits(fruit)
四、绘制字体
font_name = pygame.font.match_font('comic.ttf')def draw_text(display, text, size, x, y):font = pygame.font.Font(font_name, size)text_surface = font.render(text, True, WHITE)text_rect = text_surface.get_rect()text_rect.midtop = (x, y)gameDisplay.blit(text_surface, text_rect)
五、玩家生命的提示
# 绘制玩家的生命def draw_lives(display, x, y, lives, image) :for i in range(lives) :img = pygame.image.load(image)img_rect = img.get_rect()img_rect.x = int(x + 35 * i)img_rect.y = ydisplay.blit(img, img_rect)def hide_cross_lives(x, y):gameDisplay.blit(pygame.image.load("images/red_lives.png"), (x, y))
六、游戏开始与结束的画面
def show_gameover_screen():gameDisplay.blit(background, (0,0))draw_text(gameDisplay, "FRUIT NINJA!", 90, WIDTH / 2, HEIGHT / 4)if not game_over :draw_text(gameDisplay,"Score : " + str(score), 50, WIDTH / 2, HEIGHT /2)draw_text(gameDisplay, "Press a key to begin!", 64, WIDTH / 2, HEIGHT * 3 / 4)pygame.display.flip()waiting = Truewhile waiting:clock.tick(FPS)for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()if event.type == pygame.KEYUP:waiting = False
七、游戏主循环
first_round = Truegame_over = Truegame_running = Truewhile game_running :if game_over :if first_round :show_gameover_screen()first_round = Falsegame_over = Falseplayer_lives = 3draw_lives(gameDisplay, 690, 5, player_lives, 'images/red_lives.png')score = 0for event in pygame.event.get():if event.type == pygame.QUIT:game_running = FalsegameDisplay.blit(background, (0, 0))gameDisplay.blit(score_text, (0, 0))draw_lives(gameDisplay, 690, 5, player_lives, 'images/red_lives.png')for key, value in data.items():if value['throw']:value['x'] += value['speed_x']value['y'] += value['speed_y']value['speed_y'] += (1 * value['t'])value['t'] += 1if value['y'] value['x'] and current_position[0] value['y'] and current_position[1]