python小游戏实现代码

python小游戏实现代码早上逛CSDN首页就见到这么一篇教程。看了一下很有意思,就马上动手实现了一下。看看效果吧:完整代码:#-*-coding:utf-8-*-#1-Importlibraryimport

大家好,又见面了,我是你们的朋友全栈君。

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

<span role="heading" aria-level="2">python小游戏实现代码

<span role="heading" aria-level="2">python小游戏实现代码

完整代码:

 

# -*- 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做的,我的系统默认安装的就是这个版本,我也就没有改了。

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/156012.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • mysql数据库备份和还原的命令_Mysql数据库备份和还原常用的命令

    mysql数据库备份和还原的命令_Mysql数据库备份和还原常用的命令Mysql数据库备份和还原常用的命令是进行Mysql数据库备份和还原的关键,没有命令,什么都无从做起,更谈不上什么备份还原,只有给系统这个命令,让它去执行,才能完成Mysql数据库备份和还原的操作,下面就是操作的常用命令。一、备份命令1、备份MySQL数据库的命令mysqldump-hhostname-uusername-ppassworddatabasename>backupf…

    2022年5月4日
    56
  • android 触屏处理流程,android触摸事件处理流程 ? FOOKWOOD「建议收藏」

    android 触屏处理流程,android触摸事件处理流程 ? FOOKWOOD「建议收藏」最近在工作中,经常需要处理触摸事件,但是有时候会出现一些奇怪的bug,比如有时候会检测不到ACTION_MOVE和ACTION_UP,我决定下决心写个测试的小程序,来研究一个触摸事件从上往下是怎么传递和处理的。先说下大概的流程吧,这个应该在很多博客中都有讲解:当一个事件来临的时候,会先传递给最外层的ViewGroup(比如LinearLayout,FrameLayout),如果这个ViewGrou…

    2025年10月24日
    6
  • 前端框架AdminLTE

    前端框架AdminLTE作为CMDB资产管理项目,必须有一个丰富、直观、酷炫的前端页面。适合运维平台的前端框架有很多,开源的也不少,这里选用的是AdminLTE。AdminLTE托管在GitHub上,可以通过下面的地址下载:https://github.com/almasaeed2010/AdminLTE/releasesAdminLTE自带JQuery和Bootstrap3框架,无需另外下载。AdminLTE自带多种配…

    2022年7月27日
    17
  • 自定义web接收推送_Java Web

    自定义web接收推送_Java Webhttps://www.webjars.org/提供了很多js的jar,但是有时候有些js没有,我们也想打成jar,那怎么办?我们以jquery3.4.1版本为例子开始1.创建如下结构pom文件内容如下:<?xmlversion=”1.0″encoding=”UTF-8″?><projectxmlns=”http://maven.apache….

    2025年7月10日
    3
  • 复杂json转MAP对象

    复杂json转MAP对象普通json对象或者字符串转换map或者实体就不说了,这里主要提供复杂json转map的方法,直接上java代码了:publicclassJsonUtils{ /** *类描述:复杂json字符串转换为Map,包含数组时value为List。 */ publicstaticMapjson2Map(Stringjson){ LinkedMap

    2022年6月16日
    24
  • python 股票数据接口(深市股票什么开头)

    根据上交所2017年5月公告的文件显示,拿到L1普通行情数据授权的有112家公司,L2授权的有25家,我这里只贴出L2数据的厂家,如果想看L1的授权公司或者深交所的授权情况可以自己去查,太多了就不贴了。1.上海大智慧股份有限公司2.深圳巨灵信息技术有限公司3.浙江核新同花顺网络信息股份有限公司4.北京指南针科技发展股份有限公司5.鼎信汇金(北京)投资管理有限公司6.上海乾隆高科技有限公…

    2022年4月13日
    77

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号