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
作者邮件:231469242@qq.com
作者微信公众号:PythonEducation
"""############################################################################################
###                                                                                      ###
###   PyGame with a SnowPea shoot bullet for defensing the zombie army coming            ###
###                                                                                      ###
###   Author: Junjie Shi                                                                 ###
###   Email : handsomestone@gmail.com                                                    ###
###                                                                                      ###
###   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 = 30MAXGOTTENPASS = 10
ZOMBIESIZE = 70 #includes newKindZombies
ADDNEWZOMBIERATE = 10
ADDNEWKINDZOMBIE = ADDNEWZOMBIERATENORMALZOMBIESPEED = 2
NEWKINDZOMBIESPEED = NORMALZOMBIESPEED / 2PLAYERMOVERATE = 15
BULLETSPEED = 10
ADDNEWBULLETRATE = 15TEXTCOLOR = (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 quitsterminate()if event.key == K_RETURN:returndef playerHasHitZombie(playerRect, zombies):for z in zombies:if playerRect.colliderect(z['rect']):return Truereturn Falsedef bulletHasHitZombie(bullets, zombies):for b in bullets:if b['rect'].colliderect(z['rect']):bullets.remove(b)return Truereturn Falsedef bulletHasHitCrawler(bullets, newKindZombies):for b in bullets:if b['rect'].colliderect(c['rect']):bullets.remove(b)return Truereturn Falsedef 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 gamezombies = []newKindZombies = []bullets = []zombiesGottenPast = 0score = 0playerRect.topleft = (50, WINDOWHEIGHT /2)moveLeft = moveRight = FalsemoveUp=moveDown = Falseshoot = FalsezombieAddCounter = 0newKindZombieAddCounter = 0bulletAddCounter = 40pygame.mixer.music.play(-1, 0.0)while True: # the game loop runs while the game part is playingfor 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 = FalsemoveUp = Trueif event.key == K_DOWN or event.key == ord('s'):moveUp = FalsemoveDown = Trueif event.key == K_SPACE:shoot = Trueif event.type == KEYUP:if event.key == K_ESCAPE:terminate()if event.key == K_UP or event.key == ord('w'):moveUp = Falseif event.key == K_DOWN or event.key == ord('s'):moveDown = Falseif event.key == K_SPACE:shoot = False# Add new zombies at the top of the screen, if needed.zombieAddCounter += 1if zombieAddCounter == ADDNEWKINDZOMBIE:zombieAddCounter = 0zombieSize = 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 += 1if newKindZombieAddCounter == ADDNEWZOMBIERATE:newKindZombieAddCounter = 0newKindZombiesize = ZOMBIESIZEnewCrawler = {'rect': pygame.Rect(WINDOWWIDTH, random.randint(10,WINDOWHEIGHT-newKindZombiesize-10), newKindZombiesize, newKindZombiesize),'surface':pygame.transform.scale(newKindZombieImage, (newKindZombiesize, newKindZombiesize)),}newKindZombies.append(newCrawler)# add new bulletbulletAddCounter += 1if bulletAddCounter >= ADDNEWBULLETRATE and shoot == True:bulletAddCounter = 0newBullet = {'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 bulletfor 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 += 1for b in bullets[:]:if b['rect'].right>WINDOWWIDTH:bullets.remove(b)# check if the bullet has hit the zombiefor z in zombies:if bulletHasHitZombie(bullets, zombies):score += 1zombies.remove(z)for c in newKindZombies:if bulletHasHitCrawler(bullets, newKindZombies):score += 1newKindZombies.remove(c)      # Draw the game world on the window.windowSurface.blit(rescaledBackground, (0, 0))# Draw the player's rectangle, railswindowSurface.blit(playerImage, playerRect)# Draw each baddiefor z in zombies:windowSurface.blit(z['surface'], z['rect'])for c in newKindZombies:windowSurface.blit(c['surface'], c['rect'])# draw each bulletfor b in bullets:windowSurface.blit(b['surface'], b['rect'])# Draw the score and how many zombies got pastdrawText('zombies gotten past: %s' % (zombiesGottenPast), font, windowSurface, 10, 20)drawText('score: %s' % (score), font, windowSurface, 10, 50)# update the displaypygame.display.update()# Check if any of the zombies has hit the player.if playerHasHitZombie(playerRect, zombies):breakif playerHasHitZombie(playerRect, newKindZombies):break# check if score is over MAXGOTTENPASS which means game overif zombiesGottenPast >= MAXGOTTENPASS:breakmainClock.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

Python菜鸟快乐游戏编程_pygame(5)相关推荐

  1. Python菜鸟快乐游戏编程_pygame(4)

    Python菜鸟快乐游戏编程_pygame(博主录制,2K分辨率,超高清) https://study.163.com/course/courseMain.htm?courseId=100618802 ...

  2. python游戏编程网课_Python菜鸟快乐游戏编程_pygame(1)

    作者Toby, 持牌照金融股份公司模型验证专家,国内最大医药数据中心担任过数据库负责人.擅长python 机器学习,应用于医疗,英语,金融风控领域. 课程介绍: 编程正在逐步改变世界,程序员不是搬砖的 ...

  3. 杠子老虎鸡虫 《python二维游戏编程》课后项目一

    <python二维游戏编程>项目一:杠子老虎鸡虫 V0.0.2.20210629 项目简介 <python二维游戏编程>课后项目1 适用于中国农业出版社,张太红主编,2015版 ...

  4. 编玩边学python助手_边玩游戏,边学Python,四大游戏编程网站

    点击蓝字"python教程"关注我们,一起学习成长哟! 前言 学习编程虽然对有些人来说是件乐事,但是对大多数人来说仍然是一件比较枯燥困难的事情.当然,面临这样困惑的人,并不是只有你 ...

  5. python大鱼吃小鱼_python 游戏编程 大鱼吃小鱼

    # 游戏编程:按照以下游戏编写一个乌龟类和鱼类,并尝试编写游戏. # 假设游戏场景(x,y)为0<=x<=10,0<=y<=10 # 游戏生成1只乌龟和10只鱼 # 他们的移动 ...

  6. python猜数字游戏编程、最后显示猜了几次_用Python完成猜数字游戏

    五一假期第一天突然想学点新东西,于是把Python重新捡起来.按照Crossin的编程教室中的<Python入门教程>写了一段代码,实现猜字游戏. !/usr/bin/python cod ...

  7. python猜数字游戏编程入门_如何利用Python开发一个简单的猜数字游戏

    导读热词 前言 本文介绍如何使用Python制作一个简单的猜数字游戏. 游戏规则 玩家将猜测一个数字.如果猜测是正确的,玩家赢.如果不正确,程序会提示玩家所猜的数字与实际数字相比是"大(hi ...

  8. python方向键控制角色_用python和pygame游戏编程入门-控制角色移动

    在上一节中我们知道了事件,以及如何捕捉键盘事件进行响应,本届我们结合第一节何上一节的内容,做一个用键盘控制角色移动的功能,代码如下: #!/usr/bin/env python #指定图像文件名称 b ...

  9. python猜数字游戏编程入门_Python实现猜数字游戏

    Python实现猜数字游戏 游戏规则: 随机产生1到100之间的整数 共有6次猜测机会,每次猜测如果不正确会提示大于或小于目标值,6次机会用完退出程序 6次机会,包含第6次机会如果猜中,提示用户猜中 ...

  10. python怎么窗口显示文字_用python和pygame游戏编程入门-显示文字

    上一节我们通过键盘可以控制角色移动,如果要让角色说话,那就要用到文字显示.Pygame可以直接调用系统字体,或者也可以使用TTF字体,TTF就是字体文件,可以从网上下载.为了使用字体,你得先创建一个F ...

最新文章

  1. 如何撰写好一篇论文?密歇根Andrew教授这篇《撰写高影响力论文指南》为你细致讲解论文写作,附视频与pdf...
  2. 十年后你用什么听音乐?
  3. 动画 Interpolator
  4. php方案报价单,综合布线设计方案,综合布线报价清单
  5. Npm如何升级package.json
  6. 《c语言从入门到精通》看书笔记——第3章 数据类型
  7. 前端学习(487):css选择器下
  8. (24)System Verilog设计十进制计数器
  9. [转载] 杜拉拉升职记——34 设定工作目标要符合“SMART”原则
  10. 0084-CYX的异己
  11. 金融+大数据解决方案:银行业
  12. ASCII码转HEX与HEX转ASCII码
  13. 2022考研数学一/二/三汤老师接力题典1800(解答册及题目册)pdf版
  14. [转帖]「白帽黑客成长记」Windows提权基本原理(上)
  15. XSepConv: Extremely Separated Convolution
  16. 尚硅谷Web前端ES6教程,涵盖ES6-ES11
  17. 利用sklearn.cluster实现k均值聚类
  18. 1.2 电流和电压的参考方向
  19. SNP/单核苷酸多态性分析
  20. Hungry Rabbit

热门文章

  1. /etc/init.d/functions详解
  2. 《C#高效编程》读书笔记11-理解短小方法的优势
  3. tomcat基础应用详解
  4. Riemann映射定理
  5. ASP.NET AJAX客户端编程之旅(一)——Hello!ASP.NET AJAX
  6. python怎么打印列表长度_零基础学python_08_列表(排序+反转+长度)
  7. 二叉树类图_设计模式前言——UML类图
  8. Unity 发射子弹的两种方式
  9. Mac vscode花屏问题解决
  10. 配置中心Nacos与Apollo比较