用Python写了一个水果忍者小游戏,(入门必备) |
您所在的位置:网站首页 › python初学代码有哪些 › 用Python写了一个水果忍者小游戏,(入门必备) |
水果忍者的玩法很简单,尽可能的切开抛出的水果就行。 今天就用Python简单的模拟一下这个游戏。在这个简单的项目中,我们用鼠标选择水果来切割,同时炸弹也会隐藏在水果中,如果切开了三次炸弹,玩家就会失败。 这个函数用于随机生成水果和保存水果的数据 '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()在屏幕上的指定位置绘制图像或写入文字。 五、玩家生命的提示 ```python 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.x \= int(x + 35 \* i) 7. img\_rect.y \= 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) 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 \= Falseshow_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 14. for event in pygame.event.get(): 16. if event.type \== pygame.QUIT: 17. game\_running \= False 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') 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 30. if value\['y'\] value\['x'\] and current\_position\[0\] value\['y'\] and current\_position\[1\] |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |