python實現(xiàn)飛船游戲的縱向移動
本文實例為大家分享了python實現(xiàn)飛船游戲的縱向移動,供大家參考,具體內(nèi)容如下
我是跟著書里一步步寫到橫向移動后 我就想怎么縱向移動,放上自己寫的代碼,如果有問題的話,請指出來,我也是剛剛學習python,希望可以跟大家多多交流。
新增的就是有關up和down的代碼了。
我自己是成功了,肯定有其他的更優(yōu)化的,那就等我在學習一段時間吧。
附上代碼:
game_function:
import sys import pygame # 監(jiān)視鍵盤和鼠標事件 def check_keydown_events(event,ship): if event.key==pygame.K_RIGHT: ship.moving_right=True elif event.key==pygame.K_LEFT: ship.moving_left=True elif event.key==pygame.K_UP: ship.moving_up=True elif event.key==pygame.K_DOWN: ship.moving_down=True def check_keyup_events(event,ship): if event.key==pygame.K_RIGHT: ship.moving_right=False elif event.key==pygame.K_LEFT: ship.moving_left=False elif event.key==pygame.K_UP: ship.moving_up=False elif event.key==pygame.K_DOWN: ship.moving_down=False def check_events(ship): for event in pygame.event.get(): if event.type==pygame.QUIT: sys.exit() elif event.type==pygame.KEYDOWN: check_keydown_events(event,ship) elif event.type==pygame.KEYUP: check_keyup_events(event,ship) def update_screen(ai_settings,screen,ship): screen.fill(ai_settings.bg_color) ship.blitme() pygame.display.flip() #讓最近回執(zhí)的屏幕可見(刷新)
ship:
import pygame
class Ship():
def __init__(self,ai_settings,screen):
self.screen=screen
self.ai_settings=ai_settings
#加載飛船圖像
self.image=pygame.image.load('chengyan_ship.bmp')
self.rect=self.image.get_rect()
self.screen_rect=screen.get_rect()
self.rect.centerx=self.screen_rect.centerx #x的坐標
self.rect.centery=self.screen_rect.centery #y的坐標
self.rect.bottom=self.screen_rect.bottom
self.moving_right=False
self.moving_left=False
self.moving_up=False
self.moving_down=False
#得到飛船移動到最下面的值(我不知道有沒有表述清楚...就是只能飛到界面的最下面)
self.screen_top=self.rect.top
def update(self):
#橫向移動
if self.moving_right and self.rect.right<self.screen_rect.right:
self.rect.centerx+=self.ai_settings.ship_speed_factor
#縱向移動
if self.moving_left and self.rect.left>0:
self.rect.centerx-=self.ai_settings.ship_speed_factor
if self.moving_up and self.rect.top>0:
self.rect.centery-=self.ai_settings.ship_speed_factor
if self.moving_down and self.rect.top<self.screen_top:
self.rect.centery+=self.ai_settings.ship_speed_factor
self.rect.centerx=self.rect.centerx
self.rect.centery=self.rect.centery
def blitme(self):
self.screen.blit(self.image,self.rect)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python使用BeautifulSoup進行XPath和CSS選擇器定位
在 Python 中,BeautifulSoup 是一個常用的 HTML 和 XML 解析庫,它允許我們輕松地定位和提取網(wǎng)頁中的特定元素,本文將詳細介紹如何在 BeautifulSoup 中使用 XPath 和 CSS 選擇器定位 HTML 元素,并提供示例代碼以幫助新手理解這些概念,需要的朋友可以參考下2024-11-11
Python比較文件夾比另一同名文件夾多出的文件并復制出來的方法
這篇文章主要介紹了Python比較文件夾比另一同名文件夾多出的文件并復制出來的方法,涉及Python針對文件與文件夾的操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03
淺析python中while循環(huán)和for循環(huán)
在本篇文章里小編給各位整理的是關于python中while和for循環(huán)知識點詳解,有興趣的朋友們可以學習下。2019-11-11
Python 用turtle實現(xiàn)用正方形畫圓的例子
今天小編就為大家分享一篇Python 用turtle實現(xiàn)用正方形畫圓的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

