早上逛CSDN首页就见到这么一篇教程。看了一下很有意思,就马上动手实现了一下。看看效果吧:

完整代码:

# -*- coding: utf-8 -*-
# 1 - Import library
import pygame
from pygame.locals import *
import math
import random
# 2 - Initialize the game
keys = [False, False, False, False]
playerpos=[100,100]
acc=[0,0]
arrows=[]
badtimer=100
badtimer1=0
badguys=[[640,100]]
healthvalue=194
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height)) pygame.mixer.init() # 3 - Load images
player = pygame.image.load("resources/images/dude.png")
grass = pygame.image.load("resources/images/grass.png")
castle = pygame.image.load("resources/images/castle.png")
arrow = pygame.image.load("resources/images/bullet.png")
badguyimg1 = pygame.image.load("resources/images/badguy.png")
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
badguyimg=badguyimg1
# 3.1 - Load audio
hit = pygame.mixer.Sound("resources/audio/explode.wav")
enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('resources/audio/moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
# 4 - keep looping through
running = 1
exitcode = 0
while running:
badtimer-=1
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the screen elements for x in range(width/grass.get_width()+1):
for y in range(height/grass.get_height()+1):
screen.blit(grass,(x*100,y*100))
screen.blit(castle,(0,30))
screen.blit(castle,(0,135))
screen.blit(castle,(0,240))
screen.blit(castle,(0,345 ))
#screen.blit(player, (100,100))
#screen.blit(player, playerpos)
position = pygame.mouse.get_pos()
angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26))
playerrot = pygame.transform.rotate(player, 360-angle*57.29)
playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
screen.blit(playerrot, playerpos1)
# 6.2 - Draw arrows
for bullet in arrows:
index=0
velx=math.cos(bullet[0])*10
vely=math.sin(bullet[0])*10
bullet[1]+=velx
bullet[2]+=vely
if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:
arrows.pop(index)
index+=1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - Draw badgers
if badtimer==0:
badguys.append([640, random.randint(50,430)])
badtimer=100-(badtimer1*2)
if badtimer1>=35:
badtimer1=35
else:
badtimer1+=5
index=0
for badguy in badguys:
# 6.3.1 - Attack castle badrect=pygame.Rect(badguyimg.get_rect())
badrect.top=badguy[1]
badrect.left=badguy[0]
if badrect.left<64:
hit.play()
healthvalue -= random.randint(5,20)
badguys.pop(index)
#6.3.2 - Check for collisions index1=0
for bullet in arrows:
bullrect=pygame.Rect(arrow.get_rect())
bullrect.left=bullet[1]
bullrect.top=bullet[2]
if badrect.colliderect(bullrect):
enemy.play()
acc[0]+=1
badguys.pop(index)
arrows.pop(index1)
index1+=1
# 6.3.3 - Next bad guy
if badguy[0]<-64:
badguys.pop(index)
badguy[0]-=7
index+=1
for badguy in badguys:
screen.blit(badguyimg, badguy)
# 6.4 - Draw clock font = pygame.font.Font(None, 24)
survivedtext = font.render(str((90000-pygame.time.get_ticks())/60000)+":"+str((90000-pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect()
textRect.topright=[635,5]
screen.blit(survivedtext, textRect) # 6.5 - Draw health bar
screen.blit(healthbar, (5,5))
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
elif event.key==K_a:
keys[1]=True
elif event.key==K_s:
keys[2]=True
elif event.key==K_d:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
keys[0]=False
elif event.key==pygame.K_a:
keys[1]=False
elif event.key==pygame.K_s:
keys[2]=False
elif event.key==pygame.K_d:
keys[3]=False
if event.type==pygame.MOUSEBUTTONDOWN:
shoot.play()
position=pygame.mouse.get_pos()
acc[1]+=1
arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])
# 9 - Move player
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5
#10 - Win/Lose check
if pygame.time.get_ticks()>=90000:
running=0
exitcode=1
if healthvalue<=0:
running=0
exitcode=0
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
# 11 - Win/lose display
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.flip()

运行成功的时候有点小激动,不等不感叹,国外一个13岁的小孩都这么给力,让我情何以堪?

原文地址:点击打开链接

译文地址:点击打开链接

我是看着原文实现的代码,因为译文里面有些地方有问题,游戏资源的下载连接也没给,原文里面有。

由于pygame的首页上不去没法上它的官网下载模块,ubuntu下其实很方便,一个命令就搞定了:

sudo apt-get install python-pygame

这个游戏是用的python2.7.3做的,我的系统默认安装的就是这个版本,我也就没有改了。

python小游戏实现代码的更多相关文章

  1. Python小游戏、小程序

    python 小游戏之摇骰子猜大小 python 实现一个双色球生成程序 python-循环与判断练习题

  2. Python 小游戏 Bunny

    最近在学习Python,所以上网找了一个小程序练练手. 关于这款名为[Bunny]的小游戏,详细请看下面的链接: http://www.oschina.net/translate/beginning- ...

  3. 玩Python小游戏猜数字,在游戏中掌握基础,你还能学不会?

    学python怎么离得开案例呢? 今天再继续给大家分享一个Python教程里的猜数字游戏     我最近也是在学python,从事编程工作几年了,但是python还是今年才开始玩的,不得不说,这真是一 ...

  4. Python小游戏 -- 猜单词

    Python初学者小游戏:猜单词 游戏逻辑:就像我们曾经英语学习机上的小游戏一样,电脑会从事先预置的词库中抽取单词,然后给出单词的字母数量,给定猜解次数,然后让玩家进行猜测,并给出每次猜测的正确字母与 ...

  5. Python小游戏 -- 猜数字

    Python初学者小游戏:猜数字 游戏逻辑:电脑随机生成一个数字,然后玩家猜数字,电脑提示猜的数字大了还是小了,供玩家缩小数字范围,达到既定次数后,玩家失败.若在次数内猜对,玩家获胜. 涉及知识点:r ...

  6. Python小游戏——外星人入侵(保姆级教程)第一章 07调整飞船速度 08限制飞船活动范围

    系列文章目录 第一章:武装飞船 07调整飞船速度 08限制飞船活动范围 一.代码及演示 1.修改settings 修改文件:settings.py 点击查看代码 #渗透小红帽python的学习之路 # ...

  7. Python小游戏——外星人入侵(保姆级教程)第一章 06让飞船移动

    系列文章目录 第一章:武装飞船 06:让飞船移动 一.驾驶飞船 下面来让玩家能够左右移动飞船.我们将编写代码,在用户按左或右箭头键时做出响应.我们将首先专注于向右移动,再使用同样的原理来控制向左移动. ...

  8. Python小游戏——外星人入侵(保姆级教程)第一章 05重构模块game_functions

    系列文章目录 第一章:武装飞船 05:重构:模块game_functions 一.重构 在大型项目中,经常需要在添加新代码前重构既有代码.重构旨在简化既有代码的结构,使其更容易扩展.在本节中,我们将创 ...

  9. Python小游戏——外星人入侵(保姆级教程)第一章 03设置飞船图片 04创建Ship类

    系列文章目录 第一章:武装飞船 03:设置飞船图片 04:创建Ship类--管理飞船行为的类 一.设置飞船图片 1.注意事项 A.将图片设置为位图bmp格式最简单,因为pygame默认加载位图 B.飞 ...

随机推荐

  1. codinglife主题小修改和有意思的博客挂件

    这个主题很漂亮,不过为了迎合自己的喜好ヽ(•̀ω•́ )ゝ,修改了字号.阴影之类的小细节.同时下面还有我博客里面的两个有意思的小挂件,请向右边看(๑و•̀ω•́)و 1.主题修改:复制下面的css代码 ...

  2. Notepad++使用技法

    Alt+H 隐藏行 Ctrl+Tab  实现在多个打开的窗口间切换 Ctrl+Shift+Q区块注释 Ctrl+K行注释(取消Ctrl+Shift+K) 文件  新建文件 Ctrl+N  打开文件 C ...

  3. [转] jQuery 操作 JSON 数据

    jquery下json数组的操作用法实例: jquery中操作JSON数组的情况中遍历方法用的比较多,但用添加移除这些好像就不是太多了. 试过json[i].remove(),json.remove( ...

  4. Class类对象的三种实例化方法

    class X { } public class GetClassDemo01 {     public static void main(String[] args) {         X x = ...

  5. Spring集成Quartz定时器

    <!-- Spring集成Quartz开始 --> <bean id="startQuertz" lazy-init="false" auto ...

  6. .net mvc笔记2_Essential C# Features

    Essential C# Features 1.Using Automatically Implemented Properties public class Product { private st ...

  7. discuz门户文章页面模板修改

    修改内容:view.htm 1.文章标题,模板代码 <h1 class="ph">$article[title] <!--{if $article['status ...

  8. JAVA异常设计原则

    异常是面向对象语言非常重要的一个特性,良好的异常设计对程序的可扩展性.可维护性.健壮性都起到至关重要. JAVA根据用处的不同,定义了两类异常     * Checked Exception: Exc ...

  9. iOS开发获取缓存文件的大小并清除缓存

    移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage. 但是,离线缓存会占用手机存储空间,所以缓存清理功能基本成为资讯.购物.阅读类 ...

  10. Java经典问题算法大全

    /*[程序1] 题目:古典问题:有一对兔子.从出生后第3个月起每一个月都生一对兔子.小兔子长到第三个月后每一个月又生一对兔子,假如兔子都不死.问每一个月的兔子总数为多少?  1.程序分析: 兔子的规律 ...