For loop breaks whole script - python

I'm trying to build a Wordle clone, a word game where one gets 6 chances to guess a 5 letter word. The game itself works but when I try to show the definition of the word at the end of the game, my whole game gets stuck.
My code is this:
import pygame
import pygame.display
import sys
import random
from words import *
from PyDictionary import PyDictionary
pygame.init()
# a py file with list of words
CORRECT_WORD = WORDS
CORRECT_WORD_LIST = list(CORRECT_WORD)
word = random.choice(CORRECT_WORD_LIST)
# number of attempts, 6 in total
attempts = 0
# a list to store the previous guesses
guesses = [[]] * 6
cur_guess = []
cur_guess_str = ""
current_letter_bg_x = 110
game_result = ""
# get the meaning of the word
def get_meaning(word):
dicto = PyDictionary()
meaning = dicto.meaning(word)
if meaning == "":
meaning = "No definition found"
return meaning
meaning = get_meaning(word)
def blit_text(surface, text, pos, font):
"""Multi-line text blit from https://stackoverflow.com/a/42015712/2280890"""
def check_guess(guess):
# Check if letter is Green, Yellow or grey if not in word
# trimmed, for not being part of the problem
attempts += 1
cur_guess = []
cur_guess_str = ""
current_letter_bg_x = 110
def play_again():
SCREEN.blit(BACKGROUND, BG_RECT)
play_again_text = play_again_font.render("ENTER to Play Again? or Q to Quit!", True, "#FCFCFC")
pygame.display.update()
word_text = play_again_font.render(f"{word.upper()}", True, "#FFB90F")
SCREEN.blit(play_again_text, play_again_rect)
SCREEN.blit(word_text, word_rect)
pygame.display.flip()
def reset():
# Reset all global variables
I've trimmed/removed a bunch of lines relating to creating/drawing letters and backspace etc.
Up until this point everything works as expected. The letters, if in correct position get colored as expected.
My problem starts here. Instead of only showing the definition after 6 attempts it shows the meaning as soon as the game starts. This is the block of code that breaks the game:
for i in enumerate(guesses[attempts]):
if i == 6 and game_result is not "W":
word = random.choice(CORRECT_WORD_LIST)
meaning = get_meaning(word)
txt = f"{meaning}"
txt_pos = (40, 70)
window.blit(BACKGROUND, [-317, -300])
f"{blit_text(window, txt, txt_pos, sys_font)}", True, "#FFB90F"
pygame.display.update
If I omit that block the game runs as expected and if I leave as below, it works as expected.
Game
while running:
if game_result != "":
play_again()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
if game_result != "":
reset()
else:
if len(cur_guess_str) == 5 and cur_guess_str.lower() in WORDS:
check_guess(cur_guess)
elif event.key == pygame.K_BACKSPACE:
if len(cur_guess_str) > 0:
delete_letter()
else:
key_pressed = event.unicode.upper()
if key_pressed in "QWERTYUIOPASDFGHJKLZXCVBNM" and key_pressed != "":
if len(cur_guess_str) < 5:
new_letter()
Can someone help me understand why my logic/reasoning is flawed?
The block of code that is causing issues I insert it right after ### game, in between while running: and right before
if game_result != "":
play_again()

while True:
meaning = ""
for i in range(len(guesses[attempts])):
if i == 6 and game_result is not "W":
word = random.choice(CORRECT_WORD_LIST)
meaning = get_meaning(word)
txt = f"{meaning}"
txt_pos = (40, 70)
window.blit(BACKGROUND, [-317, -300])
f"{blit_text(window, txt, txt_pos, sys_font)}", True, "#FFB90F"
pygame.display.update()
for the code above you have put while running but you never change running so wouldn`t it be better to do while True. Also if you put while True a better way of ending the game is to just do break instead of pygame.quit() and sys.exit(). Also can I see the output that prints when the game breaks please?
Don't Work (I have edited the code and it prints because as soon as the game starts to run you have put txt=f"{meaning}" by moving it across that only happens when i == 6 and game_result is not "W". I don't know if this will work but its worth a try.)
If that doesn`t work from what I can see you don't use enumerate so I would replace it with range(len(guesses[attempts]))

Related

Window freeze for single thread in while loop of Pygame

I am writing a short program to display cards in a round. I suspect that it is the length of the code which prevents the final 'OK' submit on P3 (the last player's submission) from executing properly: at which point the program sometimes will evaluate the winner and clear the round, but most of the time instead will freeze.
I have tried clock.tick(low fps), pygame.event.pump(), and pygame.event.clear(). Any leads would be much appreciated.
# Round loop begins. Finish until all hands are empty.
while not self.game.get_is_last_round():
player = self.game.get_player(self.game.get_player_turn())
hand = player.order_hand(player.get_hand(),
self.game.get_round_level(),
self.game.get_round_trump_suit())
ok_clicked_2 = False
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.deal_running = False
self.is_running = False
pygame.display.quit()
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
play = player.get_play()
click = pygame.mouse.get_pressed(num_buttons=3)
pos = pygame.mouse.get_pos()
# Used DeMorgan's law to resolve error
ok_clicked_2 = (OK1_X < pos[0] < OK1_X + B_W) and (OK1_Y < pos[1] < OK1_Y + B_H) and click[0]
b1, card = self.check_hand(pos, player)
b2, play_card = self.check_play(pos, player)
if b1:
hand.remove(card)
play.append(card)
player.set_play(
player.order_hand(play, self.game.get_round_level(),
self.game.get_round_trump_suit()))
player.set_hand(
player.order_hand(hand, self.game.get_round_level(),
self.game.get_round_trump_suit()))
if b2:
play.remove(play_card)
hand.append(play_card)
player.set_play(
player.order_hand(play, self.game.get_round_level(),
self.game.get_round_trump_suit()))
player.set_hand(player.order_hand(hand, self.game.get_round_level(),
self.game.get_round_trump_suit()))
clock.tick(100)
surface.blit(background, (0, 0))
if len(self.game.get_player(0).get_hand()) == 25:
self.game.set_is_first_round(True)
else:
self.game.set_is_first_round(False)
if len(self.game.get_player(0).get_hand()) == 0:
self.game.set_is_last_round(True)
else:
self.game.set_is_last_round(False)
if self.game.get_play_in_turn() != NUM_PLAYERS:
pygame.event.pump()
clock.tick(100)
if len(hand) <= 1:
width = 0
x = (BG_WIDTH - CARD_WIDTH) // 2
elif len(hand) >= 8:
width = (BG_WIDTH - SIDE_W - CARD_WIDTH) // (len(hand) - 1)
x = BG_WIDTH // 2 - (CARD_WIDTH + (width * (len(hand) - 1))) // 2
else:
width = CARD_WIDTH
x = (BG_WIDTH - (CARD_WIDTH * len(hand))) // 2
surface.blit(background, (0, 0))
self.blit_backs()
self.blit_round()
self.show_ok()
self.show_hand(x, ROW3h, width, hand)
self.show_hand(CARD_POSITIONS[0][0], CARD_POSITIONS[0][1], SLIM_WIDTH, play)
if ok_clicked_2:
for card in play:
hand.append(card)
player.set_hand(player.order_hand(hand, self.game.get_round_level(),
self.game.get_round_trump_suit()))
# If player is first to start a round, he/she has a different validity check.
# (Sets the pattern for the cycle)
if player.get_begins_cycle():
valid = self.game.check_validity(True) # is_first
else:
valid = self.game.check_validity(False) # Is not first to play in the round
if not valid: # Clear holding if invalid
if (play == []) or (player.get_play() == []):
print("\nYou must make a play.\n")
else:
print("Invalid play. Try again.")
if not player.get_begins_cycle():
valid_plays = player.get_valid_plays(self.game.get_pattern(),
self.game.get_round_trump_suit())
print("Valid plays: \n")
for temp_play_idx in range(len(valid_plays)):
temp_play = valid_plays[temp_play_idx]
print("[", end='')
for temp_card_idx in range(len(temp_play)):
valid_plays[temp_play_idx][temp_card_idx].show_card("", '')
if temp_card_idx != len(temp_play) - 1:
print(", ", end='')
print("]")
# Clear the current player's selection and restore hand to its original content
cycle_order = self.game.get_cycle_order()
cycle = self.game.get_cycle()
for player_order in range(len(cycle_order)):
if player == cycle_order[player_order]:
cycle_order.remove(player)
cycle.pop()
self.game.set_cycle_order(cycle_order)
self.game.set_cycle(cycle)
else: # Valid play on submit
# Special case for HIGH_SUIT play, play lowest card if another player has greater
play = self.game.check_high_suit(play)
# If friend card played, establish and print teammates
# TODO: auto-designate friends if the last round
# has been reached (friends buried in treasure case)
# TODO: determine whether friend is "dead"
self.game.check_for_friends()
cycle = self.game.get_cycle()
cycle.append(play)
self.game.set_cycle(cycle)
cycle_order = self.game.get_cycle_order()
cycle_order.append(player)
self.game.set_cycle_order(cycle_order)
# self.clear_positions()
for card in play:
hand.remove(card)
player.set_hand(
player.order_hand(hand, self.game.get_round_level(),
self.game.get_round_trump_suit()))
self.game.next_player_turn()
self.game.set_play_in_turn(self.game.get_play_in_turn() + 1)
print(self.game.get_play_in_turn())
play = []
else:
self.game.set_play_in_turn(0)
# Distribute any points in the round to round winner
self.update_cycle_points()
for p in self.game.get_players():
for card in p.get_play():
discard = self.game.get_discard()
discard.append(card)
p.set_play([])
pygame.event.clear()
clock.tick(100)
pygame.display.update()
I think it's time for a code-cleanup, then your issue will go away (or you'll find it).
Currently the main loop is a big mix-up of event handling, screen-painting and game engine. Try to separate these parts out.
Move some of the in-loop processing out to functions - like the block after if ok_clicked_2:. It may help to make a data structure in which you store the game-state, then have the events change that game state. When it comes time to draw the game to the screen, the painting code can query the state, acting accordingly.
In terms of your actual lockup, if self.game.get_play_in_turn() == NUM_PLAYERS nothing is painted to the screen. Is this intentional? Add some print()s to your code so you can know the execution flow (or learn to use the python debugger).
I think the biggest step forward would be to move all the screen painting to one section of the main loop, something like:
# Render the screen
print( "Rendering Screen" )
surface.blit(background, (0, 0))
self.blit_backs()
self.blit_round()
# etc. for all other things, score, buttons, ...
clock.tick(60)
pygame.display.update()
You seem to be handling the events OK, so it would probably be better to remove the calls to pygame.event.pump() and pygame.event.clear(). You don't need these.
Following Kingsley's advice, I organized the code by function: rendering screen, game engine, and event handling. I would provide MRE as Random Davis suggests, but that would include 5 integrated files which would take too long to pare down.
It turns out that the problem lay in a piece of code which is called separately: "update_cycle_points()". Within, there is a while loop which does not contain an event handler. The solution was to change it to a for loop, which Pygame seems to process without error (does not freeze because it does not expect event handling there).
I also removed pygame.event.clear() and pump() functions without problems.

Values are being passed correctly however selection statements do not work properly

I've been recently trying to code a quick game which involves binary to hex conversion. I've set up some of the basic structure of the code but I've stumbled upon a problem: My selection statement in the game's entry point doesn't work as intended even though the values should be passed on correctly
What I've tried:
I tried "debugging" the program by adding print statements in between the function and statements, eg:
if event.key == pygame.K_KP_ENTER:
print('enter')
print(key_value)
key_value = 1
print(key_value)
The values when printed are correct, which are used in the game's while loop point:
while running:
if EventHandler.get_key_pressed() == 1:
print('1')
elif EventHandler.get_key_pressed() == 2:
print('2')
Changed the conditions of the statement, still got the same results eg:
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER:
print('enter')
key_value = 2
elif event.key == pygame.K_SPACE:
print('space')
key_value = 1
Changed the get_key_pressed() function to a non-static one, still had the same results.
Went back to basic python tutorials to make sure my indentation and structuring/usage of selection statements are correct.
From my observations, only the first if statement after the while loop in works, however I'm not sure as to why that happens when I think I formatted my code properly.
Code:
main.py
import pygame
from Include.src.event_handler import EventHandler
# other imports go here, not related to problem.
# Global Variables
running = True
# Object creations, not really related as well
game = Game() # initialise pygame, settings and assets
screen = game.get_screen() # get screen bounds/object
while running:
if EventHandler.get_key_pressed() == 1: # Issue here
print('1')
elif EventHandler.get_key_pressed() == 2:
print('2')
pygame.display.flip()
pygame.display.update()
event_handler.py
import pygame
class EventHandler:
#staticmethod
def get_key_pressed():
key_value = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
print('Thanks for debugging me or playing idk')
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_KP_ENTER:
print('enter')
key_value = 1
elif event.key == pygame.K_SPACE:
print('space')
key_value = 2
return key_value
Expected output
Person presses space, space and 2 is printed.
Person presses enter, enter and 1 is printed.
Actual output
Space pressed, only space is outputted.
Enter pressed, both enter and 1 is outputted.
Thank you so much!
For anyone looking back to this post, I've found the answer:
As #jasonharper said, the value was being thrown since the function was being called again
while running:
e = EventHandler.get_key_pressed() # make it constant
if e == 1:
print('1')
elif e == 2:
print('2')

A novice's hangman project: Dealing with duplicate letters

First, I realize the following code is probably not very good, so apologies for anything that makes you cringe, I'm just trying to code as much as I can in hopes of getting better.
This is part of a small hangman game project, I'm trying to figure the best way to deal with duplicate letters in strings.
This is what I got for now:
def checkDupes(word):
global dupeList
global repeatTimesDupes
if repeatTimesDupes != 0:
dupeCount = 0
for i in range(len(word)):
temp = word[i]
print("temp letter is: ", temp)
for j in range(i+1,len(word)):
if word[j] == temp:
if temp not in dupeList:
dupeList.append(word[j])
print("the dupeList contains: ", dupeList)#debug
repeatTimesDupes -= 1
def getLetter(position,buttons,word):
i = 96
index = 0
letter = chr(i)
for button in buttons:
if button != None:
i+=1
if button.collidepoint(position):
print("the position is: ", position)
print(i)
for j in range(len(word)):
print(word[j] , chr(i))
if word[j] == chr(i):
index = j
return chr(i), index
else:
return '?', -1
def checkForLetter(word,letter):
inWord = " "
for i in range(len(word)):
if word[i] == letter:
inWord = True
break
else:
print(len(word))
print (word[i])
inWord = False
return inWord
#========================== Start Loop ===========================================
while done == False:
events = pygame.event.get()
screen.fill(BGCOLOR)
timedelta = clock.tick_busy_loop(60)
timedelta /= 1000 # Convert milliseconds to seconds
for event in events:
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
if event.type == pygame.MOUSEBUTTONUP:
if event.button == MOUSEBUTTONLEFT:
pos = pygame.mouse.get_pos()
for button in buttonsList:
if button.collidepoint(pos):
if button != None:
checkDupes(gameWord)
letter, atIndex = getLetter(pos,buttonsList,gameWord)
letterSelected = True
moveCounter+=1
screen.blit(blackBG,(0,0))
showButtons(letterList)
showLetterSlots(gameWord,screenRect)
setCounters(moveMade,mistakeMade)
if letterSelected:
inGameWord = checkForLetter(gameWord, letter)
if inGameWord:
print(atIndex)
print(letter)
letterRen = wordFonts.render(letter,1,(0,255,0))
renderList[atIndex] = letterRen
print("The render list is: ", renderList)
renCount = 0
for r in lineRectList:
if renderList[renCount] != '?' :
screen.blit(renderList[renCount],((r.centerx-10),430))
if renCount <= len(gameWord):
renCount+=1
#update game screen
clock.tick(60)
pygame.display.update()
#========================== End Loop =============================================
pygame.quit()
I'm looking for quick way to deal with duplicates so they are blitted along with their matches. I'm already slowing down my letter blits with all that looping, so I'm not really sure my current getDupes is the way to go.
If anyone is willing to look at this and give some input, I'd very much appreciate it.
Thanks for your time.
Based on what you've described in the comments, it seems reasonable to use a dictionary object in this case. You don't just want to store the letter, you want to store where those letters occur.
Dictionaries have a key and a value. For example:
{'jack': 4095, 'jill': 12}
The key is jack and the value is 4095.
In this case, we won't be using an int for the value. We'll actually be using an array of ints.
So, your dictionary might look like this:
{'o':[1, 5, 6, 3, 2, 1]} where those numbers are the index that the letter was encountered at. That will work for an arbitrary number of duplicate letters. Then, in your buttons, you know which ones to 'blit' because they're in the same order as the string.
Python dictionary documentation:
https://docs.python.org/3/tutorial/datastructures.html
FWIW, some refactoring would do you service here as well.

Python 3.3 pygame 1.9.2a0 (64-bit) graphics window displays 1st image but then freezes

Using Python 2.7.3 and Pygame on a classroom PC, I created a movie-quote guessing game using both the command prompt window (to interact with the user) and a graphics window (to display still .png files, such as photos from movies). The game ran successfully.
Now I want to run and enhance the game on my own Windows 7 64-bit PC. I downloaded Python version 3.3.5 and pygame-1.9.2a0.win-amd64-py3.3.exe. Then I made two changes to my game code to adjust from Python 2.7.3 to Python 3.3.5 environment: (1) deleted "raw_" from "raw_input()" commands; and (2) deleted 1st line, which instructor had told us to use so that Python 2.6 would act like later versions: "from future import division, absolute_import, print_function, unicode_literals".
Now, on my PC, the command prompt window and the audio both work fine. The pygame graphics window displays only first .png image. Top of window (next to pygame logo) immediately says "(Not Responding)". There are no error messages. Thank you for any help.
Here's the code:
# Import common modules
import pygame, pygame.mixer, os
from pygame.locals import *
# Initialize pygame, window and sound mixer
pygame.init()
screen = pygame.display.set_mode((600,450))
pygame.display.set_caption('Greatest Movie Lines')
pygame.mouse.set_visible(0)
pygame.mixer.init()
# Create and display background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))
screen.blit(background, (0,0))
# Initialize variables that will persist through entire game
gameRunning = True
roundsCompleted = 0
totalRoundsAvailable = 5
scoreSoFar = 0
quitOrContinue = 'Try another movie line? Type y or n: '
def beginGame():
titleDisplay = pygame.image.load('titleSlide.png')
titleDisplay = pygame.transform.scale(titleDisplay, (600, 450))
screen.blit(titleDisplay, (0,0))
pygame.display.flip()
sound = pygame.mixer.music.load('20fox-fanfare-w-cinemascope-ext_anewman.mp3')
pygame.mixer.music.play()
print('First, move the photo window rightwards and make this black window')
print('smaller so that you can see both windows completely (no overlap).')
print( )
doneFixingWindow = input('When done repositioning windows, hit enter here.')
howToPlay = pygame.image.load('howToPlay.png')
howToPlay = pygame.transform.scale(howToPlay, (600, 450))
screen.blit(howToPlay, (0,0))
pygame.display.flip()
print( )
print('Read the instructions at right.')
doneFixingWindow = input('Then hit enter to play!')
print( )
def endGame():
endDisplay = pygame.image.load('ending.png')
endDisplay = pygame.transform.scale(endDisplay, (600, 450))
screen.blit(endDisplay, (0,0))
pygame.display.flip()
sound = pygame.mixer.music.load('warnerbros_fanfare.mp3')
pygame.mixer.music.play()
print(' ')
print('Game over. Thank you for playing.')
raw_input('Hit enter to exit the game.')
def playRound(cumScoreLastRound,roundsDone):
# Initialize variables and constants used in the game rounds
hintUsed = False
guessOrHint = 'Would you like to (g)uess or get a(h)int first? Type g or h: '
requestGuess = 'Guess the movie line (no commas): '
noKeywordsMatched = "Sorry, your guess didn't match any keywords."
oneKeywordMatched = 'Not bad. You got one keyword right:'
twoKeywordsMatched = 'Pretty good! You got two keywords right:'
threeKeywordsMatched = 'Great! You got all three keywords:'
# Load variables specific to this round
fo = open("quoteData.csv","r")
movieData = fo.readlines()
line = movieData[roundsDone + 1]
movie = line.split(",")
droodle = pygame.image.load(movie[3])
droodle = pygame.transform.scale(droodle, (600, 450))
hint = movie[4]
keyword1 = movie[5]
keyword2 = movie[6]
keyword3 = movie[7]
answer = pygame.image.load (movie[8])
answer = pygame.transform.scale(answer, (600, 450))
# Initialize counters specific to this round
keywordMatches = 0
keyword1Yes = ' '
keyword2Yes = ' '
keyword3Yes = ' '
# Display this round's droodle
screen.blit(droodle, (0, 0))
pygame.display.flip()
print()
print('Here is the droodle portraying a famous movie line.')
# Give user option of hint before guessing
playerChoice = input(guessOrHint)
while playerChoice != 'g' and playerChoice != 'h': # Ensure valid selection
print(' ')
print('Not a valid selection')
playerChoice = input(guessOrHint)
if playerChoice == 'h': # Display hint if player chooses to see one
print(' ')
print('Hint: ',hint)
hintUsed = True
# Solicit and evaluate the player's guess
print( )
guess = str.lower(input(requestGuess))
guessParsed = guess.split() # Determine which keywords match, if any
if word == keyword1:
keyword1Yes = keyword1
keywordMatches = keywordMatches + 1
if word == keyword2:
keyword2Yes = keyword2
keywordMatches = keywordMatches + 1
if word == keyword3:
keyword3Yes = keyword3
keywordMatches = keywordMatches + 1
# Display and play the correct answer
screen.blit(answer, (0, 0))
pygame.display.flip()
if roundsDone == 0:
sound = pygame.mixer.Sound('casab.wav')
sound.play()
elif roundsDone == 1:
sound = pygame.mixer.Sound('oz6.wav')
sound.play()
elif roundsDone == 2:
sound = pygame.mixer.music.load('WaterfrontClass.mp3')
pygame.mixer.music.play()
elif roundsDone == 3:
sound = pygame.mixer.Sound('offer.wav')
sound.play()
else:
sound = pygame.mixer.Sound('gwtw.wav')
sound.play()
# Calculate score for this round and new total score
if keywordMatches == 0:
scoreThisRound = 0
if keywordMatches == 1:
scoreThisRound = 25
if keywordMatches == 2:
scoreThisRound = 50
if keywordMatches == 3:
scoreThisRound = 100
if hintUsed == True:
scoreThisRound = scoreThisRound - 20
newCumScore = cumScoreLastRound + scoreThisRound
# Display player's result, score for round, and cumulative score
print(' ')
if keywordMatches == 0:
print(noKeywordsMatched, keyword1Yes, keyword2Yes, keyword3Yes)
if keywordMatches == 1:
print(oneKeywordMatched, keyword1Yes, keyword2Yes, keyword3Yes)
if keywordMatches == 2:
print(twoKeywordsMatched, keyword1Yes, keyword2Yes, keyword3Yes)
if keywordMatches == 3:
print(threeKeywordsMatched, keyword1Yes, keyword2Yes, keyword3Yes)
print('Your score for this round is ', scoreThisRound)
print( 'Your new total score is ', newCumScore)
return newCumScore
while gameRunning:
# To begin game, display title page and instructions
if roundsCompleted == 0:
beginGame()
# Play the round
scoreSoFar = playRound(scoreSoFar,roundsCompleted)
# Check to see if any rounds left to be played
roundsCompleted = roundsCompleted + 1
if roundsCompleted == totalRoundsAvailable:
# End game if no rounds left to play
print()
input('That was our last quote. Hit enter to exit the game.')
endGame()
gameRunning = False
# Ask player whether to continue
else:
print(' ')
playerContinue = input(quitOrContinue)
while playerContinue != 'y' and playerContinue != 'n': # Ensure valid selection
print(' ')
print('Not a valid selection')
playerContinue = input(quitOrContinue)
if playerContinue == 'n': # End game if player wants to quit
endGame()
gameRunning = False
pygame.quit()
PyGame is an event-driven system. If you're not using its internal event loop to drive your game, you still need to let it take some time occasionally to process internal events, like windows being moved or resized. There's a function specifically for this: pygame.event.pump.
I think you can get your screen to be responsive if you put a call to that function in your code in a few places (perhaps just before or after you collect input on the console).

How do I get the circles to appear on the pygame screen

Below is a small piece of my program. Currently, the program takes the user's input and converts it into a binary number in the Python Shell. I am trying to use that input so that I can graphically display the binary number. At the moment, I am unable to get anything to appear in the pygame screen. It is just white, no circles, no text. I am not sure why it is not working. I was advised by my teacher to turn this piece of code into a procedure, see if I have any luck, then get back to him. I was hoping somebody could pick out what is wrong with my procedure and either point it out to me or correct it. Any help would be much appreciated. I apologize if my formatting for the question is not spectacular, this is my first post.
from pygame import*
font.init()
comicFont=font.SysFont("ComicSansMS",12)
screen = display.set_mode((500,500))
binaryWord = str(100101)
binaryDigits = len(binaryWord)
binaryBlit = range(0,10)
binaryGraphicX = 0
color = (0,0,0)
color2 = (125,125,125)
pos = (binaryGraphicX,200)
radius = 15
width = 0
while True:
for binaryDigit in range (0,binaryDigits):
TxtPic = []
binaryGraphicX = binaryGraphicX + 25
if binaryWord[binaryDigit] == 1:
running=True
while running:
for evnt in event.get():
if evnt.type==QUIT:
running = False
event.get()
draw.circle(screen,color,pos,radius)
display.flip()
TxtPic[binaryDigit]=comicFont.render(str(2**binaryBlit),True,(0,0,0))
screen.blit(TxtPic[binaryDigit],(binaryGraphicX,220))
elif binaryWord[binaryDigit] == 0:
running=True
while running:
for evnt in event.get():
if evnt.type==QUIT:
running = False
event.get()
draw.circle(screen,color2,pos,radius)
display.flip()
TxtPic[binaryDigit]=comicFont.render(str(2**binaryBlit),True,(0,0,0))
screen.blit(TxtPic[binaryDigit],(binaryGraphicX,220))
quit()
Below is where I call on the procedure
running=True
while running:
for evnt in event.get():
if evnt.type==QUIT:
running = False
event.get()
screen.fill((255,255,255))
TxtPic1=comicFont.render(str(solution),True,(255,255,255))
screen.blit(TxtPic1,(200,200))
binaryGraphics(binaryNumber)
display.flip()
display.quit()
I have been looking through your code and the first obvious problem I found was that you are comparing a character/string to an int in your if statements.
ie.
String:
binaryWord = str(100101)
String to Int comparison: (would return false and skip)
if binaryWord[binaryDigit] == 1:
Try this instead:
if binaryWord[binaryDigit] == "1":
Your program never has a chance to get to your code that draws text/circles.

Categories