1

in my code I have text file that I have to read word randomly from it to play hangman but it does not work properly since it makes my game crash because sometimes it generates an empty word instead of selecting one so when I run it sometimes it just says you are a winner and finishes the game . It would be great if you tell me what I am doing wrong.

My code :

import random
import pygame
import math

pygame.init()
WIDTH , HIGHT =800,500
win=pygame.display.set_mode((WIDTH,HIGHT))
pygame.display.set_caption("hangman")

#button variables
RADIUS =20
GAP=15
letters=[]
startx=round((WIDTH-(RADIUS*2+GAP)*13)/2)
starty=400
A=97
for i in range(26):
    x=startx + GAP* 2+ ((RADIUS*2+GAP) * (i % 13))
    y=starty +((i // 13) * (RADIUS*2 + GAP))
    letters.append([x,y,chr(A+i),True])


#Fonts
LETTER_FONT=pygame.font.SysFont('comicsans',40)
WORD_FONT=pygame.font.SysFont('comicsans',50)
TITLE_FONT=pygame.font.SysFont('comicsans',60)
#loading images
image={0:pygame.image.load(r'C:\Users\kimia\PycharmProjects\pythonProject1\images\hangman0.png'),1:pygame.image.load(r'C:\Users\kimia\PycharmProjects\pythonProject1\images\hangman1.png'),
           2:pygame.image.load(r'C:\Users\kimia\PycharmProjects\pythonProject1\images\hangman2.png'),3:pygame.image.load(r'C:\Users\kimia\PycharmProjects\pythonProject1\images\hangman3.png'),
           4:pygame.image.load(r'C:\Users\kimia\PycharmProjects\pythonProject1\images\hangman4.png'),5:pygame.image.load(r'C:\Users\kimia\PycharmProjects\pythonProject1\images\hangman5.png'),
           6:pygame.image.load(r'C:\Users\kimia\PycharmProjects\pythonProject1\images\hangman6.png')}

hangman_status=0
for i in image:
    if i ==hangman_status:
        images=image.get(i)



#game variables
WHITE=(255,255,255)
BLACK=(0,0,0)
file=open('example.txt')
contents = file.read().splitlines()
word=random.choice(contents)
guessed =[]


#set up of loop
FPS=60
clock=pygame.time.Clock()
run=True


#draw
def draw():
    win.fill(WHITE)
    text=TITLE_FONT.render("Let's hang the man bud!",1,BLACK)
    win.blit(text, (WIDTH/2 - text.get_width()/2, 20))
    #draw word
    display_word=''
    for letter in word:
        if letter in guessed:
            display_word+=letter +" "
        else:
            display_word+="* "
    text=WORD_FONT.render(display_word,1,BLACK)
    win.blit(text,(400,200))


    #buttions
    for letter in letters:
        x,y,ltr , visible=letter
        if visible:
            pygame.draw.circle(win,BLACK,(x,y),RADIUS,3)
            text=LETTER_FONT.render(ltr,1,BLACK)
            win.blit(text,(x-text.get_width()/2,y-text.get_height()/2))

    win.blit(images,(100,100))
    pygame.display.update()
#making a def since it is drier

def display_message(message):
    pygame.time.delay(1000)
    win.fill(WHITE)
    text = WORD_FONT.render(message, 1, BLACK)
    win.blit(text, (WIDTH / 2 - text.get_width() / 2, HIGHT / 2 - text.get_height() / 2))
    pygame.display.update()
    pygame.time.delay(3000)


def hangman():
    global hangman_status
    global images
    # set up of loop
    FPS = 60
    clock = pygame.time.Clock()
    run=True
    while run:
        clock.tick(FPS)

        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                run=False
            if event.type==pygame.MOUSEBUTTONDOWN:
                m_x,m_y=pygame.mouse.get_pos()
                for letter in letters:
                    x, y, ltr , visible= letter
                    if visible:
                        dis=math.sqrt((x-m_x)**2 + (y-m_y)**2)
                        if dis < RADIUS:
                            letter[3]=False
                            guessed.append(ltr)
                            if ltr not in word:
                                hangman_status+=1
                                if hangman_status in image:
                                    images = image.get(hangman_status)

        draw()
        won=True
        for letter in word:
                if letter not in guessed:
                    won=False
                    break
        if won:
                display_message("YOUUU WON!")
                break
        if hangman_status==6:
                display_message("YOU ARE A LOSER!")
                break






hangman()
pygame.quit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
kimia
  • 49
  • 7
  • Please add the error log to the question. – Rabbid76 Jun 06 '21 at 10:47
  • You can add all the words to a list and then use ```random.choice``` to randomly select a word –  Jun 06 '21 at 10:47
  • 1
    @Sujay That is exactly what he does in his code. See the code: `random.choice(contents)` – Rabbid76 Jun 06 '21 at 10:49
  • 1
    Maybe you have empty lines in your example.txt, print out and inspect your contents variable and see if there is anything wrong there first. – Terra Jun 06 '21 at 10:49
  • @Terra,@Rabbid , it does not show an error just it does not work they way I want , in each line of my file I only have one word when I use read().strip('\n') it shows me the what I have in the file correctly but when I use random it only chooses one letter at a time instead of the whole word and with other methods it shows an empty line or something – kimia Jun 06 '21 at 11:01
  • @kima--what was the result of following Terra's advice of checking that there are no blank lines in the file (possibly at the end after the words)? – DarrylG Jun 06 '21 at 11:28
  • @DarrylG ,@Terra,@Rabbid76, Terra was right. I had to remove them. thank you all for your help. – kimia Jun 06 '21 at 11:35

1 Answers1

1

I found the answer , I just needed to change my code in this way to get rid of those empty ones :

'''

file=open('example.txt')
contents = file.read().splitlines()
contents = [i for i in contents if i != '' and i != ', ']
word=random.choice(contents)

'''

kimia
  • 49
  • 7
  • 1
    This is why it would have been good to post your data since apparently, you have blank lines and commas in your text file when you claimed there were only words. – DarrylG Jun 06 '21 at 11:32
  • 2
    As a suggestion, It's a good practice to close your files or use a file manager as noted by [Is explicitly closing files important?](https://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important) – DarrylG Jun 06 '21 at 12:17
  • @DarrylG, there were only words and I claimed it since I myself made the text file but when I printed contents I realized empty ones in the list shown in the output. – kimia Jun 06 '21 at 15:02