소연의_개발일지
article thumbnail

행맨 게임 만들기

사용함수: random, if, isalpha(), int, random 등

 

1. 코드(hang_man.py)

<python />
import random import os from data import HANGMANPICS, word_list, win_art game_continue = 'y' while game_continue != 'n': life = 7 game_over = 0 # TODO 1. 랜덤으로 나오게 할 문자열을 지정한다. 문자열을 뽑는다. chosen_word = random.choice(word_list) print(chosen_word) #정답 확인용 # TODO 2. 선택한 문자를 글자수를 세서 '_'를 출력한다. blank_answer = [] ##정답이 담길 빈칸 answer_list = [] ##정답이 담길 칸 user_guess_list = [] ##사용자가 유추한 답이 담길 리스트 for j in range(0, len(chosen_word)): blank_answer.append("_") for i in chosen_word: answer_list.append(i) # print(answer_list) # 정답 확인용 # TODO 3. 사용자에게 질문한다. 기회는 총 일곱번 준다. while game_over != 1: print(HANGMANPICS[7 - life]) if len(user_guess_list) == 0: pass else: print(f"지금까지 유추한 단어: {', '.join(user_guess_list)}") print(' '.join(blank_answer)) print(f"기회가 {life}번 남았습니다.") while True: # 예외처리 / 한글 한글자는 예외처리 못함 user_guess = input("글자를 유추하세요: ").lower() if not user_guess.isalpha(): print("문자로 입력하세요") continue if len(user_guess) >= 2: print("한 글자로만 입력하세요") continue else: break user_guess_list.append(user_guess) # TODO 4. 사용자가 유추한 글자 중 하나가 선택된 단어 안에 있으면 출력한다. if user_guess in answer_list: print("맞았습니다!") num = 0 for m in chosen_word: if user_guess == m: blank_answer[num] = m num += 1 print(blank_answer) else: ## 없으면 생명을 하나 잃는다. print("틀렸습니다!") life -= 1 os.system("cls") # TODO 5. 만약 5번의 기회 전에 다 맞추면 성공, 아니면 실피하며 정답을 출력한다. if answer_list == blank_answer: ## if '_' not in blank_answer 로 사용할 수 있을듯 print(win_art) print(f"모두 맞췄습니다! 정답은 {chosen_word}입니다. 당신은 행맨을 구했습니다.") game_over = 1 elif life == 0: print(HANGMANPICS[6]) print("기회를 모두 소진했습니다. 당신은 한 목숨을 떠나보냈습니다...") print(f"게임 종료! 정답은 {chosen_word}이었습니다!") game_over = 1 # TODO 6. 다시 시작할지 묻는다. game_continue = input("다시 하시겠습니까?(y/n): ").lower() if game_continue == 'y': os.system("cls")

 

1.1. data.py

<python />
word_list = [ "account", "act", "adjustment", "advertisement", "agreement", "air", "amount", "amusement", "animal", "answer", "apparatus", "approval", "argument", "art", "attack", "attempt", "attention", "attraction", "authority", "back", "balance", "base", "behavior", "belief", "birth", "bit", "bite", "blood", "blow", "body", "brass", "bread", "breath", "brother", "building", "burn", "burst", "business", "butter", "canvas", "care", "cause", "chalk", "chance", "change", "cloth", "coal", "color", "comfort", "committee", "company", "comparison", "competition", "condition", "connection", "control", "cook", "copper", "copy", "cork", "copy", "cough", "country", "cover", "crack", "credit", "crime", "crush", "cry", "current", "curve", "damage", "danger", "daughter", "day", "death", "debt", "decision", "degree", "design", "desire", "destruction", "detail", "development", "digestion", "direction", "discovery", "discussion", "disease", "disgust", "distance", "distribution", "division", "doubt", "drink", "driving", "dust", "earth", "edge", "education", "effect", "end", "error", "event", "example", "exchange", "existence", "expansion", "experience", "expert", "fact", "fall", "family", "father", "fear", "feeling", "fiction", "field", "fight", "fire", "flame", "flight", "flower", "fold", "food", "force", "form", "friend", "front", "fruit", "glass", "gold", "government", "grain", "grass", "grip", "group", "growth", "guide", "harbor", "harmony", "hate", "hearing", "heat", "help", "history", "hole", "hope", "hour", "humor", "ice", "idea", "impulse", "increase", "industry", "ink", "insect", "instrument", "insurance", "interest", "invention", "iron", "jelly", "join", "journey", "judge", "jump", "kick", "kiss", "knowledge", "land", "language", "laugh", "low", "lead", "learning", "leather", "letter", "level", "lift", "light", "limit", "linen", "liquid", "list", "look", "loss", "love", "machine", "man", "manager", "mark", "market", "mass", "meal", "measure", "meat", "meeting", "memory", "metal", "angle", "ant", "apple", "arch", "arm", "army", "baby", "bag", "ball", "band", "basin", "basket", "bath", "bed", "bee", "bell", "berry", "bird", "blade", "board", "boat", "bone", "book", "boot", "bottle", "box", "boy", "brain", "brake", "branch", "brick", "bridge", "brush", "bucket", "bulb", "button", "cake", "camera", "card", "carriage", "cart", "cat", "chain", "cheese", "chess", "chin", "church", "circle", "clock", "cloud", "coat", "collar", "comb", "cord", "cow", "cup", "curtain", "cushion", "dog", "door", "drain", "drawer", "dress", "drop", "ear", "egg", "engine", "eye", "face", "farm", "feather", "finger", "fish", "flag", "floor", "fly", "foot", "fork", "fowl", "frame", "garden", "girl", "glove", "goat", "gun", "hair", "hammer", "hand", "hat", "head", "heart", "hook", "horn", "horse", "hospital", "house", "island", "jewel", "kettle", "key", "middle", "milk", "mind", "mine", "minute", "mist", "money", "month", "morning", "mother", "motion", "mountain", "move", "music", "name", "nation", "need", "news", "night", "noise", "note", "number", "observation", "offer", "oil", "operation", "opinion", "order", "organization", "ornament", "owner", "page", "pain", "paint", "paper", "part", "paste", "payment", "peace", "person", "place", "plant", "play", "pleasure", "point", "poison", "polish", "porter", "position", "powder", "power", "price", "print", "process", "produce", "profit", "property", "prose", "protest", "pull", "punishment", "purpose", "push", "quality", "question", "rain", "range", "rate", "ray", "reaction", "reading", "reason", "record", "regret", "relation", "religion", "representative", "request", "respect", "rest", "reward", "rhythm", "rice", "river", "road", "roll", "room", "rub", "rule", "run", "salt", "sand", "scale", "science", "sea", "seat", "secretary", "selection", "self", "sense", "servant", "shade", "shake", "shame", "shock", "side", "sign", "silk", "silver", "sister", "size", "sky", "sleep", "slip", "slope", "smash", "smell", "smile", "smoke", "sneeze", "snow", "soap", "society", "son", "song", "sort", "sound", "soup", "space", "stage", "start", "statement", "steam", "steel", "step", "stitch", "stone", "stop", "story", "stretch", "structure", "substance", "sugar", "suggestion", "summer", "support", "surprise", "swim", "system", "talk", "taste", "tax", "teaching", "tendency", "test", "theory", "thing", "thought", "thunder", "time", "tin", "top", "touch", "trade", "transport", "trick", "trouble", "turn", "twist", "unit", "use", "value", "verse", "vessel", "view", "voice", "walk", "war", "wash", "waste", "water", "wave", "wax", "way", "weather", "week", "weight", "wind", "wine", "winter", "woman", "wood", "wool", "word", "work", "wound", "writing", "year", "knee", "knife", "knot", "leaf", "leg", "library", "line", "lip", "lock", "map", "match", "monkey", "moon", "mouth", "muscle", "nail", "neck", "needle", "nerve", "net", "nose", "nut", "office", "orange", "oven", "parcel", "pen", "pencil", "picture", "pig", "pin", "pipe", "plane", "plate", "plough", "pocket", "pot", "potato", "prison", "pump", "rail", "rat", "receipt", "ring", "rod", "roof", "root", "sail", "school", "scissors", "screw", "seed", "sheep", "shelf", "ship", "shirt", "shoe", "skin", "skirt", "snake", "sock", "spade", "sponge", "spoon", "spring", "square", "stamp", "star", "station", "stem", "stick", "stocking", "stomach", "store", "street", "sun", "table", "tail", "thread", "throat", "thumb", "ticket", "toe", "tongue", "tooth", "town", "train", "tray", "tree", "trousers", "umbrella", "wall", "watch", "wheel", "whip", "whistle", "window", "wing", "wire", "worm", ] win_art = """ _ ( (( \\ =\\ __\\_ `-\\ (____))( \\---- (____)) _ (____)) (____))____/---- """ HANGMANPICS = [''' +---+ | | | | | | =========''', ''' +---+ | | O | | | | =========''', ''' +---+ | | O | | | | | =========''', ''' +---+ | | O | /| | | | =========''', ''' +---+ | | O | /|\ | | | =========''', ''' +---+ | | O | /|\ | / | | =========''', ''' +---+ | | O | /|\ | / \ | | =========''']

 

data.py
0.01MB
han_man.py
0.00MB

 

 

2. 실행화면

게임 맞았을 때

게임 틀렸을 때

 

 

 

2.1. 행맨 만들면서 만난 문제: 예외처리

한글 여러글자나 영어 여러글자는 isalpha()와 len()으로 처리할 수 있는데

한글 한글자는 예외처리하는 방법을 찾지 못했다.

 

 

profile

소연의_개발일지

@ssoyxon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!