python小游戏——兔鼠大战

一.准备环境:更改设置pip 国内镜像

在使用pycharm来制作小游戏写代码的时候需要编译环境,使用pip镜像源,由于pip管理工具安装库文件时,默认使用国外的源文件,因此在国内的下载速度会比较慢,可能只有50KB/s。幸好,国内的一些顶级科研机构已经给我们准备好了各种镜像,下载速度可达2MB/s。所以需要更改设置成pip国内镜像。

国内源:

新版ubuntu要求使用https源,要注意。

清华:https://pypi.tuna.tsinghua.edu.cn/simple

阿里云:http://mirrors.aliyun.com/pypi/simple/

中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/

华中理工大学:http://pypi.hustunique.com/

山东理工大学:http://pypi.sdutlinux.org/

豆瓣:http://pypi.douban.com/simple/

1. 临时使用

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple some-package

可以在使用pip的时候加参数-i https://pypi.tuna.tsinghua.edu.cn/simple

例如:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyspider,这样就会从清华这边的镜像去安装pyspider库。

2.默认使用

  windows系统使用cmd(命令指示符)快速设置
  1. pip install pip -U # 升级pip到最新版本
  2. pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

注:在命令指示符里依次敲以上代码,以上例子都是用的清华大学的镜像

二.进行代码的编写

# -*-conding: utf-8  -*-
#如果要在python2的py文件里面写中文,则必须要添加一行声明文件编码的注释,否则python2会默认使用ASCII编码。
#如果是python3及其以上的版本就可以不写第一行注释。
# 1 - Import library
import pygame        #import语句:在模块模块定义好后,我们可以使用 import 语句来引入模块
from pygame.locals import *# from 语句从模块中导入一个指定的部分到当前命名空间中
import math
import random# 2 - Initialize the game          #initialize (隐藏摘要) 预置(初始状态bai), 初始化这个游戏
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.display.set_caption("兔鼠大战")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 arrowsfor bullet in arrows:index = 0velx = math.cos(bullet[0]) * 10vely = math.sin(bullet[0]) * 10bullet[1] += velxbullet[2] += velyif bullet[1] < -64 or bullet[1] > 640 or bullet[2] < -64 or bullet[2] > 480:arrows.pop(index)index += 1for 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 = 35else:badtimer1 += 5index = 0for 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 = 0for 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] += 1badguys.pop(index)arrows.pop(index1)index1 += 1# 6.3.3 - Next bad guy 下一个老鼠if badguy[0] < -64:badguys.pop(index)badguy[0] -= 7index += 1for 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_UP:          # k_wkeys[0] = Trueelif event.key == K_LEFT:      # k_akeys[1] = Trueelif event.key == K_DOWN:      # k_skeys[2] = Trueelif event.key == K_RIGHT:     # k_dkeys[ 3 ] = True         #以上设置按键也可以设置成w,a,s,d  #后是对应的代码,如用这个下面也需要更换成相同的if event.type == pygame.KEYUP:if event.key == pygame.K_UP:   #这里跟上面的设置键需要设置成相同的keys[0] = Falseelif event.key == pygame.K_LEFT:keys[1] = Falseelif event.key == pygame.K_DOWN:keys[2] = Falseelif event.key == pygame.K_RIGHT:keys[3] = Falseif event.type == pygame.MOUSEBUTTONDOWN:shoot.play()position = pygame.mouse.get_pos()acc[1] += 1arrows.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] -= 5elif keys[2]:playerpos[1] += 5if keys[1]:playerpos[0] -= 5elif keys[3]:playerpos[0] += 5# 10 - Win/Lose check  检查是否赢得/输掉游戏if pygame.time.get_ticks() >= 90000:running = 0exitcode = 1if healthvalue <= 0:running = 0exitcode = 0if acc[1] != 0:accuracy = acc[0] * 1.0 / acc[1] * 100else: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().centerxtextRect.centery = screen.get_rect().centery + 24screen.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().centerxtextRect.centery = screen.get_rect().centery + 24screen.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()

成果显示如下

以上代码有参考其他博主的,相关素材及其音效也是通过公众号:Python代码大全获得。

具体资源的及其参考网址如下:
https://blog.csdn.net/weixin_42756970/article/details/106475154

新手小白制作,如有问题请各位大佬多多指教!阿里嘎多!

python小游戏——兔鼠大战相关推荐

  1. Python小游戏-坦克大战(tank war)

    Python小游戏-坦克大战(tank war) 前言 这款游戏一直都是我很喜欢的游戏,很童年,太经典啦!也很好玩,所以我来做一做这款游戏. 开发工具 python版本:3.7.3 相关模块:pyga ...

  2. 【Python】Python小游戏--飞机大战

    一.前言 今天已经初四,舒服的在家躺尸的春节也算过去了,又要开始辛勤的(苦逼的)学习和工作了.说点题外话,今年春节的病毒疫情真的弄的人心惶惶,我也在这为国家和武汉加油,也向一线工作人员致敬,希望早日结 ...

  3. python小游戏——飞机大战小游戏(附源码)

    写在前面的一些P话: 大家之前用python编写过飞机大战的部分代码, 只能够展示英雄飞机,背景,敌机和发射子弹, 今天把背景音乐,击毁敌机,爆炸特效,得分等等相关功能一并加入进来, 代码有点长,三百 ...

  4. python小游戏“植物大战僵尸”

    python讨论qq群:996113038 导语: 这几天一直写爬虫,感觉写累了.本来准备写一个画画的程序的,但是想来想去没有想到合适的程序.后来想到好久没有给大家推送过游戏了.上次推送游戏还是两个星 ...

  5. 小甲鱼python小游戏“飞机大战”源码素材

    话不多说,链接奉上. 百度网盘链接: https://pan.baidu.com/s/1KkmCqCBJ2Jq_IrewovYPAQ 提取码:43av 注:需下载Python pygame包 下载方式 ...

  6. Python小游戏(XO大战)

    源码分享: from tkinter import * import tkinter.messagebox as msgroot = Tk() root.title('TIC-TAC-TOE---Pr ...

  7. c 语言500行小游戏代码,500行代码使用python写个微信小游戏飞机大战游戏.pdf

    500行行代代码码使使用用python写写个个微微信信小小游游戏戏飞飞机机大大战战游游戏戏 这篇文章主要介绍了500行代码使用python写个微信小游戏飞机大战游戏,本文通过实例代码给大家介绍的非常详 ...

  8. python小游戏之三

    猜拳游戏 Python代码实现猜拳小游戏 Python代码实现猜拳小游戏_zhangtongyuan0909的博客-CSDN博客_python猜拳游戏代码 用python中类与对象写一个猜拳游戏 用p ...

  9. 边玩边学,13个 Python 小游戏真有趣啊(含源码)

    经常听到有朋友说,学习编程是一件非常枯燥无味的事情.其实,大家有没有认真想过,可能是我们的学习方法不对? 比方说,你有没有想过,可以通过打游戏来学编程? 今天我想跟大家分享几个Python小游戏,教你 ...

最新文章

  1. Seamless cloning泊松克隆
  2. 【PM模块】维护业务处理流程—外部维护
  3. python 子串是否在字符串中_python七种方法判断字符串是否包含子串
  4. 文档基本结构标签的作用
  5. python 画线条进行到指定区域更改颜色,使用Colormaps在matplotlib中设置线条的颜色...
  6. [Java] Java常见错误
  7. 模式识别、机器学习的区别和联系
  8. 关于C语言全局变量定义和引用写法总结
  9. soliworks三维机柜布局(二)创建设备位置
  10. 「AI深度思考·竞赛」天池宫颈癌诊断比赛数据处理开源
  11. 山科OJ:Problem C: Lemon
  12. 我所理解的闭包是酱紫的
  13. Jenkins连接svn报E170001错误的解决办法
  14. address already in use :::8080,端口号已被占用
  15. 4.17 使用阴影/高光命令解决图像曝光不足问题 [原创Ps教程]
  16. 化合物纯度、溶剂溶解度检测
  17. 我只记得别人给了我什么,不记得别人没给我什么?
  18. coda创建虚拟环境后无法切换到原环境
  19. 好文分享 行到艰难处 方是修心时
  20. 移动联通电信4g和移动4g有什么区别

热门文章

  1. mysql 分函数_mysql常见函数-分组函数
  2. [数据分析笔记] Pandas处理TGI指标
  3. Ubuntu中安装KDE桌面【踩了好多坑~成功】
  4. Matlab 列主元高斯消去法
  5. 42个激发灵感、漂亮的登陆页面设计
  6. KVM——迁移KVM虚拟机
  7. Oracle中对空字符串的判断
  8. 数据单位:概况容量 Byte、KB、MB、GB、TB、PB、EB、ZB、YB、NB、DB、CB、XB
  9. npm ERR A complete log of this run can be found in npm ERR CUsersAppDataRoamingnpm-ca
  10. 技术演讲培训干货分享:三大要点,14个tips