프로그램 이야기/Python 이야기
Python으로 만드는 간단한 영어 단어 맞추는 게임
야생의개발자
2008. 12. 15. 18:14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
| import random
class confuse:
__dic = {
"apple":"사과","airplane":"비행기","zoo":"동물원",
"beauty":"미인","handsome":"잘생긴","monster":"괴물",
"sun":"태양","test":"연습, 실험","level":"단계",
"human":"사람","rock":"바위","love":"사랑",
"lover":"연인","classic":"오래된, 고전의","mouse":"쥐"
}
__list = []
def __init__(self):
self.__list = []
for x in self.__dic:
self.__list.append(x)
def printlist(self):
return self.__list
def insertword(self,word,detail):
self.__dic[word] = detail
self.__list = []
for x in self.__dic:
self.__list.append(x)
def searchword(self,word):
try:
searchValue = self.__dic[word]
except KeyError:
return "NULL"
else:
return searchValue
def chooseword(self):
random.shuffle(self.__list)
string = self.__list[0]
strlist = []
for x in string:
strlist.append(x)
random.shuffle(strlist)
strshuffle = ""
for x in strlist:
strshuffle += x
return [strshuffle,string,self.__dic[string]]
def delword(self,word):
del self.__dic[word]
self.__list=[]
for x in self.__dic:
self.__list.append(x)
game = confuse()
while 1:
print "\n\n===== !Confuse! ====="
print "SELECT ---> 1. START"
print " 2. INSERT"
print " 3. PRINT"
print " 4. DELETE"
print " 0. EXIT"
print "====================="
sel = raw_input(" >")
print ""
if(sel == "1"):
exam = game.chooseword()
print "===== EXAM =====".center(20)
print exam[0].center(20)
print "================".center(20)
print exam[2].center(20)
print "================".center(20)
tt = raw_input("답 >")
print ""
if(tt == exam[1]):
print "정답!!"
else:
print "오답!!"
elif(sel == "2"):
t1 = raw_input("영 단어 : ")
t2 = raw_input("뜻 : ")
if(game.searchword(t1) != "NULL"):
print "입력된 단어입니다."
else:
print "단어를 입력합니다."
game.insertword(t1,t2)
elif(sel == "3"):
print game.printlist()
elif(sel == "4"):
tt = raw_input("지울 단어 : ")
if(game.searchword(tt) == "NULL"):
print "지울 단어는 없습니다."
else:
print "단어를 지웁니다."
game.delword(tt)
elif(sel == "0"):
print "게임을 끝냅니다."
break; |
클래스를 사용하는 가장 중요한 이유는 재사용성과 코딩의 편리함이 주요 목적이다.
보안 성도 많이 향상되고, 한번 잘 만든 클래스는 코딩할 때 많은 편리함을 준다.
confuse 클래스 안에는 private 요소가 두 가지 존재한다. __dic과 __list인데, 딱 봐도 무슨 형태인지 알 수 있다. 사전형(혹은 해쉬)와 리스트 형태이다.
사전형이야 기본적인 문제 제출 정보들이 담겨 있는 곳이고, 리스트는 문제를 내기 위해 혹은 출력하기 위해서 만들어 놓은 것이다.
사전형을 사용할 때 내가 찾을 키가 없으면, KeyError exception을 호출하는 사실을 숙지하자.
영어 단어를 받아서 섞을 때 주의할 점은 Python에서는 문자열 변경허용을 하지 않아서, 위와 같은 형태로 분해한 다음 섞은 후 다시 붙이는 과정을 거쳤다.
더 좋은 방법이 있으면 댓글로...
문자열에 center(number)를 적게 되면 number의 크기만큼 공간을 잡아서 그곳 중앙에 출력하게 되는 그러한 메소드 이다. rjust, ljust 각각 우측, 좌측 정렬이다.