Introducción
Se esta estudiando un curso de python y se requiere realizar un juego del ahorcado.La manera que vamos a resolver es de la siguiente manera en una archivo llamado pregunta.txt vamos a colocar 11 preguntas y respuestas se pondra en primera columna la pregunta y de separador se utilizar un pie "|" en la segunda se colocará la respuesta de la pregunta y así sucesivamente en cada fila o renglón hasta llegar a los 11. Se utilizara la interfaz gráfica pygame y siete imagenes que mostrarán al ahorcado en caso de fallar a la respuesta.Requisitos
- Python
- pygame
- pycharm
Desarrollo
Creamos un proyecto que se llame Ahorcado
Agragamos la librería pygame
Nos vamos a File y seleccionamos Settings...

Selecionamos Python Interpreter selecionamos el proyecto y en el signo de + agragamos la dependencia


El paso que sigue es decargar las imagenes las descargamos presionando el siguiente link: Descomprimimos el archivo y pegamos los en el proyecto quedando así

Creamos el archivo pregunta.txt y escribimos el siguiente código
A que estado pertenece el municipio de Tequila|a jalisco
Cual es el fruto vegetal de mayor tamano|sandia
Que nombre generico se le da a todos indigenas de USA y canada|pieles rojas
Que heroe de la mitologia griega se robo el fuego de cielo para darselo al hombre|prometeo
Cual es el deporte nacional de USA|beisbol
Cual fue el primer vehiculo que uso motor de combustion interna|automovil
Como se llama la expresion monetaria del valor de mercancia o servicio|precio
Como se llamaban las unidades militares en que estaba dividido el ejercito romano|legiones
Cuales son los insectos mas bellos|las mariposas
De que pais asiatico es capital Pyongyang|corea del norte
Que se produce en un ingenio|azucar
#########################################################
## File Name: hangman.py ##
## Description: Starter for Hangman project - ICS3U ##
#########################################################
import pygame
import random
pygame.init()
winHeight = 480
winWidth = 1200
win=pygame.display.set_mode((winWidth,winHeight))
#---------------------------------------#
# initialize global variables/constants #
#---------------------------------------#
BLACK = (0,0, 0)
WHITE = (255,255,255)
RED = (255,0, 0)
GREEN = (0,255,0)
BLUE = (0,0,255)
LIGHT_BLUE = (102,255,255)
btn_font = pygame.font.SysFont("arial", 20)
guess_font = pygame.font.SysFont("monospace", 24)
lost_font = pygame.font.SysFont('arial', 25)
word = ''
buttons = []
guessed = []
hangmanPics = [pygame.image.load('hangman0.png'), pygame.image.load('hangman1.png'), pygame.image.load('hangman2.png'), pygame.image.load('hangman3.png'), pygame.image.load('hangman4.png'), pygame.image.load('hangman5.png'), pygame.image.load('hangman6.png')]
limbs = 0
def redraw_game_window(pregunta):
global guessed
global hangmanPics
global limbs
win.fill(GREEN)
labelPregunta = lost_font.render(pregunta, 1, BLACK)
win.blit(labelPregunta, (winWidth / 2 - labelPregunta.get_width() / 2,100))
# Buttons
for i in range(len(buttons)):
if buttons[i][4]:
pygame.draw.circle(win, BLACK, (buttons[i][1], buttons[i][2]), buttons[i][3])
pygame.draw.circle(win, buttons[i][0], (buttons[i][1], buttons[i][2]), buttons[i][3] - 2
)
label = btn_font.render(chr(buttons[i][5]), 1, BLACK)
win.blit(label, (buttons[i][1] - (label.get_width() / 2), buttons[i][2] - (label.get_height() / 2)))
spaced = spacedOut(word, guessed)
label1 = guess_font.render(spaced, 1, BLACK)
rect = label1.get_rect()
length = rect[2]
win.blit(label1,(winWidth/2 - length/2, 400))
pic = hangmanPics[limbs]
win.blit(pic, (winWidth/2 - pic.get_width()/2 + 20, 150))
pygame.display.update()
def randomWord():
file = open('pregunta.txt')
f = file.readlines()
i = random.randrange(0, len(f) - 1)
frase1,frase2=f[i][:-1].strip().split('|',1)
return frase1,frase2
def hang(guess):
global word
if guess.lower() not in word.lower():
return True
else:
return False
def spacedOut(word, guessed=[]):
spacedWord = ''
guessedLetters = guessed
for x in range(len(word)):
if word[x] != ' ':
spacedWord += '_ '
for i in range(len(guessedLetters)):
if word[x].upper() == guessedLetters[i]:
spacedWord = spacedWord[:-2]
spacedWord += word[x].upper() + ' '
elif word[x] == ' ':
spacedWord += ' '
return spacedWord
def buttonHit(x, y):
for i in range(len(buttons)):
if x < buttons[i][1] + 20 and x > buttons[i][1] - 20:
if y < buttons[i][2] + 20 and y > buttons[i][2] - 20:
return buttons[i][5]
return None
def end(pregunta, winner = False):
global limbs
lostTxt = 'Lo siento perdiste! ,presiona una tecla para continuar.'
winTxt = 'FELICIDADES GANASTE!, presiona una tecla para continuar...'
redraw_game_window(pregunta)
pygame.time.delay(1000)
win.fill(GREEN)
if winner == True:
label = lost_font.render(winTxt, 1, BLACK)
else:
label = lost_font.render(lostTxt, 1, BLACK)
wordTxt = lost_font.render(word.upper(), 1, BLACK)
wordWas = lost_font.render('La frase fue: ', 1, BLACK)
win.blit(wordTxt, (winWidth/2 - wordTxt.get_width()/2, 295))
win.blit(wordWas, (winWidth/2 - wordWas.get_width()/2, 245))
win.blit(label, (winWidth / 2 - label.get_width() / 2, 140))
pygame.display.update()
again = True
while again:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
again = False
reset()
def reset():
global limbs
global guessed
global buttons
global word
global pregunta
for i in range(len(buttons)):
buttons[i][4] = True
limbs = 0
guessed = []
pregunta,word = randomWord()
#MAINLINE
# Setup buttons
increase = round(winWidth / 13)
for i in range(26):
if i < 13:
y = 40
x = 25 + (increase * i)
else:
x = 25 + (increase * (i - 13))
y = 85
buttons.append([LIGHT_BLUE, x, y, 20, True, 65 + i])
# buttons.append([color, x_pos, y_pos, radius, visible, char])
pregunta,word = randomWord()
inPlay = True
while inPlay:
redraw_game_window(pregunta)
pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
inPlay = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
inPlay = False
if event.type == pygame.MOUSEBUTTONDOWN:
clickPos = pygame.mouse.get_pos()
letter = buttonHit(clickPos[0], clickPos[1])
if letter != None:
guessed.append(chr(letter))
buttons[letter - 65][4] = False
if hang(chr(letter)):
if limbs != 5:
limbs += 1
else:
end(pregunta)
else:
print(spacedOut(word, guessed))
if spacedOut(word, guessed).count('_') == 0:
end(pregunta,True)
pygame.quit()
# always quit pygame when done!