新聞中心
這部分是關(guān)于在使用 Python 的 Pygame 模塊開發(fā)的視頻游戲總給你的玩家提供收集的寶物和經(jīng)驗(yàn)值的內(nèi)容。

從網(wǎng)站建設(shè)到定制行業(yè)解決方案,為提供做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)服務(wù)體系,各種行業(yè)企業(yè)客戶提供網(wǎng)站建設(shè)解決方案,助力業(yè)務(wù)快速發(fā)展。創(chuàng)新互聯(lián)將不斷加快創(chuàng)新步伐,提供優(yōu)質(zhì)的建站服務(wù)。
這是正在進(jìn)行的關(guān)于使用 Python 3 的 Pygame 模塊創(chuàng)建視頻游戲的系列文章的第十部分。以前的文章有:
- 通過構(gòu)建一個(gè)簡單的擲骰子游戲去學(xué)習(xí)怎么用 Python 編程
- 使用 Python 和 Pygame 模塊構(gòu)建一個(gè)游戲框架
- 如何在你的 Python 游戲中添加一個(gè)玩家
- 用 Pygame 使你的游戲角色移動起來
- 如何向你的 Python 游戲中添加一個(gè)敵人
- 在 Pygame 游戲中放置平臺
- 在你的 Python 游戲中模擬引力
- 為你的 Python 平臺類游戲添加跳躍功能
- 使你的 Python 游戲玩家能夠向前和向后跑
如果你已經(jīng)閱讀了本系列的前幾篇文章,那么你已經(jīng)了解了編寫游戲的所有基礎(chǔ)知識?,F(xiàn)在你可以在這些基礎(chǔ)上,創(chuàng)造一個(gè)全功能的游戲。當(dāng)你第一次學(xué)習(xí)時(shí),遵循本系列代碼示例,這樣的“用例”是有幫助的,但是,用例也會約束你。現(xiàn)在是時(shí)候運(yùn)用你學(xué)到的知識,以新的方式應(yīng)用它們了。
如果說,說起來容易做起來難,這篇文章展示了一個(gè)如何將你已經(jīng)了解的內(nèi)容用于新目的的例子中。具體來說,就是它涵蓋了如何使用你以前的課程中已經(jīng)了解到的來實(shí)現(xiàn)獎勵系統(tǒng)。
在大多數(shù)電子游戲中,你有機(jī)會在游戲世界中獲得“獎勵”或收集到寶物和其他物品。獎勵通常會增加你的分?jǐn)?shù)或者你的生命值,或者為你的下一次任務(wù)提供信息。
游戲中包含的獎勵類似于編程平臺。像平臺一樣,獎勵沒有用戶控制,隨著游戲世界的滾動進(jìn)行,并且必須檢查與玩家的碰撞。
創(chuàng)建獎勵函數(shù)
獎勵和平臺非常相似,你甚至不需要一個(gè)獎勵的類。你可以重用 Platform 類,并將結(jié)果稱為“獎勵”。
由于獎勵類型和位置可能因關(guān)卡不同而不同,如果你還沒有,請?jiān)谀愕?Level 中創(chuàng)建一個(gè)名為 loot 的新函數(shù)。因?yàn)楠剟钗锲凡皇瞧脚_,你也必須創(chuàng)建一個(gè)新的 loot_list 組,然后添加獎勵物品。與平臺、地面和敵人一樣,該組用于檢查玩家碰撞:
def loot(lvl,lloc):if lvl == 1:loot_list = pygame.sprite.Group()loot = Platform(300,ty*7,tx,ty, 'loot_1.png')loot_list.add(loot)if lvl == 2:print(lvl)return loot_list
你可以隨意添加任意數(shù)量的獎勵對象;記住把每一個(gè)都加到你的獎勵清單上。Platform 類的參數(shù)是獎勵圖標(biāo)的 X 位置、Y 位置、寬度和高度(通常讓你的獎勵精靈保持和所有其他方塊一樣的大小最為簡單),以及你想要用作的獎勵的圖片。獎勵的放置可以和貼圖平臺一樣復(fù)雜,所以使用創(chuàng)建關(guān)卡時(shí)需要的關(guān)卡設(shè)計(jì)文檔。
在腳本的設(shè)置部分調(diào)用新的獎勵函數(shù)。在下面的代碼中,前三行是上下文,所以只需添加第四行:
enemy_list = Level.bad( 1, eloc )ground_list = Level.ground( 1,gloc,tx,ty )plat_list = Level.platform( 1,tx,ty )loot_list = Level.loot(1,tx,ty)
正如你現(xiàn)在所知道的,除非你把它包含在你的主循環(huán)中,否則獎勵不會被顯示到屏幕上。將下面代碼示例的最后一行添加到循環(huán)中:
enemy_list.draw(world)ground_list.draw(world)plat_list.draw(world)loot_list.draw(world)
啟動你的游戲看看會發(fā)生什么。
Loot in Python platformer
你的獎勵將會顯示出來,但是當(dāng)你的玩家碰到它們時(shí),它們不會做任何事情,當(dāng)你的玩家經(jīng)過它們時(shí),它們也不會滾動。接下來解決這些問題。
滾動獎勵
像平臺一樣,當(dāng)玩家在游戲世界中移動時(shí),獎勵必須滾動。邏輯與平臺滾動相同。要向前滾動獎勵物品,添加最后兩行:
for e in enemy_list:e.rect.x -= scrollfor l in loot_list:l.rect.x -= scroll
要向后滾動,請?zhí)砑幼詈髢尚校?/p>
for e in enemy_list:e.rect.x += scrollfor l in loot_list:l.rect.x += scroll
再次啟動你的游戲,看看你的獎勵物品現(xiàn)在表現(xiàn)得像在游戲世界里一樣了,而不是僅僅畫在上面。
檢測碰撞
就像平臺和敵人一樣,你可以檢查獎勵物品和玩家之間的碰撞。邏輯與其他碰撞相同,除了撞擊不會(必然)影響重力或生命值。取而代之的是,命中會導(dǎo)致獎勵物品會消失并增加玩家的分?jǐn)?shù)。
當(dāng)你的玩家觸摸到一個(gè)獎勵對象時(shí),你可以從 loot_list 中移除該對象。這意味著當(dāng)你的主循環(huán)在 loot_list 中重繪所有獎勵物品時(shí),它不會重繪那個(gè)特定的對象,所以看起來玩家已經(jīng)獲得了獎勵物品。
在 Player 類的 update 函數(shù)中的平臺碰撞檢測之上添加以下代碼(最后一行僅用于上下文):
loot_hit_list = pygame.sprite.spritecollide(self, loot_list, False)for loot in loot_hit_list:loot_list.remove(loot)self.score += 1print(self.score)plat_hit_list = pygame.sprite.spritecollide(self, plat_list, False)
當(dāng)碰撞發(fā)生時(shí),你不僅要把獎勵從它的組中移除,還要給你的玩家一個(gè)分?jǐn)?shù)提升。你還沒有創(chuàng)建分?jǐn)?shù)變量,所以請將它添加到你的玩家屬性中,該屬性是在 Player 類的 __init__ 函數(shù)中創(chuàng)建的。在下面的代碼中,前兩行是上下文,所以只需添加分?jǐn)?shù)變量:
self.frame = 0self.health = 10self.score = 0
當(dāng)在主循環(huán)中調(diào)用 update 函數(shù)時(shí),需要包括 loot_list:
player.gravity()player.update()
如你所見,你已經(jīng)掌握了所有的基本知識。你現(xiàn)在要做的就是用新的方式使用你所知道的。
在下一篇文章中還有一些提示,但是與此同時(shí),用你學(xué)到的知識來制作一些簡單的單關(guān)卡游戲。限制你試圖創(chuàng)造的東西的范圍是很重要的,這樣你就不會埋沒自己。這也使得最終的成品看起來和感覺上更容易完成。
以下是迄今為止你為這個(gè) Python 平臺編寫的所有代碼:
#!/usr/bin/env python3# draw a world# add a player and player control# add player movement# add enemy and basic collision# add platform# add gravity# add jumping# add scrolling# GNU All-Permissive License# Copying and distribution of this file, with or without modification,# are permitted in any medium without royalty provided the copyright# notice and this notice are preserved. This file is offered as-is,# without any warranty.import pygameimport sysimport os'''Objects'''class Platform(pygame.sprite.Sprite):# x location, y location, img width, img height, img filedef __init__(self,xloc,yloc,imgw,imgh,img):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(os.path.join('images',img)).convert()self.image.convert_alpha()self.rect = self.image.get_rect()self.rect.y = ylocself.rect.x = xlocclass Player(pygame.sprite.Sprite):'''Spawn a player'''def __init__(self):pygame.sprite.Sprite.__init__(self)self.movex = 0self.movey = 0self.frame = 0self.health = 10self.collide_delta = 0self.jump_delta = 6self.score = 1self.images = []for i in range(1,9):img = pygame.image.load(os.path.join('images','hero' + str(i) + '.png')).convert()img.convert_alpha()img.set_colorkey(ALPHA)self.images.append(img)self.image = self.images[0]self.rect = self.image.get_rect()def jump(self,platform_list):self.jump_delta = 0def gravity(self):self.movey += 3.2 # how fast player fallsif self.rect.y > worldy and self.movey >= 0:self.movey = 0self.rect.y = worldy-tydef control(self,x,y):'''control player movement'''self.movex += xself.movey += ydef update(self):'''Update sprite position'''self.rect.x = self.rect.x + self.movexself.rect.y = self.rect.y + self.movey# moving leftif self.movex < 0:self.frame += 1if self.frame > ani*3:self.frame = 0self.image = self.images[self.frame//ani]# moving rightif self.movex > 0:self.frame += 1if self.frame > ani*3:self.frame = 0self.image = self.images[(self.frame//ani)+4]# collisionsenemy_hit_list = pygame.sprite.spritecollide(self, enemy_list, False)for enemy in enemy_hit_list:self.health -= 1#print(self.health)loot_hit_list = pygame.sprite.spritecollide(self, loot_list, False)for loot in loot_hit_list:loot_list.remove(loot)self.score += 1print(self.score)plat_hit_list = pygame.sprite.spritecollide(self, plat_list, False)for p in plat_hit_list:self.collide_delta = 0 # stop jumpingself.movey = 0if self.rect.y > p.rect.y:self.rect.y = p.rect.y+tyelse:self.rect.y = p.rect.y-tyground_hit_list = pygame.sprite.spritecollide(self, ground_list, False)for g in ground_hit_list:self.movey = 0self.rect.y = worldy-ty-tyself.collide_delta = 0 # stop jumpingif self.rect.y > g.rect.y:self.health -=1print(self.health)if self.collide_delta < 6 and self.jump_delta < 6:self.jump_delta = 6*2self.movey -= 33 # how high to jumpself.collide_delta += 6self.jump_delta += 6class Enemy(pygame.sprite.Sprite):'''Spawn an enemy'''def __init__(self,x,y,img):pygame.sprite.Sprite.__init__(self)self.image = pygame.image.load(os.path.join('images',img))self.movey = 0#self.image.convert_alpha()#self.image.set_colorkey(ALPHA)self.rect = self.image.get_rect()self.rect.x = xself.rect.y = yself.counter = 0def move(self):'''enemy movement'''distance = 80speed = 8self.movey += 3.2if self.counter >= 0 and self.counter <= distance:self.rect.x += speedelif self.counter >= distance and self.counter <= distance*2:self.rect.x -= speedelse:self.counter = 0self.counter += 1if not self.rect.y >= worldy-ty-ty:self.rect.y += self.moveyplat_hit_list = pygame.sprite.spritecollide(self, plat_list, False)for p in plat_hit_list:self.movey = 0if self.rect.y > p.rect.y:self.rect.y = p.rect.y+tyelse:self.rect.y = p.rect.y-tyground_hit_list = pygame.sprite.spritecollide(self, ground_list, False)for g in ground_hit_list:self.rect.y = worldy-ty-tyclass Level():def bad(lvl,eloc):if lvl == 1:enemy = Enemy(eloc[0],eloc[1],'yeti.png') # spawn enemyenemy_list = pygame.sprite.Group() # create enemy groupenemy_list.add(enemy) # add enemy to groupif lvl == 2:print("Level " + str(lvl) )return enemy_listdef loot(lvl,tx,ty):if lvl == 1:loot_list = pygame.sprite.Group()loot = Platform(200,ty*7,tx,ty, 'loot_1.png')loot_list.add(loot)if lvl == 2:print(lvl)return loot_listdef ground(lvl,gloc,tx,ty):ground_list = pygame.sprite.Group()i=0if lvl == 1:while i < len(gloc):ground = Platform(gloc[i],worldy-ty,tx,ty,'ground.png')ground_list.add(ground)i=i+1if lvl == 2:print("Level " + str(lvl) )return ground_listdef platform(lvl,tx,ty):plat_list = pygame.sprite.Group()ploc = []i=0if lvl == 1:ploc.append((20,worldy-ty-128,3))ploc.append((300,worldy-ty-256,3))ploc.append((500,worldy-ty-128,4))while i < len(ploc):j=0while j <= ploc[i][2]:plat = Platform((ploc[i][0]+(j*tx)),ploc[i][1],tx,ty,'ground.png')plat_list.add(plat)j=j+1print('run' + str(i) + str(ploc[i]))i=i+1if lvl == 2:print("Level " + str(lvl) )return plat_list'''Setup'''worldx = 960worldy = 720fps = 40 # frame rateani = 4 # animation cyclesclock = pygame.time.Clock()pygame.init()main = TrueBLUE = (25,25,200)BLACK = (23,23,23 )WHITE = (254,254,254)ALPHA = (0,255,0)world = pygame.display.set_mode([worldx,worldy])backdrop = pygame.image.load(os.path.join('images','stage.png')).convert()backdropbox = world.get_rect()player = Player() # spawn playerplayer.rect.x = 0player.rect.y = 0player_list = pygame.sprite.Group()player_list.add(player)steps = 10forwardx = 600backwardx = 230eloc = []eloc = [200,20]gloc = []#gloc = [0,630,64,630,128,630,192,630,256,630,320,630,384,630]tx = 64 #tile sizety = 64 #tile sizei=0while i <= (worldx/tx)+tx:gloc.append(i*tx)i=i+1enemy_list = Level.bad( 1, eloc )ground_list = Level.ground( 1,gloc,tx,ty )plat_list = Level.platform( 1,tx,ty )loot_list = Level.loot(1,tx,ty)'''Main loop'''while main == True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit(); sys.exit()main = Falseif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT or event.key == ord('a'):print("LEFT")player.control(-steps,0)if event.key == pygame.K_RIGHT or event.key == ord('d'):print("RIGHT")player.control(steps,0)if event.key == pygame.K_UP or event.key == ord('w'):print('jump')if event.type == pygame.KEYUP:if event.key == pygame.K_LEFT or event.key == ord('a'):player.control(steps,0)if event.key == pygame.K_RIGHT or event.key == ord('d'):player.control(-steps,0)if event.key == pygame.K_UP or event.key == ord('w'):player.jump(plat_list)if event.key == ord('q'):pygame.quit()sys.exit()main = False# scroll the world forwardif player.rect.x >= forwardx:scroll = player.rect.x - forwardxplayer.rect.x = forwardxfor p in plat_list:p.rect.x -= scrollfor e in enemy_list:e.rect.x -= scrollfor l in loot_list:l.rect.x -= scroll# scroll the world backwardif player.rect.x <= backwardx:scroll = backwardx - player.rect.xplayer.rect.x = backwardxfor p in plat_list:p.rect.x += scrollfor e in enemy_list:e.rect.x += scrollfor l in loot_list:l.rect.x += scrollworld.blit(backdrop, backdropbox)player.gravity() # check gravityplayer.update()player_list.draw(world) #refresh player positionenemy_list.draw(world) # refresh enemiesground_list.draw(world) # refresh enemiesplat_list.draw(world) # refresh platformsloot_list.draw(world) # refresh lootfor e in enemy_list:e.move()pygame.display.flip()clock.tick(fps)
標(biāo)題名稱:在你的Python平臺類游戲中放一些獎勵
分享鏈接:http://m.fisionsoft.com.cn/article/cogeego.html


咨詢
建站咨詢
