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小游戏2048,上班摸鱼必备(附源码)
话不多说,直接上菜
为了方便大家,我就不分段解释了
import turtle, random
# 定义一个类,用来画除了数字方块之外的图形
class BackGround(turtle.Turtle):
def __init__(self):
super().__init__()
self.penup()
self.ht()
def draw_block(self):
self.shape('bg.gif') # 画出背景方块
for i in allpos:
self.goto(i)
self.stamp()
self.color('white', 'white') # 画出其他背景
self.goto(-215, 120)
self.begin_fill()
self.goto(215, 120)
self.goto(215, 110)
self.goto(-215, 110)
self.end_fill()
self.shape('title.gif')
self.goto(-125, 210)
self.stamp()
self.shape('score.gif')
self.goto(125, 245)
self.stamp()
self.shape('top_score.gif')
self.goto(125, 170)
self.stamp()
# 游戏失败及达成2048的提示文字
def judge(self):
global flag_win, flag_win_lose_text
self.color('blue')
judge = 0 # 判断是否还有位置可以移动
for i in block_dic.values():
for j in block_dic.values():
if i.num == 0 or i.num == j.num and i.distance(j) == 100:
judge += 1
if judge == 0: # 无位置可移动,游戏失败
self.write(' GAME OVER\n重新开始请按空格键', align='center', font=('黑体', 30, 'bold'))
flag_win_lose_text = False
if flag_win is True: # 此条件让2048达成的判断只能进行一次
for k in block_dic.values():
if k.num == 2048: # 游戏达成
flag_win = False
self.write(' 达成2048\n继续游戏请按回车键', align='center', font=('黑体', 30, 'bold'))
flag_win_lose_text = False
def win_lose_clear(self):
global flag_win_lose_text
self.clear()
flag_win_lose_text = True
def show_score(self): # 分值的显示
global score, top_score
if score > top_score:
top_score = score
with open('.\\score.txt', 'w') as f:
f.write(f'{top_score}')
self.color('white')
self.goto(125, 210)
self.clear()
self.write(f'{score}', align='center', font=('Arial', 20, 'bold'))
self.goto(125, 135)
self.write(f'{top_score}', align='center', font=('Arial', 20, 'bold'))
# 数字方块类
class Block(turtle.Turtle):
def __init__(self):
super().__init__()
self.ht()
self.penup()
self.num = 0
def draw(self):
self.clear()
dic_draw = {2: '#eee6db', 4: '#efe0cd', 8: '#f5af7b',
16: '#fb9660', 32: '#f57d5a', 64: '#f95c3d',
128: '#eccc75', 256: '#eece61', 512: '#efc853',
1024: '#ebc53c', 2048: '#eec430', 4096: '#aeb879',
8192: '#aab767', 16384: '#a6b74f'}
if self.num > 0: # 数字大于0,画出方块
self.color(f'{dic_draw[self.num]}') # 选择颜色
self.begin_fill()
self.goto(self.xcor()+48, self.ycor()+48)
self.goto(self.xcor()-96, self.ycor())
self.goto(self.xcor(), self.ycor()-96)
self.goto(self.xcor()+96, self.ycor())
self.goto(self.xcor(), self.ycor()+96)
self.end_fill()
self.goto(self.xcor()-48, self.ycor()-68)
if self.num > 4: # 按照数字选择数字的颜色
self.color('white')
else:
self.color('#6d6058')
self.write(f'{self.num}', align='center', font=('Arial', 27, 'bold'))
self.goto(self.xcor(), self.ycor()+20)
class Game():
def init(self):
back = BackGround() # 实例画出游戏的背景
back.draw_block()
for i in allpos: # 画出16个海龟对应16个数字块
block = Block()
block.goto(i)
block_dic[i] = block
game.grow()
def restart(self): # 重开游戏的方法
global score, flag_win_lose_text
score = 0
for i in block_dic.values():
i.num = 0
i.clear()
win_lose_text.clear()
game.grow()
flag_win_lose_text = True # 此flag为游戏达成或失败出现提示语后的判断,要提示语被clear后才能继续move
def grow(self): # 随机出现一个2或4的数字块
block_list = []
for i in allpos:
if block_dic[i].num == 0:
block_list.append(block_dic[i]) # 挑出空白方块的海龟
turtle_choice = random.choice(block_list) # 随机选中其中一个海龟
turtle_choice.num = random.choice([2, 2, 2, 2, 4]) # 赋属性num=2/4
turtle_choice.draw()
win_lose_text.judge()
show_score_text.show_score()
ms.update()
def move_up(self):
allpos1 = allpos[::4] # 切片为四列
allpos2 = allpos[1::4]
allpos3 = allpos[2::4]
allpos4 = allpos[3::4]
self.move_move(allpos1, allpos2, allpos3, allpos4)
def move_down(self):
allpos1 = allpos[-4::-4]
allpos2 = allpos[-3::-4]
allpos3 = allpos[-2::-4]
allpos4 = allpos[-1::-4]
self.move_move(allpos1, allpos2, allpos3, allpos4)
def move_left(self):
allpos1 = allpos[:4]
allpos2 = allpos[4:8]
allpos3 = allpos[8:12]
allpos4 = allpos[12:16]
self.move_move(allpos1, allpos2, allpos3, allpos4)
def move_right(self):
allpos1 = allpos[-1:-5:-1]
allpos2 = allpos[-5:-9:-1]
allpos3 = allpos[-9:-13:-1]
allpos4 = allpos[-13:-17:-1]
self.move_move(allpos1, allpos2, allpos3, allpos4)
def move_move(self, allpos1, allpos2, allpos3, allpos4):
if flag_win_lose_text is True:
count1 = self.move(allpos1) # 四列或四行依次移动
count2 = self.move(allpos2)
count3 = self.move(allpos3)
count4 = self.move(allpos4)
if count1 or count2 or count3 or count4: # 判断是否有方块移动,有才能继续出现新的数字块
self.grow()
def move(self, pos_list):
num_list = [] # 为某一列或行的数字块海龟的坐标
for i in pos_list:
num_list.append(block_dic[i].num) # 把这些海龟的NUM形成list
new_num_list, count = self.list_oper(num_list) # 只是list_oper的方法形成新的list
for j in range(len(new_num_list)): # 把新的list依次赋值给对应的海龟.num属性并调用draw()方法
block_dic[pos_list[j]].num = new_num_list[j]
block_dic[pos_list[j]].draw()
return count
def list_oper(self, num_list): # num_list的操作,假设其为【2,0,2,2】
global score
count = True
temp = []
new_temp = []
for j in num_list:
if j != 0:
temp.append(j) # temp=[2,2,2]
flag = True
for k in range(len(temp)):
if flag:
if k < len(temp)-1 and temp[k] == temp[k+1]:
new_temp.append(temp[k]*2)
flag = False
score += temp[k]
else:
new_temp.append(temp[k]) # new_temp=[4,2]
else:
flag = True
for m in range(len(num_list)-len(new_temp)):
new_temp.append(0) # new_temp=[4,2,0,0]
if new_temp == num_list:
count = False # 此变量判断num_list没有变化,数字块无移动
return(new_temp, count)
if __name__ == '__main__':
ms = turtle.Screen() # 主窗口的设置
ms.setup(430, 630, 400, 50)
ms.bgcolor('gray')
ms.title('2048')
ms.tracer(0)
ms.register_shape('bg.gif')
ms.register_shape('title.gif')
ms.register_shape('score.gif')
ms.register_shape('top_score.gif')
block_dic = {} # 放数字方块海龟的字典,位置坐标为key,对应海龟为value
allpos = [(-150, 50), (-50, 50), (50, 50), (150, 50),
(-150, -50), (-50, -50), (50, -50), (150, -50),
(-150, -150), (-50, -150), (50, -150), (150, -150),
(-150, -250), (-50, -250), (50, -250), (150, -250)]
flag_win = True # 达成2048的判断,让达成的文字仅出现一次
flag_win_lose_text = True # 用来判断失败或成功的提示文字是否有被清除,不清除不能继续移动方块
score = 0
with open('.\\score.txt', 'r') as f:
top_score = int(f.read()) # 读取score中的数据
show_score_text = BackGround()
win_lose_text = BackGround()
game = Game()
game.init()
ms.listen()
ms.onkey(game.move_up, 'Up')
ms.onkey(game.move_down, 'Down')
ms.onkey(game.move_left, 'Left')
ms.onkey(game.move_right, 'Right')
ms.onkey(win_lose_text.win_lose_clear, 'Return')
ms.onkey(game.restart, 'space')
ms.mainloop()
这是游戏界面:
欢迎挑战最高分。
要运行出来,必须本地要有这些文件:bg.gif,score.gif,title.gif,top_score.gif,score.txt
我把这些文件放在了群里,还有一些学习的资料,群号642109462,欢迎对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]