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 = 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()  

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

https://study.163.com/provider/400000000398149/index.htm?share=2&shareId=400000000398149(博主视频教学主页)

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

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

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

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

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

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

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

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

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

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

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

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

    python爬虫基本告一段落,琢磨搞点其他的,正好在网上看到一个帖子,一个外国13岁小朋友用python写的下棋程序,内容详细,也有意思,拿来练手. 13岁啊.. 我这年纪还在敲 dir啥的吧 想到原 ...

  7. Python游戏编程入门

    <Python游戏编程入门>这些文章负责整理在这本书中的知识点.注意事项和课后习题的尝试实现.并且对每一个章节给出的最终实例进行分析和注释. 初识pygame:pie游戏pygame游戏库 ...

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

    通过编写一个个小巧.有趣的游戏来学习Python,通过实例来解释编程的原理的方式.14个游戏程序和示例,介绍了Python基础知识.数据类型.函数.流程控制.程序调试.流程图设计.字符串操作.列表和字 ...

  9. 《Python游戏编程快速上手》——1.3 如何使用本书

    本节书摘来自异步社区<Python游戏编程快速上手>一书中的第1章,第1.3节,作者[美] Al Sweigart(斯维加特),李强 译,更多章节内容可以访问云栖社区"异步社区& ...

随机推荐

  1. Android Interpolator解析

    本文部分图片转自:https://blog.csdn.net/lgaojiantong/article/details/39451243 目录 自定义插值器 系统插值器 1. 自定义插值器 要自定义插 ...

  2. MySQL随笔(1)

    mysql是一种关系型数据库,和SQL ,oracle一样是较为常用的关系型数据库,属于oracle旗下的产品,在web应用方面,MySQL是最好的RDBMS(relational database ...

  3. RAID5当一块硬盘离线后处理

    RAID5当一块硬盘离线后,处理降级状态,这时候正常的建议是马上更换硬盘做REBUILD以恢复完整的数据状态,如果有热备盘的话,就会自动做REBUILD,这样做合适吗? 一组RAID卷在工作很长时间以 ...

  4. 获取DataTable前几条数据

    #region 获取DataTable前几条数据 /// <summary> /// 获取DataTable前几条数据 /// </summary> /// <param ...

  5. Linux(二)—— Unix&Linux 的基本概念

    Linux(二)-- Unix&Linux 的基本概念 计算机 = 主机(host)+ 终端(terminal) 主机 = 内核 + 实用工具 内核(kernel) 当计算机启动时,计算机要经 ...

  6. Charles(V3.10.1)的抓包以及常见功能的使用

    一.Charles的安装 安装都不会,那就不用再往下看了.(*^__^*) 嘻嘻…… 二.HTTP抓包 1.查看电脑IP地址 2.设置手机的HTTP代理 手机连接到同一WiFi下设置HTTP代理: 服 ...

  7. Linux常用命令之Tmux

    Tmux是一个优秀的终端复用软件,类似GNU Screen,但来自于OpenBSD,采用BSD授权.使用它最直观的好处就是,通过一个终端登录远程主机并运行tmux后,在其中可以开启多个控制台而无需再“ ...

  8. 安装 VMware CentOS Xmanager Xshell

    1.CentOS下载CentOS是免费版,推荐在官网上直接下载,网址:https://www.centos.org/download/DVD ISO:普通光盘完整安装版镜像,可离线安装到计算机硬盘上, ...

  9. styled-components解决全局样式'injectGlobal' 废除的问题

    最新版的 styled-components v4 已经将原有的 injectGlobal() 方法替换成了 createGlobalStyle() ,而且用法也和之前的 injectGlobal 方 ...

  10. 转载泡泡机器人——IMU预积分总结与公式推导2

    本文为IMU预积分总结与公式推导系列技术报告的第二篇. 承接第一篇的内容,本篇将推导IMU预积分的测量值,并分析其测量误差的分布形式. 传统捷联惯性导航的递推算法,以初始状态为基础,利用IMU测量得到 ...