473,385 Members | 1,528 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Help for creating a hangman game

8
Hi,

I'm trying to make a hangman game that should look like this:

Welcome to Hangman
______
Your guess: c
Success!
__cc__
Your guess: b
Failure! You have tried tried 1 times!
__cc__
.
.
.
Your guess: r
Success!
soccer
You won!

etc

In this game I'm trying to make it so that I first need to give a file - where game takes words - at commandline as a parameter to game. I've done that so far that program takes randomly a word from a certain file (here words.txt), prints blanks as a hintword and starts asking letters. My problem is that I can't make the program to check for the letters in word and replace blanks with guessed letter.

So far my code looks like that:

Expand|Select|Wrap|Line Numbers
  1. import sys
  2.  
  3. if sys.argv[1] == 'words.txt':
  4.     list = open('words.txt','r')
  5.     a = list.readlines()
  6.  
  7.     import random
  8.  
  9.     b = random.choice(a)
  10.  
  11.     print 'Welcome to Hangman'
  12.     c = '_'*(len(b)-1)
  13.     print c
  14.     for i in range(1,6):
  15.         mark = raw_input('Your guess: ')
  16.         check = b.find(mark)
  17.         if check != -1:
  18.             print 'Succes!', mark, 'is in word at position', check
  19.             c = c[:check] + mark + c[check + 1:]
  20.             print c
  21.         else:
  22.             print 'Failure! You have tried tried %d times!' %(i)
  23.  
  24. else:
  25.     print '[Errno2] No such file or directory: %s' %(sys.argv[1])
  26.  
Can anyone tell me how to solve this problem? Sorry for the dots, but I didn't know any other way to get that structure showing right.

Edit: Thanks for the tip. I edited the code to show right :)
Nov 13 '08 #1
8 3728
boxfish
469 Expert 256MB
I haven't taken a look at your problem yet, but you can enclose your code in code tags, [CODE] and [/CODE], and the parser won't eat the indentation.
Edit:
Thanks, that's much better.
Nov 13 '08 #2
boxfish
469 Expert 256MB
For some reason, you can't replace a character in a string with another character. The only way I know to get around this is to slice the string into two pieces and put the new character between them. It seems like there must be a better way to do this, but here it is:
Expand|Select|Wrap|Line Numbers
  1. c = c[:check] + mark + c[check + 1:]
And list is a reserved word. You shouldn't be using it as a variable name.
Hope this helps.
Nov 13 '08 #3
tidiz
8
Thanks for the help. It helped to replace those blanks with letters, but now I encountered a new one problem. If we have a word "soccer" and we are guessing the letter "c", program only takes the first letter and converts it, but not the other c. So here we would end in result "__c___". So in the end we will have result "soc_er".

I edited the current code for the first post.
Nov 13 '08 #4
boxfish
469 Expert 256MB
How about replacing the letters from b with underlines after they have been guessed?
Edit:
Never mind, that would make the user have to guess the same letter more than once.
Nov 13 '08 #5
tidiz
8
I think I need to fix that find-structure so that program wont stop finding at the first hit, but also checks the whole word for hits. Any recommendations for how to do this would be great as I am not very skilled with python... yet :)
Nov 13 '08 #6
boxfish
469 Expert 256MB
I have a book on Python with a hangman game example in it. It works something like
Expand|Select|Wrap|Line Numbers
  1. Clear out c.
  2. For each letter in b:
  3.     If the letter is equal to mark:
  4.         Add mark to c.
  5.     Else:
  6.         Add a blank to c.
Hope this helps.
Edit:
Sorry, still won't work. Try it like this:
Expand|Select|Wrap|Line Numbers
  1. Create a new string.  Let's call it new_c.
  2. For each letter in b:
  3.     If the letter is equal to mark:
  4.         Add mark to new_c.
  5.     Else:
  6.         Add a letter from the old c to new_c.
  7. Replace c with new_c.
Nov 13 '08 #7
bvdet
2,851 Expert Mod 2GB
This returns a list of indexes of letter in word s:
Expand|Select|Wrap|Line Numbers
  1. def idxList(s, letter, idx=0):
  2.     ''' Return a list of indices of "letter" in string "s".'''
  3.     if not type(s) == str:
  4.         raise AttributeError, 'Argument 0 must be a string'
  5.     idxList = []
  6.     while True:
  7.         idx = s.find(letter, idx)
  8.         if idx == -1:
  9.             return idxList
  10.         idxList.append(idx)
  11.         idx += 1
Example:
>>> idxList('mississippi', 's')
[2, 3, 5, 6]
>>>

To substitute the letters in the hint string, create a list of letters:

Expand|Select|Wrap|Line Numbers
  1. list(hint_string)
Iterate on the indexes list, and assign the list item to letter.

Expand|Select|Wrap|Line Numbers
  1. string_list[idx] = letter
Join the letters to form the new hint string:

Expand|Select|Wrap|Line Numbers
  1. ''.join(string_list)
Nov 13 '08 #8
tidiz
8
Hi,

Thanks to you all for help. Somehow I wasn't able to make my code working exactly how you suggested, so I made it in different way. Maybe this coding isn't the best possible, but at least this works :)

Expand|Select|Wrap|Line Numbers
  1. import sys
  2.  
  3. if sys.argv[1] == 'words.txt':
  4.     list1 = open('words.txt','r')
  5.     list2 = []
  6.     for word in list1.readlines():
  7.         sana = word.replace('\n','')
  8.         list2.append(sana)
  9.  
  10.     import random
  11.  
  12.     b = random.choice(list2)
  13.  
  14.     print 'Welcome to Hangman'
  15.     hint = '_'*len(b)
  16.     print hint
  17.  
  18.     counter = 0
  19.  
  20.     while counter < 5:
  21.         if hint == b:
  22.             print 'You win!'
  23.             print 'Goodbye'
  24.             break
  25.         else:
  26.             pass
  27.         mark = raw_input('Your guess: ')
  28.         if mark == '':
  29.             counter += 1
  30.             print 'Failure! You have tried tried %d times!' %(counter)
  31.         else:
  32.             counter2 = 0
  33.             if mark in hint:
  34.                 counter += 1
  35.                 print 'Failure! You have tried tried %d times!' %(counter)
  36.                 print hint
  37.             elif mark in b:
  38.                 print 'Success!'
  39.                 for i in b:
  40.                     if mark == i:
  41.                         x = list(hint)
  42.                         x[counter2] = mark
  43.                         hint = "".join(x)
  44.                     counter2 += 1
  45.                 if hint != b:
  46.                     print hint
  47.                 else:
  48.                     pass
  49.             else:
  50.                 counter += 1
  51.                 print 'Failure! You have tried tried %d times!' %(counter)
  52.                 if counter != 5:
  53.                     print hint
  54.                 else:
  55.                     pass
  56.  
  57.     else:
  58.         print 'Game over! you lose!'
  59.         print 'The word was %s' %(b)
  60.         print 'Goodbye'
  61.  
  62. else:
  63.     print "[Errno 2] No such file or directory: '%s'" %(sys.argv[1])
  64.  
Nov 25 '08 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: rainbowii7 | last post by:
Calling all programmers for helllllllllllllllppppp!!! i am currently doing a uni degree and our lecturers have set us the task of making a game in JavaScript. i chose to do a hangman game and...
5
by: tigrfire | last post by:
So I'm trying to write a hangman game and the output is coming out a little strange. Here's my code thus far: #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> ...
4
by: princessfrost | last post by:
Hi! I was wondering if someone could please help me with a hangman program that I have to do. I have some ideas, but really don't know what to do or where to start. My program needs to be:...
47
by: araujo2nd | last post by:
Originally Posted by araujo2nd my name is andre, im from south africa, i was wondering if any1 could help me with a hangman application, im now in grade 11 and have a huge portfolio piece to do by...
3
by: kaka_hunter | last post by:
#include <iostream> #include <fstream> using namespace std; const int max_tries=7; int earnings=0; int wordnum; void getword () { ifstream fin;
5
by: av3rage | last post by:
I have never done any programming in my life but I have decided to go into engineering and in doing so we have to take this intro to programming course and I am pretty clueless. I am starting to get...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.