我的第一个Python项目--你好兔子

本文记录了一位12岁少年初次尝试Python编程的过程,通过制作小游戏"你好,兔子"来学习Python。首先介绍了所需的开发环境(Python 3.7 和 Pygame)以及开发工具(Xcode)。接着,虽然遇到了素材下载的问题,但作者通过搜索替代资源克服困难。在编程阶段,按照教程进行,发现并解决了关于时间显示的bug。最后,分享了完整的项目代码,鼓励大家动手实践。
摘要由CSDN通过智能技术生成

不知道Python能做什么,看基础语法没动力,找项目玩一玩了解下Python能做什么
12岁的少年教你用Python做小游戏
好吧,就从这个开始。

看看需要准备什么

  • 1、开发环境
1、需要Python 2.7
2、需要pygame 模块

2.7就算了,刚装好的3.7,应该差不多
继续安装pygame
Mac 安装Pygame小记
pip install pygame
OK,安装好了,继续看代码。

  • 2、然后是开发工具

使用Xcode编写并运行Python
环境搭配好了,工具准备好了,可以开始coding了。

素材

作者准备好了素材文件,然后,没有下载链接。。。
去文章最下面看看源码吧,这种文章应该都会有源码链接的。OK,果然有源码链接,点击下载。等待下载。等待下载。等待下载。。。打不开。。。

既然决定做一件事,那就要坚持做下去,不能因为一点点小挫折就放弃,图片百度搜一下代替了,音频百度下找一找,目的是写代码。
OK,继续看代码。
素材原网页可以下
原文链接
素材下载
准备完毕

编程

1、你好,兔子

# 1、导入pygame库
import pygame
from pygame.locals import *

# 2、初始化pygame,设置展示窗口
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))

# 3、加载作为兔子的图片
player = pygame.image.load("resources/images/dude.png")

# 4、循环执行接下来的部分
while 1:
    # 5、在给屏幕画任何东西之前用黑色进行填充
    screen.fill(0)
    # 6、在屏幕的(100,100)坐标出添加你加载的兔子图片
    screen.blit(player, (100, 100))
    # 7、更新屏幕
    pygame.display.flip()
    # 8、检查一些新的事件,如果有退出命令,则终止程序的执行。
    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)

你好,兔子
good,第一步已经成功了,继续。

coding…

按照步骤做下来都很顺利,显示时间的时候有些问题

原文

# 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))

修改

# 6.4 - 游戏时间
    font = pygame.font.Font(None, 24)
    survivedtext = font.render(str(int((90000-pygame.time.get_ticks())/60000))+":"+str(int((90000-pygame.time.get_ticks())/1000%60)).zfill(2), True, (0,0,0))

时间为90秒(1:30)倒计时,pygame.time.get_ticks()这个函数获取的是游戏开始到现在经历的毫秒数,按照原文计算(90000-pygame.time.get_ticks())/60000得到的是浮点型,可能2.7版本Python显示的是整数吧,所以这里要调用int()函数转为int。显示就正常了。

最后,去享受自己的成果,守护你的家园吧。
end
贴一份完整代码。

# 1、导入pygame库
import random
import math
import pygame
from pygame.locals import *

# 2、初始化pygame,设置展示窗口
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
keys = [False, False, False, False] # 按键,移动
playerpos = [100, 100]
acc = [0, 0] # 射出的箭头数和被击中的獾的数量
arrows = [] # 跟踪所有的箭头,更新它们,旋转它们,在它们跑出屏幕的时候删除它们。
badtimer = 100 #
badtimer1 = 0
badguys = [[640, 100]]
healthvalue = 194 # 城堡血量

pygame.mixer.init()


# 3、加载作为兔子的图片
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")
badguyimg = badguyimg1
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")
# 3.1 - 加载音乐
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、循环执行接下来的部分
running = 1
exitcode = 0
while running:
    badtimer -= 1
    # 5、在给屏幕画任何东西之前用黑色进行填充
    screen.fill(0)
    # 添加草地背景
    for x in range(int(width/grass.get_width())+1):
        for y in range(int(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))
    # 6.1、在屏幕的(100,100)坐标出添加你加载的兔子图片
    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、画箭头
    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 敌人
    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:
        if badguy[0] < -64:
            badguys.pop(index)
        badguy[0] -= 7
        # 6.3.1 - 獾攻击城堡
        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 - 检查碰撞
        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
        
        index += 1
    for badguy in badguys:
        screen.blit(badguyimg, badguy)
    # 6.4 - 游戏时间
    font = pygame.font.Font(None, 24)
    survivedtext = font.render(str(int((90000-pygame.time.get_ticks())/60000))+":"+str(int((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 - 生命值
    screen.blit(healthbar, (5, 5))
    for health1 in range(healthvalue):
        screen.blit(health, (health1 + 8, 8))
    # 7、更新屏幕
    pygame.display.flip()
    # 8、检查一些新的事件,如果有退出命令,则终止程序的执行。
    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 == K_w:
                keys[0] = False
            elif event.key == K_a:
                keys[1] = False
            elif event.key == K_s:
                keys[2] = False
            elif event.key == 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、移动玩家
    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、判断输赢
    if pygame.time.get_ticks() >= 90000:
        running = 0
        exitcode = 1
    if healthvalue <= 1:
        running = 0
        exitcode = 0
    if acc[1] != 0:
        accuracy = acc[0]*1.0/acc[1]*100
    else:
        accuracy = 0
# 11、展示结束画面
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, (255,0,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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值