Pygame Hangman生成新词的更简单方法?而不是制作另一个主循环



所以我正在开发这个hangman游戏,我正在尝试制作新生成的水果名称,而不是复制第一个主循环并再次粘贴它;这是我的水果11((,现在它只适用于单词Apple。有一种方法我可以制作它,所以当我完成单词Apple时,它会重置并生成一个新单词,而不是复制整个主循环并再次粘贴它,这将是如此多的代码,将有很多事情需要更改,谢谢!

如果我复制这个并为我的第二个单词做一个新的循环,就像我现在的第一个单词是";苹果;如果我复制这个主循环并制作一个新的循环,那么我将有数千行代码,我只想知道是否有一种简单的方法可以为我的刽子手制作新词


def lose_screen():

timer = 0
# the background image
bg = pygame.image.load("lose.png")

FPS = 50
clock = pygame.time.Clock()

def redraw():
window.blit(bg,(0,0))





intro = True
while intro:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro = False
pygame.quit()
timer += 1
if timer >= 120:
fruit11()

redraw()
clock.tick(FPS)

pygame.display.update()



def player1_win():

timer = 0
# the background image
bg = pygame.image.load("player1win.png")

FPS = 50
clock = pygame.time.Clock()

def redraw():
window.blit(bg,(0,0))





intro = True
while intro:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro = False
pygame.quit()
timer += 1
if timer >= 120:
fruit11()

redraw()
clock.tick(FPS)

pygame.display.update()


def player2_win():

timer = 0
# the background image
bg = pygame.image.load("player2win.png")

FPS = 50
clock = pygame.time.Clock()

def redraw():
window.blit(bg,(0,0))





intro = True
while intro:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro = False
pygame.quit()
timer += 1
if timer >= 120:
fruit11()

redraw()
clock.tick(FPS)

pygame.display.update()


def fruit11():
class partic:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
def draw(self,DrawX,DrawY):
self.rect.topleft = (DrawX,DrawY)
pygame.draw.rect(window,self.color,self.rect,2)
white = (255,255,255)            
partic1 = partic(500,500,50,50,white)

colors = (0, 0, 0)
greenbutton0 = button((colors),60,600,50,50, 'A')
greenbutton1 = button((colors),140,600,50,50, 'C')
greenbutton2 = button((colors),220,600,50,50, 'F')
greenbutton3 = button((colors),300,600,50,50, 'P')
greenbutton4 = button((colors),380,600,50,50, 'D')
greenbutton5 = button((colors),60,660,50,50, 'U')
greenbutton6 = button((colors),140,660,50,50, 'L')
greenbutton7 = button((colors),220,660,50,50, 'P')
greenbutton8 = button((colors),300,660,50,50, 'N')
greenbutton9 = button((colors),380,660,50,50, 'H')
greenbutton10 = button((colors),60,720,50,50, 'X')
greenbutton11 = button((colors),140,720,50,50, 'R')
greenbutton12 = button((colors),220,720,50,50, 'D')
greenbutton13 = button((colors),300,720,50,50, 'E')
greenbutton14 = button((colors),380,720,50,50, 'O')
menu_button = button((colors),390,210,150,50, "")
buttons = [greenbutton0,greenbutton1,greenbutton2,greenbutton3,greenbutton4,greenbutton5,greenbutton6,greenbutton7,greenbutton8,greenbutton9,greenbutton10,greenbutton11,greenbutton12,greenbutton13,greenbutton14]



font = pygame.font.Font("times.ttf", 40)
scor = 0
scoretext = font.render("" + str(scor), True, (255,255,255))
scorerect = scoretext.get_rect()
scorerect.center = ((450,180))

font = pygame.font.Font("times.ttf", 40)
sco = 0
scoretex = font.render("" + str(sco), True, (255,255,255))
scorerec = scoretex.get_rect()
scorerec.center = ((50,180))
nor = pygame.image.load("lose.png")

bg = pygame.image.load("player1.png")
bg2 = pygame.image.load("player2.png")
stickhead = pygame.image.load("nos.png")
stickbody = pygame.image.load("bod.png")
stickleg = pygame.image.load("leg2.png")
stickleg2 = pygame.image.load("leg1.png")
arm = pygame.image.load("bod2.png")
arm2 = pygame.image.load("bod3.png")
score = 0
score2 = 0
particles = []
def redraw():

window.blit(bg,(0,0))

if score == 1 or score == 3 or score == 5 or score == 7 or score == 9 or score == 11 or score == 14 or score == 15:
window.blit(bg2,(0,0))
if score == 2 or score == 4 or score == 6 or score == 8 or score == 10 or score == 12 or score == 14 or score == 16:
window.blit(bg,(0,0))



for button in buttons:
button.draw(window)

pos = pygame.mouse.get_pos()
for button in buttons:
if button.isOver(pos):
partic1.draw(button.x,button.y)

if score2 >= 1:
for button in buttons:
if button.x == 1040:
window.blit(stickhead,(170,240))
if score2 >= 2:
for button in buttons:
if button.x == 1040:
window.blit(stickbody,(180,300))
if score2 >= 3:
for button in buttons:
if button.x == 1040:
window.blit(stickleg,(180,360))
if score2 >= 4:
for button in buttons:
if button.x == 1040:
window.blit(stickleg2,(150,360))
if score2 >= 5:
for button in buttons:
if button.x == 1040:
window.blit(arm,(170,280))
if score2 >= 6:
for button in buttons:
if button.x == 1040:
window.blit(arm2,(150,280))
window.blit(scoretext,scorerect)
window.blit(scoretex,scorerec)
# our main loop



run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# what happens if our mouse clicks the button
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()



# back to game
if menu_button.isOver(pos):
game_intro()


if greenbutton0.isOver(pos) and greenbutton0.y == 600:
greenbutton0.y = 490
greenbutton0.x = 34
score += 1

if score == 1 or score == 3 or score == 5 or score == 7 or score == 9 or score == 11 or score == 14 or score == 15:
scor += 1
scoretext = font.render("" + str(scor), True, (255,255,255))
scorerect.center = ((450,180))

if score == 2 or score == 4 or score == 6 or score == 8 or score == 10 or score == 12 or score == 14 or score == 16:
sco += 1
scoretex = font.render("" + str(sco), True, (255,255,255))
scorerec.center = ((50,180))


if greenbutton7.isOver(pos) and greenbutton7.y == 660:
greenbutton7.y = 490
greenbutton7.x = 120
score += 1
if score == 1 or score == 3 or score == 5 or score == 7 or score == 9 or score == 11 or score == 14 or score == 15:
scor += 1
scoretext = font.render("" + str(scor), True, (255,255,255))
scorerect.center = ((450,180))

if score == 2 or score == 4 or score == 6 or score == 8 or score == 10 or score == 12 or score == 14 or score == 16:
sco += 1
scoretex = font.render("" + str(sco), True, (255,255,255))
scorerec.center = ((50,180))


if greenbutton3.isOver(pos) and greenbutton3.y == 600:
greenbutton3.y = 490
greenbutton3.x = 200
score += 1
if score == 1 or score == 3 or score == 5 or score == 7 or score == 9 or score == 11 or score == 14 or score == 15:
scor += 1
scoretext = font.render("" + str(scor), True, (255,255,255))
scorerect.center = ((450,180))

if score == 2 or score == 4 or score == 6 or score == 8 or score == 10 or score == 12 or score == 14 or score == 16:
sco += 1
scoretex = font.render("" + str(sco), True, (255,255,255))
scorerec.center = ((50,180))

if greenbutton6.isOver(pos) and greenbutton6.y == 660:
greenbutton6.y = 490
greenbutton6.x = 300
score += 1
if score == 1 or score == 3 or score == 5 or score == 7 or score == 9 or score == 11 or score == 14 or score == 15:
scor += 1
scoretext = font.render("" + str(scor), True, (255,255,255))
scorerect.center = ((450,180))

if score == 2 or score == 4 or score == 6 or score == 8 or score == 10 or score == 12 or score == 14 or score == 16:
sco += 1
scoretex = font.render("" + str(sco), True, (255,255,255))
scorerec.center = ((50,180))

if greenbutton13.isOver(pos) and greenbutton13.y == 720:
greenbutton13.y = 490
greenbutton13.x = 380
score += 1
if score == 1 or score == 3 or score == 5 or score == 7 or score == 9 or score == 11 or score == 14 or score == 15:
scor += 1
scoretext = font.render("" + str(scor), True, (255,255,255))
scorerect.center = ((450,180))

if score == 2 or score == 4 or score == 6 or score == 8 or score == 10 or score == 12 or score == 14 or score == 16:
sco += 1
scoretex = font.render("" + str(sco), True, (255,255,255))
scorerec.center = ((50,180))                    


if greenbutton1.isOver(pos):
score2 += 1
score +=1 
greenbutton1.x = 1040

if greenbutton2.isOver(pos):
score2 += 1
score +=1 
greenbutton2.x = 1040

if greenbutton4.isOver(pos):
score2 += 1
score +=1 
greenbutton4.x = 1040

if greenbutton5.isOver(pos):
score2 += 1
score +=1 
greenbutton5.x = 1040


if greenbutton8.isOver(pos):
score2 += 1
score +=1 
greenbutton8.x = 1040

if greenbutton9.isOver(pos):
score2 += 1
score +=1 
greenbutton9.x = 1040

if greenbutton10.isOver(pos):
score2 += 1
score +=1 
greenbutton10.x = 1040

if greenbutton11.isOver(pos):
score2 += 1
score +=1 
greenbutton11.x = 1040

if greenbutton12.isOver(pos):
score2 += 1
score +=1 
greenbutton12.x = 1040


if greenbutton14.isOver(pos):
score2 += 1
score += 1 
greenbutton14.x = 1040

if score2 == 6:
lose_screen()

if greenbutton0.y == 490 and greenbutton7.y == 490 and greenbutton3.y == 490 and greenbutton6.y == 490 and greenbutton13.y == 490:
if sco > scor:
player1_win()

if greenbutton0.y == 490 and greenbutton7.y == 490 and greenbutton3.y == 490 and greenbutton6.y == 490 and greenbutton13.y == 490:
if sco < scor:
player2_win()


redraw()
pygame.display.update()

pygame.quit()

那么对于Hangman游戏,我们如何将每个玩家的回合作为一个函数来处理呢?玩家提供了一封信,我们返回";"正确"失败";以及";重复";(这可能也是一个失败(。

def hangmanGuess( secret_word, guess_letter, used_letters ):
""" Given a guess, return "correct" if the letter is in the secret, but
already used.  Return "fail" if the letter is not in the secret, and
"duplicate" for a letter already used (pass or fail) """
result = "fail"
### Is the letter in the secret?
if ( guess_letter.lower() in used_letters ):
result = "duplicate"
elif ( guess_letter.lower() in secret_word.lower() ):
result = "correct"
return result

所以现在我们可以很容易地检查结果了。

我们还需要用所有未猜到的字母来显示这个秘密;"空白";。我认为下划线会有好处。有些单词也有空格和破折号,但我们不想猜测这些。

INVALID_LETTERS=' ~!@#$%^&*()-_+=[{]}|:;'"?/,.<>1234567890'  # not used for guesses
def getWordString( secret_word, used_letters, hide_character='_' ):
""" Given a secret, hide any letters that are not already used,
by replacing it with hide_character.  Returns a copy of the
secret with all known letters shown """
result = ''
for letter in secret_word:
# Anything that's guessed already, or not-a-letter is copied through
if ( letter.lower() in used_letters or letter.lower() in INVALID_LETTERS ):
result += letter
else:
result += hide_character
return result

就这样。现在我们可以循环,打印到目前为止猜测的单词,然后从用户那里获取输入,并检查猜测是否正确。如果他们尝试了太多次,比赛就结束了。如果他们赢了,重新设置一切,然后再试一次。

所以把所有这些放在一起:

python3 ./handman.py 
[ _______ ]
Guess a Letter: a
[ _______ ]
Guess a Letter: b
[ B______ ]
Guess a Letter: c
[ B______ ]
Guess a Letter: l
[ B_ll___ ]
Guess a Letter: u
[ Bull___ ]
Guess a Letter: s
[ Bull___ ]
Guess a Letter: t
[ Bull___ ]
Guess a Letter: o
[ Bull_o_ ]
Guess a Letter: f
[ Bull_o_ ]
Guess a Letter: d
[ Bulldo_ ]
Guess a Letter: g
[Bulldog]
*** GAME WON ***

代码:

#! /usr/bin/env python
import random
INVALID_LETTERS=' ~!@#$%^&*()-_+=[{]}|:;'"?/,.<>1234567890'  # not used for guesses
def hangmanGuess( secret_word, guess_letter, used_letters ):
""" Given a guess, return "correct" if the letter is in the secret, but
already used.  Return "fail" if the letter is not in the secret, and
"duplicate" for a letter already used (pass or fail) """
result = "fail"
### Is the letter in the secret?
if ( guess_letter in used_letters ):
result = "duplicate"
elif ( guess_letter in secret_word.lower() ):
result = "correct"
return result

def getWordString( secret_word, used_letters, hide_character='_' ):
""" Given a secret, hide any letters that are not already used,
by replacing it with hide_character.  Returns a copy of the
secret with all known letters shown """
result = ''
for letter in secret_word:
# Anything that's guessed already, or not-a-letter is copied through
if ( letter.lower() in used_letters or letter.lower() in INVALID_LETTERS ):
result += letter
else:
result += hide_character
return result
def getPlainWord( secret_word ):
""" Return the word without any punctuation or digits (etc.) """
cleaned_word = secret_word.translate( str.maketrans( '', '', INVALID_LETTERS ) )
return cleaned_word

all_words = [ 'Aardvark', 'Abyssinian', 'Adelie Penguin', 'Affenpinscher', 'Afghan Hound', 'African Bush Elephant', 'African Civet', 'African Clawed Frog', 'African Forest Elephant', 'African Palm Civet', 'African Penguin', 'African Tree Toad', 'African Wild Dog', 'Ainu Dog', 'Airedale Terrier', 'Akbash', 'Akita', 'Alaskan Malamute', 'AlbatrossBaboon', 'Bactrian Camel', 'Badger', 'Baiji', 'Balinese', 'Banded Palm Civet', 'Bandicoot', 'Barb', 'Barn Owl', 'Barnacle', 'Barracuda', 'Barramundi Fish', 'Basenji Dog', 'Basking Shark', 'Basset Hound', 'Bat', 'Bavarian Mountain Hound', 'Beagle', 'Bear', 'Bearded Collie', 'Bearded Dragon', 'Beaver', 'Bedlington Terrier', 'Beetle', 'Beluga Sturgeon', 'Bengal Tiger', 'Bernese Mountain Dog', 'Bichon Frise', 'Binturong', 'Bird', 'Birds Of Paradise', 'Birman', 'Bison', 'Black Marlin', 'Black Rhinoceros', 'Black Russian Terrier', 'Black Widow Spider', 'Blobfish', 'Bloodhound', 'Blue Jay', 'Blue Lacy Dog', 'Blue Whale', 'Bluetick Coonhound', 'Bobcat', 'Bolognese Dog', 'Bombay', 'Bongo', 'Bonito Fish', 'Bonobo', 'Booby', 'Border Collie', 'Border Terrier', 'Bornean Orang-utan', 'Borneo Elephant', 'Boston Terrier', 'Bottlenose Dolphin', 'Bowhead Whale', 'Boxer Dog', 'Boykin Spaniel', 'Brazilian Terrier', 'British Timber', 'Brown Bear', 'Budgerigar', 'Buffalo', 'Bull Shark', 'Bull Terrier', 'Bulldog', 'Bullfrog', 'Bullmastiff', 'Bumblebee', 'Burmese', 'Burrowing Frog', 'Butterfly', 'Butterfly Fish', 'Aldabra Giant Tortoise', 'Alligator', 'Alpaca', 'Amur Leopard', 'Anatolian Shepherd Dog', 'Angelfish', 'Ant', 'Anteater', 'Antelope', 'Appenzeller Dog', 'Arctic Fox', 'Arctic Hare', 'Arctic Wolf', 'Armadillo', 'Asian Elephant', 'Asian Giant Hornet', 'Asian Palm Civet', 'Asiatic Black Bear', 'Aurochs', 'Cattle Dog', 'Kelpie Dog', 'Avocet', 'Axolotl', 'Aye Aye', 'Caiman', 'Caiman Lizard', 'Cairn Terrier', 'Camel', 'Camel Spider', 'Canaan Dog', 'Canadian Eskimo Dog', 'Capybara', 'Caracal', 'Carolina Dog', 'Cassowary', 'Cat', 'Caterpillar', 'Catfish', 'Cavalier King Charles Spaniel', 'Centipede', 'Cesky Fousek', 'Chameleon', 'Chamois', 'Cheetah', 'Chesapeake Bay Retriever', 'Chicken', 'Chihuahua', 'Chimaera', 'Chimpanzee', 'Chinchilla', 'Chinese Crested Dog', 'Chinook', 'Chinstrap Penguin', 'Chipmunk', 'Chow Chow', 'Cichlid', 'Clouded Leopard', 'Clown Fish', 'Clumber Spaniel', 'Coati', 'Cockatoo', 'Cockroach', 'Collared Peccary', 'Collie', 'Colossal Squid', 'Common Buzzard', 'Common Frog', 'Common Loon', 'Common Toad', 'Coral', 'Cotton-top Tamarin', 'Cougar', 'Cow', 'Coyote', 'Crab', 'Crab-Eating Macaque', 'Crane', 'Crested Penguin', 'Crocodile', 'Cross River Gorilla', 'Curly Coated Retriever', 'Cuscus', 'Cuttlefish', 'Dachshund', 'Dalmatian', 'Darwin’s Frog', 'Deer', 'Desert Tortoise', 'Deutsche Bracke', 'Dhole', 'Dingo', 'Discus', 'Doberman Pinscher', 'Dodo', 'Dog', 'Dogo Argentino', 'Dogue De Bordeaux', 'Dolphin', 'Donkey', 'Dormouse', 'Dragonfish', 'Dragonfly', 'Drever', 'Drum Fish', 'Duck', 'Dugong', 'Dunker', 'Dusky Dolphin', 'Dwarf Crocodile', 'Eagle', 'Earwig', 'Eastern Gorilla', 'Eastern Lowland Gorilla', 'Echidna', 'Edible Frog', 'Egyptian Mau', 'Electric Eel', 'Elephant', 'Elephant Seal', 'Elephant Shrew', 'Emperor Penguin', 'Emperor Tamarin', 'Emu', 'English Cocker Spaniel', 'English Shepherd', 'English Springer Spaniel', 'Entlebucher Mountain Dog', 'Epagneul Pont Audemer', 'Ermine', 'Eskimo Dog', 'Estrela Mountain Dog' ]

used_letters   = []
failed_letters = 0
pass_letters   = 0
secret_word    = random.choice( all_words )
target_size    = len( getPlainWord( secret_word ) )  # remove punctuation from guess-count
finished = False
while not finished:
display_word = getWordString( secret_word, used_letters )
print( "[ %s ]" % ( display_word ) )
letter = input( "Guess a Letter: " )
letter = letter.lower().strip()
if ( len( letter ) != 1 ):
print( "Please enter only a single letter!" )
else:
guess_result = hangmanGuess( secret_word, letter, used_letters )
if ( guess_result != "duplicate" ):
used_letters.append( letter )
if ( guess_result == "fail" ):
failed_letters += 1     
else:
# guess was correct
count = secret_word.lower().count( letter )
pass_letters += count
# Is the game over?
if ( failed_letters > 10 ):
print( "* GAME OVER * " )
finished = True
elif ( pass_letters == target_size ):
print( "[%s]" % ( secret_word ) )
print( "*** GAME WON ***n" )
# Restart
used_letters   = []
failed_letters = 0
pass_letters   = 0
secret_word    = random.choice( all_words )
target_size    = len( getPlainWord( secret_word ) ) # remove punctuation from guess-count

我看了一会儿。我甚至看不出单词是从哪里产生的。。。苹果

您应该学习如何使用%模运算符。它会给你除法后的余数,所以

"4除以2没有余数";4 % 2 = 0
"5除以2的余数为1〃;5 % 2 = 1

因此,能够快速判断数字是偶数还是奇数。这将大大减少CCD_ 4的长谱线
https://www.w3schools.com/python/trypython.asp?filename=demo_oper_mod

最新更新