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)
上一篇 2022年7月5日 下午4:36
下一篇 2022年7月5日 下午4:36


相关推荐

  • MacBook安装telnet工具和使用

    MacBook安装telnet工具和使用MacBook 安装 telnet 工具和使用 telnet 安装使用 brew 工具安装 brewinstallt 工具使用 ping 命令是测试本机和远程机器的 ip 通不通 telnet 工具可以测试本机和远程机器的端口通不通 pingIP 为 192 168 3 2 通不通 ping192 168 3 2 测试 192 168 3 2 机器的 1883 端口是否通 telnet192 168 3 21883

    2026年3月18日
    3
  • Burp Suite修改响应包字段

    Burp Suite修改响应包字段抓到包之后设置Action:dointercept->responsetothisrequest点击Forward即可

    2022年5月10日
    74
  • C语言学生成绩管理系统设计 《C语言程序设计》实训报告[通俗易懂]

    C语言学生成绩管理系统设计 《C语言程序设计》实训报告[通俗易懂]一、课程设计题目《学生成绩管理系统设计》二、实训目的(1)掌握结构化程序设计的基本方法,基本掌握面向对象程序设计的基本思路和方法。(2)掌握C++的基本概念和基础知识。(3)通过训练能够读懂较为复杂的C++语言源程序并具备基本C++语言程序设计的能力。(4)通过实训,培养自己编写、调试、分析程序的能力。(5)培养自己独立解决问题,查找资料的能力。同学之间相互帮助,相互交流,相互合作的团队精神。(6)培养自己良好的学习兴趣,独立的编程风格。(7)通过实训检查自己学习上的

    2022年6月20日
    34
  • Keil MDK 2020过期问题[通俗易懂]

    Keil MDK 2020过期问题[通俗易懂]KeilMDK2020过期问题由于到2020年过期,之前曾担心到2020年是否我们用KEILMDK所编写的代码,全部不可用。经过今天测试,虽然软件提示过期,不过依然可以正常使用,只是没有软件的支持维护而已。用微信扫描二维码为博主打个赏金额随意快来“打”我呀要买枸杞当归补补~~转自:https://www.zhjm.site/wordpress/?p=340…

    2022年5月9日
    207
  • IDEA2018.2.1最新版本破解[通俗易懂]

    转载自:https://www.52pojie.cn/thread-781394-1-1.html再次换电脑,再次安装IDEA,之前的破解用不了,再次查找破解方法。1、把下载的破解补丁放在你的idea的安装目录下的bin的目录下面(如下图所示),本文示例为F:\ProgramFiles\JetBrains\IntelliJIDEA2018.2\bin\JetbrainsCrack-3….

    2022年4月17日
    57
  • mysql 设置外键约束SET FOREIGN_KEY_CHECKS=1

    mysql 设置外键约束SET FOREIGN_KEY_CHECKS=1

    2022年2月19日
    66

发表回复

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

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