Python基础教程——制作记事本、俄罗斯方块(完整版,附源码)

一、记事本

1. 案例介绍

tkinter 是 Python下面向 tk 的图形界面接口库,可以方便地进行图形界面设计和交互操作编程。tkinter 的优点是简单易用、与 Python 的结合度好。tkinter 在 Python 3.x 下默认集成,不需要额外的安装操作;不足之处为缺少合适的可视化界面设计工具,需要通过代码来完成窗口设计和元素布局。

本例采用的 Python 版本为 3.8,如果想在 python 2.x下使用 tkinter,请先进行安装。需要注意的是,不同 Python 版本下的 tkinter 使用方式可能略有不同,建议采用 Python3.x 版本。

本例难度为中级,适合具有 Python 基础和 Tkinter 组件编程知识的用户学习。

2. 示例效果

3. 示例源码

from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
import os


filename = ""   


def author():
showinfo(title="作者", message="Python")


def power():
showinfo(title="版权信息", message="课堂练习")


def mynew():
global top, filename, textPad
top.title("未命名文件")
filename = None
textPad.delete(1.0, END)


def myopen():
global filename
filename = askopenfilename(defaultextension=".txt")
if filename == "":
filename = None
else:
top.title("记事本" + os.path.basename(filename))
textPad.delete(1.0, END)
f = open(filename, 'r')
textPad.insert(1.0, f.read())
f.close()


def mysave():
global filename
try:
f = open(filename, 'w')
msg = textPad.get(1.0, 'end')
f.write(msg)
f.close()
except:
mysaveas()


def mysaveas():
global filename
f = asksaveasfilename(initialfile="未命名.txt", defaultextension=".txt")
filename = f
fh = open(f, 'w')
msg = textPad.get(1.0, END)
fh.write(msg)
fh.close()
top.title("记事本 " + os.path.basename(f))


def cut():
global textPad
textPad.event_generate("<<Cut>>")


def copy():
global textPad
textPad.event_generate("<<Copy>>")


def paste():
global textPad
textPad.event_generate("<<Paste>>")


def undo():
global textPad
textPad.event_generate("<<Undo>>")


def redo():
global textPad
textPad.event_generate("<<Redo>>")


def select_all():
global textPad
# textPad.event_generate("<<Cut>>")
textPad.tag_add("sel", "1.0", "end")


def find():
t = Toplevel(top)
t.title("查找")
t.geometry("260x60+200+250")
t.transient(top)
Label(t, text="查找:").grid(row=0, column=0, sticky="e")
v = StringVar()
e = Entry(t, width=20, textvariable=v)
e.grid(row=0, column=1, padx=2, pady=2, sticky="we")
e.focus_set()
c = IntVar()
Checkbutton(t, text="不区分大小写", variable=c).grid(row=1, column=1, sticky='e')
Button(t, text="查找所有", command=lambda: search(v.get(), c.get(),
 textPad, t, e)).grid(row=0, column=2, sticky="e" + "w", padx=2,pady=2)
                                  


def close_search():
textPad.tag_remove("match", "1.0", END)
t.destroy()
t.protocol("WM_DELETE_WINDOW", close_search)


def mypopup(event):
# global editmenu
editmenu.tk_popup(event.x_root, event.y_root)


def search(needle, cssnstv, textPad, t, e):
textPad.tag_remove("match", "1.0", END)
count = 0
if needle:
pos = "1.0"
while True:
pos = textPad.search(needle, pos, nocase=cssnstv, stopindex=END)
if not pos:
break
lastpos = pos + str(len(needle))
textPad.tag_add("match", pos, lastpos)
count += 1
pos = lastpos
textPad.tag_config('match', fg='yellow', bg="green")
e.focus_set()
t.title(str(count) + "个被匹配")


top = Tk()
top.title("记事本")
top.geometry("600x400+100+50")
menubar = Menu(top)


# 文件功能
filemenu = Menu(top)
filemenu.add_command(label="新建", accelerator="Ctrl+N", command=mynew)
filemenu.add_command(label="打开", accelerator="Ctrl+O", command=myopen)
filemenu.add_command(label="保存", accelerator="Ctrl+S", command=mysave)
filemenu.add_command(label="另存为", accelerator="Ctrl+shift+s", command=mysaveas)
menubar.add_cascade(label="文件", menu=filemenu)


# 编辑功能
editmenu = Menu(top)
editmenu.add_command(label="撤销", accelerator="Ctrl+Z", command=undo)
editmenu.add_command(label="重做", accelerator="Ctrl+Y", command=redo)
editmenu.add_separator()``editmenu.add_command(label="剪切", accelerator="Ctrl+X", command=cut)
editmenu.add_command(label="复制", accelerator="Ctrl+C", command=copy)
editmenu.add_command(label="粘贴", accelerator="Ctrl+V", command=paste)
editmenu.add_separator()
editmenu.add_command(label="查找", accelerator="Ctrl+F", command=find)
editmenu.add_command(label="全选", accelerator="Ctrl+A", command=select_all)
menubar.add_cascade(label="编辑", menu=editmenu)


# 关于 功能
aboutmenu = Menu(top)
aboutmenu.add_command(label="作者", command=author)
aboutmenu.add_command(label="版权", command=power)
menubar.add_cascade(label="关于", menu=aboutmenu)


top['menu'] = menubar


# shortcutbar = Frame(top, height=25, bg='light sea green')
# shortcutbar.pack(expand=NO, fill=X)
# Inlabe = Label(top, width=2, bg='antique white')
# Inlabe.pack(side=LEFT, anchor='nw', fill=Y)


textPad = Text(top, undo=True)
textPad.pack(expand=YES, fill=BOTH)
scroll =Scrollbar(textPad)
textPad.config(yscrollcommand=scroll.set)
scroll.config(command=textPad.yview)
scroll.pack(side=RIGHT, fill=Y)


# 热键绑定
textPad.bind("<Control-N>", mynew)
textPad.bind("<Control-n>", mynew)
textPad.bind("<Control-O>", myopen)
textPad.bind("<Control-o>", myopen)
textPad.bind("<Control-S>", mysave)
textPad.bind("<Control-s>", mysave)
textPad.bind("<Control-A>", select_all)
textPad.bind("<Control-a>", select_all)
textPad.bind("<Control-F>", find)
textPad.bind("<Control-f>", find)

textPad.bind("<Button-3>", mypopup)
top.mainloop()

二、俄罗斯方块

1. 案例介绍

俄罗斯方块是由 4 个小方块组成不同形状的板块,随机从屏幕上方落下,按方向键调整板块的位置和方向,在底部拼出完整的一行或几行。这些完整的横条会消失,给新落下来的板块腾出空间,并获得分数奖励。没有被消除掉的方块不断堆积,一旦堆到顶端,便告输,游戏结束。

本例难度为高级,适合具有 Python 进阶和 Pygame 编程技巧的用户学习。

2. 设计要点

边框――由 15*25 个空格组成,方块就落在这里面。

盒子――组成方块的其中小方块,是组成方块的基本单元。

方块――从边框顶掉下的东西,游戏者可以翻转和改变位置。每个方块由 4 个盒子组成。

形状――不同类型的方块。这里形状的名字被叫做 T, S, Z ,J, L, I , O。如下图所示:

在这里插入图片描述
在这里插入图片描述

模版――用一个列表存放形状被翻转后的所有可能样式。全部存放在变量里,变量名字如 S or J。

着陆――当一个方块到达边框的底部或接触到在其他的盒子话,就说这个方块着陆了。那样的话,另一个方块就会开始下落。

3. 示例效果

4. 示例源码

import pygame
import random
import os


pygame.init()


GRID_WIDTH = 20
GRID_NUM_WIDTH = 15
GRID_NUM_HEIGHT = 25
WIDTH, HEIGHT = GRID_WIDTH * GRID_NUM_WIDTH, GRID_WIDTH * GRID_NUM_HEIGHT
SIDE_WIDTH = 200
SCREEN_WIDTH = WIDTH + SIDE_WIDTH
WHITE = (0xff, 0xff, 0xff)
BLACK = (0, 0, 0)
LINE_COLOR = (0x33, 0x33, 0x33)


CUBE_COLORS = [
(0xcc, 0x99, 0x99), (0xff, 0xff, 0x99), (0x66, 0x66, 0x99),
(0x99, 0x00, 0x66), (0xff, 0xcc, 0x00), (0xcc, 0x00, 0x33),
(0xff, 0x00, 0x33), (0x00, 0x66, 0x99), (0xff, 0xff, 0x33),
(0x99, 0x00, 0x33), (0xcc, 0xff, 0x66), (0xff, 0x99, 0x00)
]


screen = pygame.display.set_mode((SCREEN_WIDTH, HEIGHT))
pygame.display.set_caption("俄罗斯方块")
clock = pygame.time.Clock()
FPS = 30


score = 0
level = 1


screen_color_matrix = [[None] * GRID_NUM_WIDTH for i in range(GRID_NUM_HEIGHT)]


# 设置游戏的根目录为当前文件夹
base_folder = os.path.dirname(__file__)


def show_text(surf, text, size, x, y, color=WHITE):
font_name = os.path.join(base_folder, 'font/font.ttc')
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)


class CubeShape(object):
SHAPES = ['I', 'J', 'L', 'O', 'S', 'T', 'Z']
I = [[(0, -1), (0, 0), (0, 1), (0, 2)],
[(-1, 0), (0, 0), (1, 0), (2, 0)]]
J = [[(-2, 0), (-1, 0), (0, 0), (0, -1)],
[(-1, 0), (0, 0), (0, 1), (0, 2)],
[(0, 1), (0, 0), (1, 0), (2, 0)],
[(0, -2), (0, -1), (0, 0), (1, 0)]]
L = [[(-2, 0), (-1, 0), (0, 0), (0, 1)],
[(1, 0), (0, 0), (0, 1), (0, 2)],
[(0, -1), (0, 0), (1, 0), (2, 0)],
[(0, -2), (0, -1), (0, 0), (-1, 0)]]
O = [[(0, 0), (0, 1), (1, 0), (1, 1)]]
S = [[(-1, 0), (0, 0), (0, 1), (1, 1)],
[(1, -1), (1, 0), (0, 0), (0, 1)]]
T = [[(0, -1), (0, 0), (0, 1), (-1, 0)],
[(-1, 0), (0, 0), (1, 0), (0, 1)],
[(0, -1), (0, 0), (0, 1), (1, 0)],
[(-1, 0), (0, 0), (1, 0), (0, -1)]]
Z = [[(0, -1), (0, 0), (1, 0), (1, 1)],
[(-1, 0), (0, 0), (0, -1), (1, -1)]]
SHAPES_WITH_DIR = {
'I': I, 'J': J, 'L': L, 'O': O, 'S': S, 'T': T, 'Z': Z`    `}


def __init__(self):
self.shape = self.SHAPES[random.randint(0, len(self.SHAPES) - 1)]
# 骨牌所在的行列
self.center = (2, GRID_NUM_WIDTH // 2)
self.dir = random.randint(0, len(self.SHAPES_WITH_DIR[self.shape]) - 1)
self.color = CUBE_COLORS[random.randint(0, len(CUBE_COLORS) - 1)]


def get_all_gridpos(self, center=None):
curr_shape = self.SHAPES_WITH_DIR[self.shape][self.dir]
if center is None:
center = [self.center[0], self.center[1]]


return [(cube[0] + center[0], cube[1] + center[1])
for cube in curr_shape]


def conflict(self, center):
for cube in self.get_all_gridpos(center):
# 超出屏幕之外,说明不合法
if cube[0] < 0 or cube[1] < 0 or cube[0] >= GRID_NUM_HEIGHT or \
cube[1] >= GRID_NUM_WIDTH:
return True


# 不为None,说明之前已经有小方块存在了,也不合法
if screen_color_matrix[cube[0]][cube[1]] is not None:
return True


return False


def rotate(self):
new_dir = self.dir + 1
new_dir %= len(self.SHAPES_WITH_DIR[self.shape])
old_dir = self.dir
self.dir = new_dir
if self.conflict(self.center):
self.dir = old_dir
return False


def down(self):
# import pdb; pdb.set_trace()
center = (self.center[0] + 1, self.center[1])
if self.conflict(center):
return False


self.center = center
return True


def left(self):
center = (self.center[0], self.center[1] - 1)
if self.conflict(center):
return False
self.center = center
return True


def right(self):
center = (self.center[0], self.center[1] + 1)
if self.conflict(center):
return False
self.center = center
return True


def draw(self):
for cube in self.get_all_gridpos():
pygame.draw.rect(screen, self.color,
(cube[1] * GRID_WIDTH, cube[0] * GRID_WIDTH,
GRID_WIDTH, GRID_WIDTH))
pygame.draw.rect(screen, WHITE,
(cube[1] * GRID_WIDTH, cube[0] * GRID_WIDTH,
GRID_WIDTH, GRID_WIDTH),                            
1)


def draw_grids():
for i in range(GRID_NUM_WIDTH):
pygame.draw.line(screen, LINE_COLOR,
(i * GRID_WIDTH, 0), (i * GRID_WIDTH, HEIGHT))


for i in range(GRID_NUM_HEIGHT):
pygame.draw.line(screen, LINE_COLOR,
(0, i * GRID_WIDTH), (WIDTH, i * GRID_WIDTH))


pygame.draw.line(screen, WHITE,
(GRID_WIDTH * GRID_NUM_WIDTH, 0),
(GRID_WIDTH * GRID_NUM_WIDTH, GRID_WIDTH * GRID_NUM_HEIGHT))


def draw_matrix():
for i, row in zip(range(GRID_NUM_HEIGHT), screen_color_matrix):
for j, color in zip(range(GRID_NUM_WIDTH), row):
if color is not None:
pygame.draw.rect(screen, color,
(j * GRID_WIDTH, i * GRID_WIDTH,
GRID_WIDTH, GRID_WIDTH))
pygame.draw.rect(screen, WHITE,
(j * GRID_WIDTH, i * GRID_WIDTH,
GRID_WIDTH, GRID_WIDTH), 2)


def draw_score():
show_text(screen, u'得分:{}'.format(score), 20, WIDTH + SIDE_WIDTH // 2, 100)


def remove_full_line():
global screen_color_matrix
global score
global level
new_matrix = [[None] * GRID_NUM_WIDTH for i in range(GRID_NUM_HEIGHT)]
index = GRID_NUM_HEIGHT - 1
n_full_line = 0
for i in range(GRID_NUM_HEIGHT - 1, -1, -1):
is_full = True
for j in range(GRID_NUM_WIDTH):
if screen_color_matrix[i][j] is None:
is_full = False
continue
if not is_full:
new_matrix[index] = screen_color_matrix[i]
index -= 1
else:
n_full_line += 1
score += n_full_line
level = score // 20 + 1
screen_color_matrix = new_matrix


def show_welcome(screen):
show_text(screen, u'俄罗斯方块', 30, WIDTH / 2, HEIGHT / 2)
show_text(screen, u'按任意键开始游戏', 20, WIDTH / 2, HEIGHT / 2 + 50)

running = True
gameover = True
counter = 0
live_cube = None
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if gameover:
gameover = False
live_cube = CubeShape()
break
if event.key == pygame.K_LEFT:
live_cube.left()
elif event.key == pygame.K_RIGHT:
live_cube.right()
elif event.key == pygame.K_DOWN:   
live_cube.down()
elif event.key == pygame.K_UP:               
live_cube.rotate()
elif event.key == pygame.K_SPACE:
while live_cube.down() == True:
pass
remove_full_line()


# level 是为了方便游戏的难度,level 越高 FPS // level 的值越小
# 这样屏幕刷新的就越快,难度就越大
if gameover is False and counter % (FPS // level) == 0:
# down 表示下移骨牌,返回False表示下移不成功,可能超过了屏幕或者和之前固定的
# 小方块冲突了
if live_cube.down() == False:
for cube in live_cube.get_all_gridpos():
screen_color_matrix[cube[0]][cube[1]] = live_cube.color
live_cube = CubeShape()
if live_cube.conflict(live_cube.center):
gameover = True
score = 0
live_cube = None
screen_color_matrix = [[None] * GRID_NUM_WIDTH for i in range(GRID_NUM_HEIGHT)]
# 消除满行
remove_full_line()
counter += 1
# 更新屏幕
screen.fill(BLACK)
draw_grids()
draw_matrix()
draw_score()
if live_cube is not None:
live_cube.draw()
if gameover:
show_welcome(screen)
pygame.display.update()

看完案例的小伙伴们点个在看,顺便扫码帮忙关注一下呗,你的支持是我继续推新案例的动力。

最后这里免费分享给大家一份Python学习资料,包含视频、源码。课件,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
编程资料、学习路线图、源代码、软件安装包等!

看下方图片哦(掉落)↓↓↓

Python所有方向的学习路线图,清楚各个方向要学什么东西
100多节Python课程视频,涵盖必备基础、爬虫和数据分析
100多个Python实战案例,学习不再是只会理论
华为出品独家Python漫画教程,手机也能学习
历年互联网企业Python面试真题,复习时非常方便

在这里插入图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值