- 实现双人游戏之2048
import curses
from itertools import chain
from random import choice
import time
class GameField(object):
# 初始化信息
def __init__(self, width=4, height=4, win_value=8):
self.width = width
self.height = height
self.win_value = win_value
self.score_1 = 0 # 1当前得分
self.highscore_1 = 0 # 1最高分
self.score_2 = 0 # 1当前得分
self.highscore_2 = 0 # 1最高分
self.moves_1 = {}
self.moves_1['a'] = self.is_move_left
self.moves_1['d'] = self.is_move_right
self.moves_1['s'] = self.is_move_down
self.moves_1['w'] = self.is_move_up
self.movesDict_1 = {}
self.movesDict_1['a'] = self.move_left_1
self.movesDict_1['d'] = self.move_right_1
self.movesDict_1['s'] = self.move_down_1
self.movesDict_1['w'] = self.move_up_1
self.moves_2 = {}
self.moves_2['Left'] = self.is_move_left
self.moves_2['Right'] = self.is_move_right
self.moves_2['Down'] = self.is_move_down
self.moves_2['Up'] = self.is_move_up
self.movesDict_2 = {}
self.movesDict_2['Left'] = self.move_left_2
self.movesDict_2['Right'] = self.move_right_2
self.movesDict_2['Down'] = self.move_down_2
self.movesDict_2['Up'] = self.move_up_2
def reset_1(self): # 重置棋盘1
if self.score_1 > self.highscore_1:
self.highscore_1 = self.score_1 # 更新最高分
self.score_1 = 0
# 需求1: 生成4*4的棋盘, 其中数据结构选择列表嵌套列表;
self.field_1 = [[0 for j in range(self.width)]
for i in range(self.height)]
# 在棋盘的一个随机位置插入一个数字2或者4
self.random_create()
self.random_create()
def reset_2(self): # 重置棋盘2
if self.score_2 > self.highscore_2:
self.highscore_2 = self.score_2 # 更新最高分
self.score_2 = 0
# 需求1: 生成4*4的棋盘, 其中数据结构选择列表嵌套列表;
self.field_2 = [[0 for j in range(self.width)]
for i in range(self.height)]
# 在棋盘的一个随机位置插入一个数字2或者4
self.random_create()
self.random_create()
def random_create(self):
# 在棋盘的一个随机位置插入一个数字2或者4
# field[0][3] = 2
while True:
i, j = choice(range(self.height)), choice(range(self.width))
if self.field[i][j] == 0:
self.field[i][j] = choice([2, 2, 2, 4])
break
def draw(self, stdscr): #stdscr 逻辑屏幕
def draw_sep():
stdscr.addstr('+' + "-----+" * self.width + '\n')
def draw_one_row(row):
stdscr.addstr("".join('|{:^5}'.format(num) if num != 0 else "| " for num in row) + '|' + '\n')
# 清屏
stdscr.clear() #清屏
stdscr.addstr("2048".center(50, '-') + '\n') #显示一串字串
stdscr.addstr("当前玩家1分数:" + str(self.score_1) + '\n')
stdscr.addstr("当前玩家2分数:" + str(self.score_2) + '\n')
if self.highscore_1 != 0:
stdscr.addstr("最高分:" + str(self.highscore_1) + '\n')
if self.highscore_2 != 0:
stdscr.addstr("最高分:" + str(self.highscore_2) + '\n')
def draw_sep_1():
for row in self.field_1:
draw_sep()
draw_one_row(row)
draw_sep()
def draw_sep_2():
for row in self.field_2:
draw_sep()
draw_one_row(row)
draw_sep()
draw_sep_1()
draw_sep_2()
# 判断是否赢或者输
if self.is_win_1():
stdscr.addstr("player1 Winner!!!!" + '\n')
if self.is_gameover_1():
stdscr.addstr("player1 Game over!!!!" + '\n')
if self.is_win_2():
stdscr.addstr("player2 Winner!!!!" + '\n')
if self.is_gameover_2():
stdscr.addstr("player2 Game over!!!!" + '\n')
stdscr.addstr(" 游戏帮助: (1)player1: 上下左右键 (2)player2: wasd键 \n (R)Restart Q(Quit)")
#玩家1的结束判断
def is_win_1(self):
return max(chain(*self.field_1)) >= self.win_value
def is_gameover_1(self):
# 任何方向都不能移动的时候, 游戏结束
return not any([self.move_is_possible_1(direction)
for direction in self.moves_1])
#玩家2的结束判断
def is_win_2(self):
return max(chain(*self.field_2)) >= self.win_value
def is_gameover_2(self):
# 任何方向都不能移动的时候, 游戏结束
return not any([self.move_is_possible_2(direction)
for direction in self.moves_2])
@staticmethod
def invert(field):
# 矩阵进行反转
return [row[::-1] for row in field]
# print(invert(li))
@staticmethod
# 矩阵的转置
def transpose(field):
# *field ==== [1,2,3] [4,5,6] [7,8,9]
# zip(*field) ===== [1,4,7], [2,5,8] [3,6,9]
# list(zip(*field)) ====== [(1, 4, 7), (2, 5, 8), (3, 6, 9)] 但是将来元素需要修改,必须转换为列表
return [list(row) for row in zip(*field)]
@staticmethod
def is_row_change(row):
# row
# 需求3. 判断一行内容是否可移动。
def is_change(i): # 0
# 判断每两个元素之间是否可移动
if row[i] == 0 and row[i + 1] != 0:
return True
if row[i] != 0 and row[i] == row[i + 1]:
return True
return False
return any([is_change(index) for index in range(len(row) - 1)])
# 判断这个棋盘是否可向左移动
def is_move_left(self, field):
return any([self.is_row_change(row) for row in field])
def is_move_right(self, field):
# 对于列表元素进行反转
field = self.invert(field)
print(field)
return self.is_move_left(field)
def is_move_up(self, field):
# 对于列表元素进行转置
field = self.transpose(field)
return self.is_move_left(field)
def is_move_down(self, field):
# 反转+ 转置
field = self.transpose(field)
return self.is_move_right(field)
def move_is_possible_1(self, direction): # 'left'
# 判断用户1选择的方向是否可移动
if direction in self.moves_1:
return self.moves_1[direction](self.field)
else:
return False
def move_is_possible_2(self, direction): # 'left'
# 判断用户2选择的方向是否可移动
if direction in self.moves_2:
return self.moves_2[direction](self.field)
else:
return False
# 将棋盘每一行的非0数向前移动, 0向后移动;
@staticmethod
def tight(row): # [2, 0, 2, 0]
# 最快的方式, 通过排序实现...........
return sorted(row, key=lambda x: 1 if x == 0 else 0)
def merge_1(self, row): # [2,2,0,0]
# [0,1,2]
for i in range(len(row) - 1):
# 如果两个值相等, 前一个元素*2, 后一个元素改为0。
if row[i] == row[i + 1]:
row[i] *= 2
row[i + 1] = 0
# 如果覆盖成功, 就给得分
self.score_1 += row[i]
return row # [4, 0, 0, 0]
def merge_2(self, row): # [2,2,0,0]
# [0,1,2]
for i in range(len(row) - 1):
# 如果两个值相等, 前一个元素*2, 后一个元素改为0。
if row[i] == row[i + 1]:
row[i] *= 2
row[i + 1] = 0
# 如果覆盖成功, 就给得分
self.score_2 += row[i]
return row # [4, 0, 0, 0]
def move_row_left_1(self, row):
return self.tight(self.merge_1(self.tight(row)))
def move_left_1(self, field):
return [self.move_row_left_1(row) for row in field]
def move_right_1(self, field):
field = self.invert(field)
return self.invert([self.move_row_left_1(row) for row in field])
def move_up_1(self, field):
return self.transpose([self.move_row_left_1(row) for row in self.transpose(field)])
def move_down_1(self, field):
return self.invert(self.transpose([self.move_row_left_1(row)
for row in self.invert(self.transpose(field))]))
def move_row_left_2(self, row):
return self.tight(self.merge_1(self.tight(row)))
def move_left_2(self, field):
return [self.move_row_left_2(row) for row in field]
def move_right_2(self, field):
field = self.invert(field)
return self.invert([self.move_row_left_2(row) for row in field])
def move_up_2(self, field):
return self.transpose([self.move_row_left_2(row) for row in self.transpose(field)])
def move_down_2(self, field):
return self.invert(self.transpose([self.move_row_left_2(row)
for row in self.invert(self.transpose(field))]))
def move_1(self, direction): # 'left'
# 判断用户选择的方向是否可移动
if direction in self.movesDict_1:
# 判断是否可移动
if self.move_is_possible_1(direction):
self.field = self.movesDict_1[direction](self.field)
self.random_create()
return True
else:
return False
def move_2(self, direction): # 'left'
# 判断用户选择的方向是否可移动
if direction in self.movesDict_2:
# 判断是否可移动
if self.move_is_possible_2(direction):
self.field = self.movesDict_2[direction](self.field)
self.random_create()
return True
else:
return False
def get_user_action(stdscr):
action = stdscr.getch()
if action == curses.KEY_UP:
return 'Up'
if action == curses.KEY_DOWN:
return 'Down'
if action == curses.KEY_LEFT:
return 'Left'
if action == curses.KEY_RIGHT:
return 'Right'
if action == ord('w'):
return 'w'
if action == ord('s'):
return 's'
if action == ord('a'):
return 'a'
if action == ord('d'):
return 'd'
if action == ord('r'):
return 'Restart'
if action == ord('q'):
return 'Exit'
def main(stdscr):
action = stdscr.getch()
def init():
# 初始化棋盘的操作
game_field.reset_1()
game_field.reset_2()
game_field.draw(stdscr)
return 'Game'
def game():
game_field.draw(stdscr)
action = get_user_action(stdscr)
if action == 'Restart':
return 'Init'
if action == 'Exit':
return 'Exit'
if game_field.move_1(action):
if game_field.is_win_1():
return 'Win'
if game_field.is_gameover_1():
return 'GameOver'
if game_field.move_2(action):
if game_field.is_win_2():
return 'Win'
if game_field.is_gameover_2():
return 'GameOver'
return 'Game'
def not_game():
game_field.draw(stdscr)
while True:
action = get_user_action(stdscr)
if action == 'Restart':
return 'Init'
if action == 'Exit':
return 'Exit'
state_actions = {
'Init': init,
'Game': game,
'Win': not_game,
'GameOver': not_game,
}
game_field = GameField()
state = 'Init'
# 如果当前状态不是退出, 那么一直执行
while state != 'Exit':
# 执行当前状态需要操作的内容, 并返回, 下一次的状态为什么.
state = state_actions[state]()
curses.wrapper(main)
- 面向对象,文件操作与数据库操作复习题目:
文件score.dat中保存的是100名学生的姓名和Python课、高数和英语成绩。
(1)定义学生类,其中包含姓名、Python课、高数和英语成绩及总分、均分数据成员,成员函数根据需要确定。
(2)读入这名学生的成绩,用对象列表进行存储。
(3)求出各科和总分的最高分。
(4)请按总分的降序(高成绩在前,低成绩在后)排序
(5)在屏幕上显示各科及总分的最高分,排序后的成绩单(包括总分)保存到文件odered_score.dat中。
(6) 将文件中的所有学生信息, 保存在mariadb数据库中;
from itertools import chain
from random import *
import pymysql
def create_student_info():
def creat_name():
first = ['许', '张', '赵', '钱', '孙', '李', '朱', '杨']
second = ['彬', '群', '宁', '盼', '龙', '欢', '丹']
last = ['彬', '群', '宁', '盼', '龙', '欢', '丹', ' ', ' ', ' ', ' ']
name = choice(first) + choice(second) + choice(last)
return name.rstrip()
with open("score.dat", 'w+') as f:
for i in range(100):
name = creat_name()
py_score = randint(40, 100)
high_math_score = randint(40, 100)
english_score = randint(40, 100)
sum_score = int(py_score) + int(high_math_score) + int(english_score)
ave_score = float(sum_score)
f.write(name + ' ' + str(py_score) + ' ' + str(high_math_score) + ' ' + str(english_score) + ' '+ str(sum_score) + ' ' + str(ave_score) + '\n')
class Student(object):
def __init__(self, name, py_score, high_math_score, english_score,sum_score,ave_score):
self.name = name
self.py_score = py_score
self.high_math_score = high_math_score
self.english_score = english_score
self.sum_score = sum_score
self.ave_score = float(ave_score)
def __repr__(self):
return '姓名:%s python成绩:%s 高数成绩:%s 英语成绩:%s 总分:%s 平均分:%.2f' %(self.name,self.py_score,
self.high_math_score,self.english_score,self.sum_score,self.ave_score)
def main():
#创建100个学会信息
create_student_info()
#读取学生信息
with open('score.dat') as f:
AllStudentInfo = [Student(*student_info.split(' ')) for student_info in f.readlines()]
#输出信息
py_score_max = max(AllStudentInfo,key=lambda x:x.py_score).py_score
high_math_score_max = max(AllStudentInfo, key=lambda x: x.high_math_score).high_math_score
english_score_max = max(AllStudentInfo, key=lambda x: x.english_score).english_score
sum_score_sorted = sorted(AllStudentInfo,key=lambda x:x.sum_score,reverse=True)
print('python最高分:%s' %(py_score_max))
print('高数最高分:%s' % (high_math_score_max))
print('英语最高分:%s' % (english_score_max))
print('总分最高分:%s' %(sum_score_sorted[0].sum_score) + '\n')
with open('odered_score.dat','w') as f:
for info in sum_score_sorted:
print(info)
f.write(str(info)+'\n')
with open('odered_score.dat','w+') as f:
conn = pymysql.connect(user = 'root',password = 'westos',charset = 'utf8',db ='student',autocommit = True)
cur = conn.cursor()
info_table = 'create table student(姓名 varchar(20) not null,python成绩 varchar(3),高数成绩 varchar(3),英语成绩 varchar(3),总分 varchar(3),平均分 varchar(5));'
cur.execute(info_table)
for line in f.readlines():
studentInfo_all = [i.split(':') for i in line.split()]
studentInfo= list(chain(*studentInfo_all))[1::2]
insertInfo = "insert into student values('%s', '%s', '%s', '%s', '%s', '%s');" %(
studentInfo[0], studentInfo[1], studentInfo[2], studentInfo[3], studentInfo[4], studentInfo[5])
cur.execute(insertInfo)
cur.close()
conn.close()
if __name__ == '__main__':
main()
知识点复习
题目描述
正整数A和正整数B 的最小公倍数是指 能被A和B整除的最小的正整数值,设计一个算法,求输入A和B的最小公倍数。- 输入描述: 输入两个正整数A和B。
- 输出描述: 输出A和B的最小公倍数。
示例1
- 输入
5
7
- 输出
35
题目描述
Catcher 是MCA国的情报员,他工作时发现敌国会用一些对称的密码进行通信,比如像这些ABBA,ABA,A,123321,但是他们有时会在开始或结束时加入一些无关的字符以防止别国破解。比如进行下列变化 ABBA->12ABBA,ABA->ABAKK,123321->51233214 。因为截获的串太长了,而且存在多种可能的情况(abaaab可看作是aba,或baaab的加密形式),Cathcer的工作量实在是太大了,他只能向电脑高手求助,你能帮Catcher找出最长的有效密码串吗?
(注意:记得加上while处理多个测试用例)- 输入描述:输入一个字符串
- 输出描述:返回有效密码串的最大长度
示例1
- 输入
ABBA - 输出
4