Python菜鸟快乐游戏编程_pygame(5)

Python菜鸟快乐游戏编程_pygame(博主录制,2K分辨率,超高清)

https://study.163.com/course/courseMain.htm?courseId=1006188025&share=2&shareId=400000000398149

前面介绍了pygame的一些基础知识,这节课我们来个复杂点游戏,DIY植物大战僵尸。当然不是复现原款游戏所有功能,而是简单模拟一下其中乐趣。

打开zombie文件夹,我们可以看到游戏需要很多素材,包括人物,背景,配音等等,我们可以替换这些图片。比如我用川普替换了主角,音乐也可以改为你喜欢的。

运行脚本zombie.py运行环境anaconda2(Python2版本)# -*- coding: utf-8 -*-
"""
Created on Sun Oct  7 10:16:24 2018
作者邮件:[email protected]
作者微信公众号:PythonEducation
"""

############################################################################################
###                                                                                      ###
###   PyGame with a SnowPea shoot bullet for defensing the zombie army coming            ###
###                                                                                      ###
###   Author: Junjie Shi                                                                 ###
###   Email : [email protected]                                                    ###
###                                                                                      ###
###   Do Enjoy the game!                                                                 ###
###   You need to have Python and PyGame installed to run it.                            ###
###   Run it by typing "python zombie.py" in the terminal                                ###
###                                                                                      ###
###   This program is free software: you can redistribute it and/or modify               ###
###   it under the terms of the GNU General Public License as published by               ###
###   the Free Software Foundation, either version 3 of the License, or                  ###
###   (at your option) any later version.                                                ###
###                                                                                      ###
###   This program is distributed in the hope that it will be useful,                    ###
###   but WITHOUT ANY WARRANTY; without even the implied warranty of                     ###
###   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                      ###
###   GNU General Public License for more details.                                       ###
###                                                                                      ###
###   You should have received a copy of the GNU General Public License                  ###
###   along with this program.  If not, see <http://www.gnu.org/licenses/>.              ###                                                                              ###
###                                                                                      ###
############################################################################################

import pygame, random, sys, time
from pygame.locals import *

#set up some variables
WINDOWWIDTH = 1024
WINDOWHEIGHT = 600
FPS = 30

MAXGOTTENPASS = 10
ZOMBIESIZE = 70 #includes newKindZombies
ADDNEWZOMBIERATE = 10
ADDNEWKINDZOMBIE = ADDNEWZOMBIERATE

NORMALZOMBIESPEED = 2
NEWKINDZOMBIESPEED = NORMALZOMBIESPEED / 2

PLAYERMOVERATE = 15
BULLETSPEED = 10
ADDNEWBULLETRATE = 15

TEXTCOLOR = (255, 255, 255)
RED = (255, 0, 0)

def terminate():
    pygame.quit()
    sys.exit()

def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE: # pressing escape quits
                    terminate()
                if event.key == K_RETURN:
                    return

def playerHasHitZombie(playerRect, zombies):
    for z in zombies:
        if playerRect.colliderect(z[‘rect‘]):
            return True
    return False

def bulletHasHitZombie(bullets, zombies):
    for b in bullets:
        if b[‘rect‘].colliderect(z[‘rect‘]):
            bullets.remove(b)
            return True
    return False

def bulletHasHitCrawler(bullets, newKindZombies):
    for b in bullets:
        if b[‘rect‘].colliderect(c[‘rect‘]):
            bullets.remove(b)
            return True
    return False

def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))#, pygame.FULLSCREEN)
pygame.display.set_caption(‘Zombie Defence‘)
pygame.mouse.set_visible(False)

# set up fonts
font = pygame.font.SysFont(None, 48)

# set up sounds
gameOverSound = pygame.mixer.Sound(‘gameover.wav‘)
pygame.mixer.music.load(‘grasswalk.mp3‘)

# set up images
playerImage = pygame.image.load(‘SnowPea.gif‘)
playerRect = playerImage.get_rect()

bulletImage = pygame.image.load(‘SnowPeashooterBullet.gif‘)
bulletRect = bulletImage.get_rect()

zombieImage = pygame.image.load(‘tree.png‘)
newKindZombieImage = pygame.image.load(‘ConeheadZombieAttack.gif‘)

backgroundImage = pygame.image.load(‘background.png‘)
rescaledBackground = pygame.transform.scale(backgroundImage, (WINDOWWIDTH, WINDOWHEIGHT))

# show the "Start" screen
windowSurface.blit(rescaledBackground, (0, 0))
windowSurface.blit(playerImage, (WINDOWWIDTH / 2, WINDOWHEIGHT - 70))
drawText(‘Zombie Defence By handsomestone‘, font, windowSurface, (WINDOWWIDTH / 4), (WINDOWHEIGHT / 4))
drawText(‘Press Enter to start‘, font, windowSurface, (WINDOWWIDTH / 3) - 10, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
while True:
    # set up the start of the game

    zombies = []
    newKindZombies = []
    bullets = []

    zombiesGottenPast = 0
    score = 0

    playerRect.topleft = (50, WINDOWHEIGHT /2)
    moveLeft = moveRight = False
    moveUp=moveDown = False
    shoot = False

    zombieAddCounter = 0
    newKindZombieAddCounter = 0
    bulletAddCounter = 40
    pygame.mixer.music.play(-1, 0.0)

    while True: # the game loop runs while the game part is playing
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()

            if event.type == KEYDOWN:
                if event.key == K_UP or event.key == ord(‘w‘):
                    moveDown = False
                    moveUp = True
                if event.key == K_DOWN or event.key == ord(‘s‘):
                    moveUp = False
                    moveDown = True

                if event.key == K_SPACE:
                    shoot = True

            if event.type == KEYUP:
                if event.key == K_ESCAPE:
                        terminate()

                if event.key == K_UP or event.key == ord(‘w‘):
                    moveUp = False
                if event.key == K_DOWN or event.key == ord(‘s‘):
                    moveDown = False

                if event.key == K_SPACE:
                    shoot = False

        # Add new zombies at the top of the screen, if needed.
        zombieAddCounter += 1
        if zombieAddCounter == ADDNEWKINDZOMBIE:
            zombieAddCounter = 0
            zombieSize = ZOMBIESIZE
            newZombie = {‘rect‘: pygame.Rect(WINDOWWIDTH, random.randint(10,WINDOWHEIGHT-zombieSize-10), zombieSize, zombieSize),
                        ‘surface‘:pygame.transform.scale(zombieImage, (zombieSize, zombieSize)),
                        }

            zombies.append(newZombie)

        # Add new newKindZombies at the top of the screen, if needed.
        newKindZombieAddCounter += 1
        if newKindZombieAddCounter == ADDNEWZOMBIERATE:
            newKindZombieAddCounter = 0
            newKindZombiesize = ZOMBIESIZE
            newCrawler = {‘rect‘: pygame.Rect(WINDOWWIDTH, random.randint(10,WINDOWHEIGHT-newKindZombiesize-10), newKindZombiesize, newKindZombiesize),
                        ‘surface‘:pygame.transform.scale(newKindZombieImage, (newKindZombiesize, newKindZombiesize)),
                        }
            newKindZombies.append(newCrawler)

        # add new bullet
        bulletAddCounter += 1
        if bulletAddCounter >= ADDNEWBULLETRATE and shoot == True:
            bulletAddCounter = 0
            newBullet = {‘rect‘:pygame.Rect(playerRect.centerx+10, playerRect.centery-25, bulletRect.width, bulletRect.height),
						 ‘surface‘:pygame.transform.scale(bulletImage, (bulletRect.width, bulletRect.height)),
						}
            bullets.append(newBullet)

        # Move the player around.
        if moveUp and playerRect.top > 30:
            playerRect.move_ip(0,-1 * PLAYERMOVERATE)
        if moveDown and playerRect.bottom < WINDOWHEIGHT-10:
            playerRect.move_ip(0,PLAYERMOVERATE)

        # Move the zombies down.
        for z in zombies:
            z[‘rect‘].move_ip(-1*NORMALZOMBIESPEED, 0)

        # Move the newKindZombies down.
        for c in newKindZombies:
            c[‘rect‘].move_ip(-1*NEWKINDZOMBIESPEED,0)

        # move the bullet
        for b in bullets:
            b[‘rect‘].move_ip(1 * BULLETSPEED, 0)

        # Delete zombies that have fallen past the bottom.
        for z in zombies[:]:
            if z[‘rect‘].left < 0:
                zombies.remove(z)
                zombiesGottenPast += 1

        # Delete newKindZombies that have fallen past the bottom.
        for c in newKindZombies[:]:
            if c[‘rect‘].left <0:
                newKindZombies.remove(c)
                zombiesGottenPast += 1

		for b in bullets[:]:
			if b[‘rect‘].right>WINDOWWIDTH:
				bullets.remove(b)

        # check if the bullet has hit the zombie
        for z in zombies:
            if bulletHasHitZombie(bullets, zombies):
                score += 1
                zombies.remove(z)

        for c in newKindZombies:
            if bulletHasHitCrawler(bullets, newKindZombies):
                score += 1
                newKindZombies.remove(c)      

        # Draw the game world on the window.
        windowSurface.blit(rescaledBackground, (0, 0))

        # Draw the player‘s rectangle, rails
        windowSurface.blit(playerImage, playerRect)

        # Draw each baddie
        for z in zombies:
            windowSurface.blit(z[‘surface‘], z[‘rect‘])

        for c in newKindZombies:
            windowSurface.blit(c[‘surface‘], c[‘rect‘])

        # draw each bullet
        for b in bullets:
            windowSurface.blit(b[‘surface‘], b[‘rect‘])

        # Draw the score and how many zombies got past
        drawText(‘zombies gotten past: %s‘ % (zombiesGottenPast), font, windowSurface, 10, 20)
        drawText(‘score: %s‘ % (score), font, windowSurface, 10, 50)

        # update the display
        pygame.display.update()

        # Check if any of the zombies has hit the player.
        if playerHasHitZombie(playerRect, zombies):
            break
        if playerHasHitZombie(playerRect, newKindZombies):
           break

        # check if score is over MAXGOTTENPASS which means game over
        if zombiesGottenPast >= MAXGOTTENPASS:
            break

        mainClock.tick(FPS)

    # Stop the game and show the "Game Over" screen.
    pygame.mixer.music.stop()
    gameOverSound.play()
    time.sleep(1)
    if zombiesGottenPast >= MAXGOTTENPASS:
        windowSurface.blit(rescaledBackground, (0, 0))
        windowSurface.blit(playerImage, (WINDOWWIDTH / 2, WINDOWHEIGHT - 70))
        drawText(‘score: %s‘ % (score), font, windowSurface, 10, 30)
        drawText(‘GAME OVER‘, font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
        drawText(‘YOUR COUNTRY HAS BEEN DESTROIED‘, font, windowSurface, (WINDOWWIDTH / 4)- 80, (WINDOWHEIGHT / 3) + 100)
        drawText(‘Press enter to play again or escape to exit‘, font, windowSurface, (WINDOWWIDTH / 4) - 80, (WINDOWHEIGHT / 3) + 150)
        pygame.display.update()
        waitForPlayerToPressKey()
    if playerHasHitZombie(playerRect, zombies):
        windowSurface.blit(rescaledBackground, (0, 0))
        windowSurface.blit(playerImage, (WINDOWWIDTH / 2, WINDOWHEIGHT - 70))
        drawText(‘score: %s‘ % (score), font, windowSurface, 10, 30)
        drawText(‘GAME OVER‘, font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
        drawText(‘YOU HAVE BEEN KISSED BY THE ZOMMBIE‘, font, windowSurface, (WINDOWWIDTH / 4) - 80, (WINDOWHEIGHT / 3) +100)
        drawText(‘Press enter to play again or escape to exit‘, font, windowSurface, (WINDOWWIDTH / 4) - 80, (WINDOWHEIGHT / 3) + 150)
        pygame.display.update()
        waitForPlayerToPressKey()
    gameOverSound.stop()  

最后畅玩游戏,啊啊啊僵尸太多了,我们要把僵尸参数设置少一些。。

Python入门基础(2K分辨率超清,免费,博主录制)

https://study.163.com/course/courseMain.htm?courseId=1006183019&share=2&shareId=400000000398149

原文地址:https://www.cnblogs.com/webRobot/p/9824230.html

时间: 2024-10-16 21:00:37

Python菜鸟快乐游戏编程_pygame(5)的相关文章

【python游戏编程之旅】第一篇---初识pygame

本系列博客介绍以python+pygame库进行小游戏的开发.有写的不对之处还望各位海涵. 参考书籍:<python游戏编程入门> 一.pygame简介 Pygame 是一组用来开发游戏软件的 Python 程序模块,基于 SDL 库的基础上开发.允许你在 Python 程序中创建功能丰富的游戏和多媒体程序,Pygame 是一个高可移植性的模块可以支持多个操作系统.用它来开发小游戏非常适合. 可以去http://www.pygame.org/hifi.html 下载并安装使用pygame. 二

python游戏编程——跟13岁儿童学编程

python爬虫基本告一段落,琢磨搞点其他的,正好在网上看到一个帖子,一个外国13岁小朋友用python写的下棋程序,内容详细,也有意思,拿来练手. 13岁啊.. 我这年纪还在敲 dir啥的吧 想到原先玩跑跑卡丁车时看到欧酷有个4岁熊孩子玩的完美漂移录像,深受打击,从此退出车坛... 废话不多说,记录一下这几天的游戏编程折腾史 原帖: http://blog.jobbole.com/80379/    <13岁Python开发者写给青少年的Python入门教程> 游戏规则:6*6的方格棋盘,两

Pygame - Python游戏编程入门(2)

前言 前几天我们做出了一个可控制的飞机,今天我们来做一些小改进,这是代码的一些小改进,却是我们小游戏的一大改进啊~(╯°口°)╯(┴—┴ 然后再引进另外一个主题,pygame.sprite,精灵模块,那它究竟又有什么用呢? 正片开始~ 1. 对主循环的优化 记得我们的上一个版本吗?我们在主循环中不断地绘制背景和飞机,这样的做法其实很消耗cpu资源的,但在这种现象在我们的demo中并不明显,这是为什么呢?我想主要原因应该是我们使用了update()函数(部分刷新,surface与surface之间

分享《Python 游戏编程快速上手(第3版)》高清中文版PDF+高清英文版PDF+源代码

下载:https://pan.baidu.com/s/1n4hyQq1YFkuLiL2G3388fw 更多资料分享:http://blog.51cto.com/3215120 <Python 游戏编程快速上手(第3版)>高清中文版PDF+高清英文版PDF+源代码高清中文版,带目录和书签,文字能够复制粘贴图.高清英文版,带目录和书签,文字能够复制粘贴.中英文两版对比学习.配套源代码.经典书籍,讲解详细. 其中,高清中文版如图: 原文地址:http://blog.51cto.com/3215120

最大的幻术-游戏开发-到底是先学游戏引擎还是先学游戏编程

学习游戏的目的 我们学习游戏制作,游戏开发,游戏编程,游戏XX,我们的目的只有一个,打造一个非常牛逼,非常屌,非常让人开心的虚拟体验.我们用自己的学识让玩家在虚拟世界征战,生活,一步一步的让玩家幸福!那么我们的目的只有一个,让玩家知道自己的幸福在哪里,并且学会追求自己的幸福.当然,每个人对幸福的定义不一样.那么,我们只好让玩家来体验我们所来表达的最通俗的,最普遍的幸福体验,然后慢慢引导玩家去寻找自己的幸福体验.可能,在最后玩家都会离开游戏,离开虚拟世界,(对,这是真的,玩家需要一步一步达到定点,

12岁的少年教你用Python做小游戏

原地址:http://blog.jobbole.com/46308/ 本文由 伯乐在线 - 贱圣OMG 翻译自 Julian Meyer.欢迎加入技术翻译小组.转载请参见文章末尾处的要求. [感谢@贱圣OMG 的热心翻译.如果其他朋友也有不错的原创或译文,可以尝试推荐给伯乐在线.] 你有没有想过电脑游戏是怎样制作出来的?其实它没有你想象的那样复杂! 在这个教程里,你要学做一个叫<兔子和獾>的塔防游戏,兔子作为英雄,需要在城堡里抵御獾的进攻. 为了写这个游戏的代码,你将会用Python.好吧,我

Python菜鸟之路:Django 路由补充FBV和CBV

在Python菜鸟之路:Django 路由.模板.Model(ORM)一节中,已经介绍了几种路由的写法及对应关系,那种写法可以称之为FBV: function base view . 今天补充另外一种路由关系的写法:CBV,即:class base view , 也可以看做为面向资源编程的另外一种叫法,类似tornado中的路由写法. 1. 建立路由关系urls.py from app01 import views urlpatterns = [ url(r'^home/', views.Hom

Day6 - Python基础6 面向对象编程

Python之路,Day6 - 面向对象学习 本节内容: 面向对象编程介绍 为什么要用面向对象进行开发? 面向对象的特性:封装.继承.多态 类.方法. 引子 你现在是一家游戏公司的开发人员,现在需要你开发一款叫做<人狗大战>的游戏,你就思考呀,人狗作战,那至少需要2个角色,一个是人, 一个是狗,且人和狗都有不同的技能,比如人拿棍打狗, 狗可以咬人,怎么描述这种不同的角色和他们的功能呢? 你搜罗了自己掌握的所有技能,写出了下面的代码来描述这两个角色 1 2 3 4 5 6 7 8 9 10 11

PC游戏编程(入门篇)(前言写的很不错)

PC游戏编程(入门篇) 第一章 基石 1. 1 BOSS登场--GAF简介 第二章 2D图形程式初体验 2.l 饮水思源--第一个"游戏"程式 2.2 知其所以然一一2D图形学基础 2.3 进入图形世界的钥匙--GAFDDraw 2.4 2D图像的本质--图层表面 2.5 场景的秘密--背景卷动 2.6 诱惑--来自"精灵"的问候 2.7 餐后甜点--GAFApp/GAFDDraw的其他法宝 第三章 塞壬的歌声魔力和第三类接触 3.1 1,2,3--计算机音乐概述