Ⅰ 用Python写一个简单的小游戏
相信大家都玩过俄罗斯方块吧,应该是小时候的回忆吧,但是想不想了解一下这个程序是怎么写出来的呢,自己写出来的应该玩起来更有感觉吧凳孙!
感觉还是蛮好玩吧!
接下来,我就分享一下这个游戏的源码过程啊!
先用python创建一个py文件
定义这次程序所需要的类
然后写出竖粗汪它所需要的模块
画背景图
画网格线
# 画已经落下的方块
# 画单个方块
# 画得分等信息
这样就可以写出来一个十分简单的俄罗斯方块啦,是不是觉得还不余仔错呢!
Ⅱ python小游戏
idea +python3.8+pygame
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n5" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import random
rang1 = int(input("请设置本局游戏的最小值:"))
rang2 = int(input("请设置本局游戏的最大值:"))
num = random.randint(rang1,rang2)
guess = "guess"
print("数饥裂岁字猜谜游戏!")
i = 0
while guess != num:
i += 1
guess = int(input("请输入你猜的数字:"))
if guess == num:
print("恭喜,你猜对了!")
elif guess < num:
print("你猜的数小了...")
else:
print("你猜的数大了...")
print("你总共猜了%d" %i + "次",end = '')
print(",快和你朋友较量一下...")</pre>
成果图源顷
[图片上烂睁传失败...(image-6ef72d-1619168958721)]
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n10" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">import pygame
import random
from pygame.locals import *
WIDTH = 1200
HEIGHT = 600
class Peas:
def init (self):
self.image = pygame.image.load("./res/peas.gif")
self.image_rect = self.image.get_rect()
self.image_rect.top = 285
self.image_rect.left = 30
self.is_move_up = False
self.is_move_down = False
self.is_shout = False
def display(self):
"""显示豌豆的方法"""
screen.blit(self.image, self.image_rect)
def move_up(self):
"""豌豆向上移动"""
if self.image_rect.top > 30:
self.image_rect.move_ip(0, -10)
else:
for z in Zombie.zombie_list:
if self.image_rect.colliderect(z.image_rect):
pygame.quit()
exit()
def move_down(self):
"""豌豆向下移动"""
if self.image_rect.bottom < HEIGHT - 10:
self.image_rect.move_ip(0, 10)
else:
for z in Zombie.zombie_list:
if self.image_rect.colliderect(z.image_rect):
pygame.quit()
exit()
def shout_bullet(self):
"""发射炮弹方法"""
bullet = Bullet(self)
Bullet.bullet_list.append(bullet)
class Bullet:
bullet_list = []
interval = 0
def init (self, peas):
self.image = pygame.image.load("./res/bullet.gif")
self.image_rect = self.image.get_rect()
self.image_rect.top = peas.image_rect.top
self.image_rect.left = peas.image_rect.right
def display(self):
"""显示炮弹的方法"""
screen.blit(self.image, self.image_rect)
def move(self):
"""移动炮弹"""
self.image_rect.move_ip(8, 0)
if self.image_rect.right > WIDTH - 20:
Bullet.bullet_list.remove(self)
else:
for z in Zombie.zombie_list[:]:
if self.image_rect.colliderect(z.image_rect):
Zombie.zombie_list.remove(z)
Bullet.bullet_list.remove(self)
break
class Zombie:
zombie_list = []
interval = 0
def init (self):
self.image = pygame.image.load("./res/zombie.gif")
self.image = pygame.transform.scale(self.image, (70, 70))
self.image_rect = self.image.get_rect()
self.image_rect.top = random.randint(10, HEIGHT-70)
self.image_rect.left = WIDTH
def display(self):
"""显示炮弹的方法"""
screen.blit(self.image, self.image_rect)
def move(self):
"""移动僵尸"""
self.image_rect.move_ip(-2, 0)
if self.image_rect.left < 0:
Zombie.zombie_list.remove(self)
else:
if self.image_rect.colliderect(peas.image_rect):
pygame.quit()
exit()
for b in Bullet.bullet_list[:]:
if self.image_rect.colliderect(b.image_rect):
Bullet.bullet_list.remove(b)
Zombie.zombie_list.remove(self)
break
def key_control():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
if event.type == KEYDOWN:
if event.key == K_UP:
peas.is_move_up = True
peas.is_move_down = False
elif event.key == K_DOWN:
peas.is_move_up = False
peas.is_move_down = True
elif event.key == K_SPACE:
peas.is_shout = True
if event.type == KEYUP:
if event.key == K_UP:
peas.is_move_up = False
elif event.key == K_DOWN:
peas.is_move_down = False
elif event.key == K_SPACE:
peas.is_shout = False
if name == ' main ':
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
background_image = pygame.image.load("./res/background.png")
scale_background_image = pygame.transform.scale(background_image, (WIDTH, HEIGHT))
scale_background_image_rect = scale_background_image.get_rect()
clock = pygame.time.Clock()
peas = Peas()
while True:
screen.fill((0,0,0))
screen.blit(scale_background_image, scale_background_image_rect)
peas.display()
key_control()
if peas.is_move_up:
peas.move_up()
if peas.is_move_down:
peas.move_down()
Bullet.interval += 1
if peas.is_shout and Bullet.interval >= 15:
Bullet.interval = 0
peas.shout_bullet()
Zombie.interval += 1
if Zombie.interval >= 15:
Zombie.interval = 0
Zombie.zombie_list.append(Zombie())
for bullet in Bullet.bullet_list:
bullet.display()
bullet.move()
for zombie in Zombie.zombie_list:
zombie.display()
zombie.move()
pygame.display.update()
clock.tick(60)</pre>
成果[图片上传失败...(image-983fba-1619168958718)]
Ⅲ python入门可以做的小游戏
1、Python入门拼图小游戏
简单介绍:
将图像分为m×n个矩形块,并将图像右下角的矩形块替换为空白块后,将这些矩形块随机摆放成原图像的形状。
2、Python入门推箱子小游戏
简单介绍:
这是来自日本的一个经典游戏,在狭小的仓库中,要求把木箱放到指定的位置,如果不小心就可能出现箱子无法移动或者通道被堵的情况,所以,如何巧妙利用有限的空间和通道,合理安排移动顺棚前迟序,就成了这个游戏能否通关的关键。
3、Python入门小游戏之外星人入侵
简单介绍:
玩家可以通过鼠标控制飞船的移动和射击,如果能在敌人达到游戏界面低端之前消灭所有敌人,则游戏胜利,否则游戏失败。
4、Python入门小游戏之吃豆子
简单介绍:
通过键盘方向键,控制游戏的人物吃豆人,吃掉藏在迷宫内的所有豆子,并且不能被敌人抓到。
5、Python入门小游戏之宝石消消乐
简单介绍:
玩家通过鼠标交换相邻的拼图,若交换后,在水平/竖直方向存在连续三个相同的链李拼图,则这些拼图消失,玩家得分。
6、Python入门小游戏之乒乓球对战
简单介绍:
中间是球网,玩家通过上下键移动球拍,并且这个游戏是可以悔升两个人玩的哦。
7、还有其他四个游戏
它们是:炸弹人小游戏、逃出迷宫、飞扬的小鸟、五子棋
Ⅳ “python小游戏”据说这是一款还原度超高的小游戏,你感受下....
哈喽,大家好呀~欢迎大家阅读我的文章!
又到了每日 游戏 更新系列,看到这么如下.gif是不是让你想起来了童年吖~
贪吃蛇 的人气可谓是经久不衰,有过了许多不同的版本,但大体 游戏 规则都是控制蛇的向,
寻找吃的东西,每吃一口就能得到一定的积分,而且蛇的身子会越吃越长,身子越长玩的难度
就越大,不能碰墙,不能咬到自己的身体,更不能咬自己的尾巴,还要注意其他的蛇!
哪个版本的贪吃蛇是你罩誉的童年
是这个
嘿嘿 ~~~
好了,放图片路
就是这个大工程今天带大家做一款 Python 版本的贪吃蛇 游戏 !
直接放代码
不管玩得多么纯熟,技术多么高超,但最终慎宽都会是听到贪食蛇的一声惨叫。记住:小蛇韬光养晦,中蛇欺软怕物孝段硬,大蛇明哲保身哟~
Ⅳ python能做什么游戏
Python是一门高级且有趣的编程语言,除了网络爬虫、人工智能、数据分析之外,Python还可以进行游戏开发,为大家介绍五个支持Python的2D、3D游戏开发库。
1、Cocos2d:是一系列开源软件框架,用于构建跨平台2D游戏和应用程序,由cocos2d-x、cocos2d-js、cocos2d-xna和cocos2d多种框架组成,像大鱼赌场、城堡冲突等小游戏,就是用此框架开发出来的。
2、Panda3D:是由迪士尼开发的3D游戏引擎,一个用于Python和C++程序的3D渲染和游戏开发框架,并由卡内基梅陇娱乐技术中心负责维护,使用C++编写的,针对Python进行了完全的封装。
3、Pygame:它是一组Python模块,用来编写游戏,可支持Python3.7,游戏例子有:纸牌游戏、超级马里奥、击球等多种游戏。
4、Pyogre:ogre 3D渲染引擎的Python绑定,可以用来开发游戏和仿真程序等任何3D应用,它的API更加稳定,也非常快速灵活。
5、RenPy:一个视觉小说引擎,被世界各地的成千万的创造者所使用,它可以帮助你使用文字、图像和声音来讲述电脑和移动设备上的故事。RenPy是开放源码的,可免费的商业用途,易于学习的脚本语言任何人都能有效地编写大型视觉小说,它的Python脚本足以用来模拟游戏。
Ⅵ Python实现消消乐小游戏
pre{overflow-x: auto} 实现 消消乐局搭的构成主要包括三嫌祥部分:游戏主体、计分器、计时器,下面芹腊搏来看一下具体实现。
先来看一下游戏所需 Python 库。
import os import sys import time import pygame import random
定义一些常量,比如:窗口宽高、网格行列数等,代码如下:
WIDTH = 400 HEIGHT = 400 NUMGRID = 8 GRIDSIZE = 36 XMARGIN = (WIDTH - GRIDSIZE * NUMGRID) // 2 YMARGIN = (HEIGHT - GRIDSIZE * NUMGRID) // 2 ROOTDIR = os.getcwd() FPS = 30
接着创建一个主窗口,代码如下:
pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('消消乐')
看一下效果:
再接着在窗口中画一个 8 x 8 的网格,代码如下:
screen.fill((255, 255, 220)) # 游戏界面的网格绘制 def drawGrids(self): for x in range(NUMGRID): for y in range(NUMGRID): rect = pygame.Rect((XMARGIN+x*GRIDSIZE, YMARGIN+y*GRIDSIZE, GRIDSIZE, GRIDSIZE)) self.drawBlock(rect, color=(255, 165, 0), size=1 # 画矩形 block 框 def drawBlock(self, block, color=(255, 0, 0), size=2): pygame.draw.rect(self.screen, color, block, size)
看一下效果:
再接着在网格中随机放入各种拼图块,代码如下:
while True: self.all_gems = [] self.gems_group = pygame.sprite.Group() for x in range(NUMGRID): self.all_gems.append([]) for y in range(NUMGRID): gem = Puzzle(img_path=random.choice(self.gem_imgs), size=(GRIDSIZE, GRIDSIZE), position=[XMARGIN+x*GRIDSIZE, YMARGIN+y*GRIDSIZE-NUMGRID*GRIDSIZE], downlen=NUMGRID*GRIDSIZE) self.all_gems[x].append(gem) self.gems_group.add(gem) if self.isMatch()[0] == 0: break
看一下效果:
再接着加入计分器和计时器,代码如下:
# 显示得分 def drawScore(self): score_render = self.font.render('分数:'+str(self.score), 1, (85, 65, 0)) rect = score_render.get_rect() rect.left, rect.top = (55, 15) self.screen.blit(score_render, rect) # 显示加分 def drawAddScore(self, add_score): score_render = self.font.render('+'+str(add_score), 1, (255, 100, 100)) rect = score_render.get_rect() rect.left, rect.top = (250, 250) self.screen.blit(score_render, rect) # 显示剩余时间 def showRemainingTime(self): remaining_time_render = self.font.render('倒计时: %ss' % str(self.remaining_time), 1, (85, 65, 0)) rect = remaining_time_render.get_rect() rect.left, rect.top = (WIDTH-190, 15) self.screen.blit(remaining_time_render, rect)
看一下效果:
当设置的游戏时间用尽时,我们可以生成一些提示信息,代码如下:
while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYUP and event.key == pygame.K_r: flag = True if flag: break screen.fill((255, 255, 220)) text0 = '最终得分: %s' % score text1 = '按 R 键重新开始' y = 140 for idx, text in enumerate([text0, text1]): text_render = font.render(text, 1, (85, 65, 0)) rect = text_render.get_rect() if idx == 0: rect.left, rect.top = (100, y) elif idx == 1: rect.left, rect.top = (100, y) y += 60 screen.blit(text_render, rect) pygame.display.update()
看一下效果:
说完了游戏图形化界面相关的部分,我们再看一下游戏的主要处理逻辑。
我们通过鼠标来操纵拼图块,因此程序需要检查有无拼图块被选中,代码实现如下:
def checkSelected(self, position): for x in range(NUMGRID): for y in range(NUMGRID): if self.getGemByPos(x, y).rect.collidepoint(*position): return [x, y] return None
我们需要将鼠标连续选择的拼图块进行位置交换,代码实现如下:
def swapGem(self, gem1_pos, gem2_pos): margin = gem1_pos[0] - gem2_pos[0] + gem1_pos[1] - gem2_pos[1] if abs(margin) != 1: return False gem1 = self.getGemByPos(*gem1_pos) gem2 = self.getGemByPos(*gem2_pos) if gem1_pos[0] - gem2_pos[0] == 1: gem1.direction = 'left' gem2.direction = 'right' elif gem1_pos[0] - gem2_pos[0] == -1: gem2.direction = 'left' gem1.direction = 'right' elif gem1_pos[1] - gem2_pos[1] == 1: gem1.direction = 'up' gem2.direction = 'down' elif gem1_pos[1] - gem2_pos[1] == -1: gem2.direction = 'up' gem1.direction = 'down' gem1.target_x = gem2.rect.left gem1.target_y = gem2.rect.top gem1.fixed = False gem2.target_x = gem1.rect.left gem2.target_y = gem1.rect.top gem2.fixed = False self.all_gems[gem2_pos[0]][gem2_pos[1]] = gem1 self.all_gems[gem1_pos[0]][gem1_pos[1]] = gem2 return True
每一次交换拼图块时,我们需要判断是否有连续一样的三个及以上拼图块,代码实现如下:
def isMatch(self): for x in range(NUMGRID): for y in range(NUMGRID): if x + 2 -2: for each in [res_match[1], res_match[1]+1, res_match[1]+2]: gem = self.getGemByPos(*[each, start]) if start == res_match[2]: self.gems_group.remove(gem) self.all_gems[each][start] = None elif start >= 0: gem.target_y += GRIDSIZE gem.fixed = False gem.direction = 'down' self.all_gems[each][start+1] = gem else: gem = Puzzle(img_path=random.choice(self.gem_imgs), size=(GRIDSIZE, GRIDSIZE), position=[XMARGIN+each*GRIDSIZE, YMARGIN-GRIDSIZE], downlen=GRIDSIZE) self.gems_group.add(gem) self.all_gems[each][start+1] = gem start -= 1 elif res_match[0] == 2: start = res_match[2] while start > -4: if start == res_match[2]: for each in range(0, 3): gem = self.getGemByPos(*[res_match[1], start+each]) self.gems_group.remove(gem) self.all_gems[res_match[1]][start+each] = None elif start >= 0: gem = self.getGemByPos(*[res_match[1], start]) gem.target_y += GRIDSIZE * 3 gem.fixed = False gem.direction = 'down' self.all_gems[res_match[1]][start+3] = gem else: gem = Puzzle(img_path=random.choice(self.gem_imgs), size=(GRIDSIZE, GRIDSIZE), position=[XMARGIN+res_match[1]*GRIDSIZE, YMARGIN+start*GRIDSIZE], downlen=GRIDSIZE*3) self.gems_group.add(gem) self.all_gems[res_match[1]][start+3] = gem start -= 1
之后反复执行这个过程,直至耗尽游戏时间,游戏结束。
最后,我们动态看一下游戏效果。
总结
本文我们使用 Python 实现了一个简单的消消乐游戏,有兴趣的可以对游戏做进一步扩展,比如增加关卡等。
到此这篇关于Python实现消消乐小游戏的文章就介绍到这了,希望大家以后多多支持!
Ⅶ python能做什么游戏
python能做什么游戏?
python可以开发一些小游戏,实际上Python中是有一些对应的官方或者非官方的游戏开发库的。
1. Github上面有个项目Free Python Games,里面集合了不少的Python开发的小游戏,能玩,也适合新手用来练练手,另外 PyGame 这个网站里面里面集合了很多Python开发的小游戏。
2. Python版本的 Flapy Bird 简化版,但是感觉更加难玩了。当然你也可以尝试用Python开发原版的 Flapy Bird,涵盖了颜色图像等:Flappy Block - 1.0
3. 小时候经常在手机上玩的一个游戏,凳友扰也是一款经典的街机游戏,这款游戏进化之后其实就是一个打乒乓的小游戏,枣旦这里同样有一个进化版本,图形设计的更加好看告键:Ping Pong
4. 以前初高中在学校很无聊的时候跟同桌或者前后桌玩的游戏,你还记得么
5. 同样一款小时候在小霸王上玩的游戏:Junk Jungle
6. 除此之外,一款比较有名基于Pyhton的战争的游戏:Home - TaleWorlds Entertainment
7. 一款看起来非常有趣的3D游戏:Galcon
相关推荐:《Python教程》
以上就是小编分享的关于python能做什么游戏的详细内容希望对大家有所帮助,更多有关python教程请关注环球青藤其它相关文章!
Ⅷ Python程序开发之简单小程序实例(11)小游戏-跳动的小球
Python程序开发之简单小程序实例
(11)小 游戏 -跳动的小球
一、项目功能
用户控制挡板来阻挡跳动的小球。
二、项目分析
根据项目功能自定义两个类,一个用于控制小球在窗体中的运动,一个用于接收用户按下左右键时,挡板在窗体中的运动。在控制小球的类中,我们还需要考虑当小球下降时,碰到挡板时的位置判断。
三、程序源代码
源码部分截图:
源码:
#!/usr/bin/python3.6
# -*- coding: GBK -*-
#导入相应模块
from tkinter import *
import random
import time
#自定义小球的类 Ball
class Ball:
# 初始化
def __init__(self,canvas,paddle,color):
#传递画布值
self.canvas=canvas
#传递挡板值
self.paddle=paddle
#画圆并且保存其ID
self.id=canvas.create_oval(10,10,25,25,fill=color)
self.canvas.move(self.id,245,100)
#小球的水平位置档厅起始列表
start=[-3,-2,-1,1,2,3]
#随机化位置列表
random.shuffle(start)
self.x=start[0]
self.y=-2
self.canvas_heigh=self.canvas.winfo_height()#获取窗口高度并保存
self.canvas_width=self.canvas.winfo_width()
#根据参数值绘制小球
def draw(self):
self.canvas.move(self.id,self.x,self.y)
pos=self.canvas.coords(self.id)#返回相应ID代表的图形的当前坐败拿标(左察蠢搭上角和右上角坐标)
#使得小球不会超出窗口
pad=self.canvas.coords(self.paddle.id)#获取小球挡板的坐标
if pos[1]=self.canvas_heigh or(pos[3]>=pad[1] and pos[2]>=pad[0] and pos[2]