Python 记忆游戏的代码优化
我为班级制作了这个记忆卡匹配游戏,感觉我写的代码比我必须写的要多。有没有办法优化这个?作业只是为了得到一个工作程序,但我觉得我需要学习一点优化Python 记忆游戏的代码优化,python,Python,我为班级制作了这个记忆卡匹配游戏,感觉我写的代码比我必须写的要多。有没有办法优化这个?作业只是为了得到一个工作程序,但我觉得我需要学习一点优化 import random class Card(object): """ A card object with value but not suit""" def __init__(self, value): """Creates a card with the given value and suit."""
import random
class Card(object):
""" A card object with value but not suit"""
def __init__(self, value):
"""Creates a card with the given value and suit."""
self.value = value
self.face = 0
def showFace(self):
'''flips the card over'''
self.face = 1
def __str__(self):
"""Returns the string representation of a card."""
return str(self.value)
class Deck(object):
""" A deck containing cards."""
def __init__(self, rows, columns):
"""Creates a full deck of cards."""
self._cards = []
self._rows = rows
self._columns = columns
for value in range(1,(int((self._rows*self._columns)/2))+1):
c = Card(value)
self._cards.append(c)
self._cards.append(c)
def shuffle(self):
"""Shuffles the cards."""
random.shuffle(self._cards)
def deal(self):
"""Removes and returns the top card or None
if the deck is empty."""
if len(self) == 0:
return None
else:
return self._cards.pop(0)
def __len__(self):
"""Returns the number of cards left in the deck."""
return len(self._cards)
def __str__(self):
"""Returns the string representation of a deck."""
self.result = ''
for c in self._cards:
self.result = self.result + str(c) + '\n'
return self.result
class Game(Deck,Card):
'''Runs the memory game'''
def __init__(self, rows, columns):
'''gets rows and columns for the game'''
self._rows = rows
self._columns = columns
def play(self):
'''starts the game'''
self._deck = Deck(self._rows, self._columns)
self._deck.shuffle()
Game.populateBoard(self)
matches = 0
#While the game is not finished
while True:
while True: #The First Card
try:
coor1 = input("Enter coordinates for first card ")
coor1 = coor1.split(' ') # Removes spaces
coor1 = [x for x in coor1 if x != ' '] # puts in list
coor1 = [int(x)-1 for x in coor1 if x == x] # converts
except IndexError:
print('***Invalid coordinates! Try again.***')
except ValueError:
print('***Invalid coordinates! Try again.***')
else:
try: #Check if coordinates are valid
if 0 > coor1[0] or coor1[0] > self._rows\
or 0 > coor1[1] or coor1[1] > self._columns:
print('***Invalid coordinates! Try again.***')
else:
guess1 = self._gameboard[coor1[0]][coor1[1]]
break
except IndexError:
print('***Invalid coordinates! Try again.***')
while True: # The Second Card
try:
coor2 = input("Enter coordinates for second card ")
coor2 = coor2.split(' ') # Removes Spaces
coor2 = [x for x in coor2 if x != ' '] # puts in list
coor2 = [int(x)-1 for x in coor2 if x == x]# converts
except IndexError:
print('***Invalid coordinates! Try again.***')
except ValueError:
print('***Invalid coordinates! Try again.***')
else:
try: #Check if coordinates are valid
if 0 > coor2[0] or coor2[0] > self._rows\
or 0 > coor2[1] or coor2[1] > self._columns:
print('***Invalid coordinates! Try again.***')
else:
guess2 = self._gameboard[coor2[0]][coor2[1]]
break
except IndexError:
print('***Invalid coordinates! Try again.***')
if guess1 == guess2\
and coor2[0]-coor1[0] == 0\
and coor2[1]-coor1[1] == 0:#User enters same input for 1 and 2
print("***That's the same card! Try again.***")
elif guess1 == guess2:
guess1.showFace()
Game.showBoard(self)
matches += 1
if matches == ((self._rows * self._columns)/2):
break
else:
Game.showBoard(self)
print('Not an identical pair. Found',guess1,'at ('+
str(coor1[0]+1)+','+ str(coor1[1]+1)+') and', guess2,
'at ('+str(coor2[0]+1)+','+str(coor2[1]+1)+')')
def populateBoard(self):
'''populates the game board'''
self._gameboard = []
for row in range(self._rows):
self._gameboard.append([0] * self._columns)
for row in range(len(self._gameboard)):
for column in range(len(self._gameboard[row])):
self._gameboard[row][column] = self._deck.deal()
Game.showBoard(self)
def showBoard(self):
'''shows the board'''
for row in self._gameboard:
for card in row:
if card.face == 0:
print('*', end =" ")
else:
print(card, end= " ")
print()
def main():
while True:
# Force user to enter valid value for number of rows
while True:
rows = input("Enter number of rows ")
if rows.isdigit() and ( 1 <= int(rows) <= 9):
rows = int(rows)
break
else:
print (" ***Number of rows must be between 1 and 9! Try again.***")
# Adding *** and indenting error message makes it easier for the user to see
# Force user to enter valid value for number of columns
while True:
columns = input("Enter number of columns ")
if columns.isdigit() and ( 1 <= int(columns) <= 9):
columns = int(columns)
break
else:
print (" ***Number of columns must be between 1 and 9! Try again.***")
if rows * columns % 2 == 0:
break
else:
print (" ***The value of rows X columns must be even. Try again.***")
game = Game(rows, columns)
game.play()
if __name__ == "__main__":
main()
随机导入
类别卡(对象):
“”“有价值但不适合的卡对象”“”
定义初始值(自身,值):
“”“创建具有给定值和套色的卡。”“”
自我价值=价值
self.face=0
def showFace(自我):
“把卡片翻过来”
self.face=1
定义(自我):
“”“返回卡的字符串表示形式。”“”
返回str(self.value)
类甲板(对象):
“包含卡片的卡片组。”
定义初始化(self、行、列):
“”“创建一整套卡片。”“”
自助卡=[]
self.\u行=行
self.\u列=列
对于范围(1,(int((self.\u行*self.\u列)/2))中的值+1):
c=卡(值)
自我介绍卡。附加(c)
自我介绍卡。附加(c)
def随机播放(自):
“洗牌。”
随机。洗牌(自选卡)
def交易(自我):
“”“删除并返回最上面的卡,或者不返回
如果甲板是空的
如果len(self)==0:
一无所获
其他:
返回自我。\u卡。弹出(0)
定义(自我):
“”“返回牌组中剩余的牌数。”“”
返回len(自卡)
定义(自我):
“”“返回组的字符串表示形式。”“”
self.result=“”
对于自助卡中的c:
self.result=self.result+str(c)+'\n'
返回自我结果
班级游戏(套牌、纸牌):
“运行记忆游戏”
定义初始化(self、行、列):
''获取游戏的行和列''
self.\u行=行
self.\u列=列
def播放(自我):
“开始游戏”
self.\u deck=deck(self.\u行、self.\u列)
self._deck.shuffle()
游戏。大众板(自我)
匹配项=0
#游戏还没结束
尽管如此:
正确时:#第一张牌
尝试:
coor1=输入(“输入第一张卡的坐标”)
coor1=coor1.split(“”)#删除空格
coor1=[x代表coor1中的x,如果x!=''']#放入列表
coor1=[int(x)-1表示coor1中的x,如果x==x]#转换
除索引器外:
打印('***坐标无效!请重试。***')
除值错误外:
打印('***坐标无效!请重试。***')
其他:
try:#检查坐标是否有效
如果0>coor1[0]或coor1[0]>self.\u行\
或0>coor1[1]或coor1[1]>self.\u列:
打印('***坐标无效!请重试。***')
其他:
猜1=self.\u游戏板[coor1[0]][coor1[1]]
打破
除索引器外:
打印('***坐标无效!请重试。***')
如果为True:#第二张牌
尝试:
coor2=输入(“输入第二张卡的坐标”)
coor2=coor2.split(“”)#删除空格
coor2=[x代表coor2中的x,如果x!='']#放入列表
coor2=[int(x)-1表示coor2中的x,如果x==x]#转换
除索引器外:
打印('***坐标无效!请重试。***')
除值错误外:
打印('***坐标无效!请重试。***')
其他:
try:#检查坐标是否有效
如果0>coor2[0]或coor2[0]>self.\u行\
或0>coor2[1]或coor2[1]>self.\u列:
打印('***坐标无效!请重试。***')
其他:
猜2=self.\u游戏板[coor2[0]][coor2[1]]
打破
除索引器外:
打印('***坐标无效!请重试。***')
如果猜测1==猜测2\
和coor2[0]-coor1[0]==0\
和coor2[1]-coor1[1]==0:#用户为1和2输入相同的输入
打印(“***这是同一张卡!请重试。***”)
elif guess1==guess2:
猜1.showFace()
游戏展示板(自我)
匹配项+=1
如果匹配==((self.\u行*self.\u列)/2):
打破
其他:
游戏展示板(自我)
打印('不是一对。找到',猜测1,'at('+
str(coor1[0]+1)+'、'+str(coor1[1]+1)+')和',2,
‘at(‘+str(coor2[0]+1)+’,‘+str(coor2[1]+1)+’)
def populateBoard(自):
“填充游戏板”
self._gameboard=[]
对于范围内的行(自身行):
self.\u gameboard.append([0]*self.\u列)
对于范围内的行(len(self.\u gameboard)):
对于范围内的列(len(self.\u gameboard[行]):
self.\u gameboard[行][列]=self.\u deck.deal()
游戏展示板(自我)
def展示板(自):
“显示板”
对于self.\u gameboard中的行:
对于行中的卡:
如果card.face==0:
打印(“*”,end=“”)
其他:
打印(卡片,结束=“”)
打印()
def main():
尽管如此:
#强制用户为行数输入有效值
尽管如此:
行=输入(“输入行数”)
如果rows.isdigit()和(1这里有几个地方可以简化代码
def populateBoard(self):
'''populates the game board'''
self._gameboard = [self._deck.deal() for row in self._rows
for column in self._columns]
self.showBoard()
及
def showBoard(self):
'''shows the board'''
for row in self._gameboard:
print(*(card if card.face else '*' for card in row))