A novice's hangman project: Dealing with duplicate letters - python

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.

Related

For loop breaks whole script

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]))

How to select an item from the selected list?

The player enters the letter (a-z).
The program randomizes a word from a list starting with the entered letter and displays the drawn word.
What to do to make the entered key the name of the list from which it will be possible to randomly select a word beginning with the entered character?
Possibly what other way to do this?
Thank you.
Code:
import random
import pygame
# list of letters (a-z)
a = ["ananas", "arbuz", "agrest"]
b = ["banan", "balon", "beton"]
c = ["cytryna", "cebula", "candy"]
# ...
z = ["zebra", "zombie", "zonk"]
pygame.init()
screen = pygame.display.set_mode((0, 0))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN :
if event.key == pygame.K_ESCAPE:
running = False
else:
print(event.unicode)
pygame.quit()
I implemented the following function using a dictionary though it is not necessary. Depending on what you would like to do with the word list, you can write the script with or without using the dictionary. (Both of which should be easy to directly implement into your pygame script)
import keyboard
import random
a = ["ananas", "arbuz", "agrest"]
b = ["banan", "balon", "beton"]
c = ["cytryna", "cebula", "candy"]
# ...
words_dict = {}
words_dict['a'] = a
words_dict['b'] = b
words_dict['c'] = c
# ...
while True:
try:
if keyboard.is_pressed('a'):
print(random.choice(words_dict['a']))
break
elif keyboard.is_pressed('b'):
print(random.choice(words_dict['b']))
break
elif keyboard.is_pressed('c'):
print(random.choice(words_dict['c']))
break
# implement more elif here
except:
break
Instead of assigning each list with a key into the dict like what I did above, you can also directly create a dict with everything included:
words_dict = {
'a': ["ananas", "arbuz", "agrest"],
'b': ["banan", "balon", "beton"],
# and so on
}
Without using a dictionary:
import keyboard
import random
a = ["ananas", "arbuz", "agrest"]
b = ["banan", "balon", "beton"]
c = ["cytryna", "cebula", "candy"]
# ...
while True:
try:
if keyboard.is_pressed('a'):
print(random.choice(a))
break
elif keyboard.is_pressed('b'):
print(random.choice(b))
break
elif keyboard.is_pressed('c'):
print(random.choice(c))
break
# implement more elif here
except:
break
============================================================
Update: The following script detects the user's key clicks and retrieves/displays the correct information without having to use cases to check which key the user entered.
import random
import msvcrt
words_dict = {
'a': ["ananas", "arbuz", "agrest"],
'b': ["banan", "balon", "beton"],
'c': ["cytryna", "cebula", "candy"]
# ...
}
while True:
if msvcrt.kbhit():
key_pressed = msvcrt.getch()
try:
if words_dict.__contains__(key_pressed.decode('utf-8')):
print(random.choice(words_dict[key_pressed.decode('utf-8')]))
break
else:
print(f'Input "{key_pressed.decode("utf-8")}" is not recognized. Please try again!')
except:
break
Note that the variable key_pressed is of type bytes and needs to be decoded like above before been used.
Instead of creating separate lists for each character, consider using a dictionary to hold all of the lists, with the keys being the various characters. For instance,
ch_lsts = {
"a": ["ananas", "arbuz", "agrest"],
"b": ["banan", "balon", "beton"],
"c": ["cytryna", "cebula", "candy"],
...,
"z": ["zebra", "zombie", "zonk"]
}
Then, when you're ready to select the list of a given character, simply retrieve the specified list with ch_lsts["c"] (or whatever the character is) and do whatever you'd like to that list.

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.

making tic tac toe, code is complete without error messages but wont run?

This is my first project, I used a lot of resources from others with the same project and this is what I have come up with. I am using Jupyter notebook. I am not getting any more error messages in my code, but for some reason I can't get it to run? Also, any advice or improvements in my code would also be appreciated.
I've tried to just call the tic_tac_toe() command but nothing comes up and I'm not sure why.
def tic_tac_toe():
brd = [None] + list(range(1,10))
end = False
winner = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9), (3,5,7))
from IPython.display import clear_output
def show_board():
print(brd[1]+'|'+brd[2]+'|'+brd[3])
print(brd[4]+'|'+brd[5]+'|'+brd[6])
print(brd[7]+'|'+brd[8]+'|'+brd[9])
print()
def player_input():
marker = ''
while marker != 'x' and marker != 'o':
marker = input('Do you want to be x or o?: ')
player1 = marker
if player1 == 'x':
player2 ='o'
else:
player2 = 'x'
player_markers = [player1,player2]
def choose_number():
while True:
try:
val = int(input())
if val in brd:
return val
else:
print('\n Please choose another number')
except ValueError:
print('\n Please choose another number')
def game_over():
for a, b, c in winner:
if brd[a] == brd[b] == brd[c]:
print("{0} wins!\n".format(board[a]))
print("Congrats\n")
return True
if 9 == sum((pos == 'x' or pos == 'o') for pos in board):
print("The game ends in a tie\n")
return True
for player in 'x' or 'o' * 9:
draw()
if is_game_over():
break
print("{0} pick your move".format(player))
brd[choose_number()] = player
print()
while True:
tac_tac_toe()
if input("Play again (y/n)\n") != "y":
break
I'm not sure why it is not running normally.
There's a couple things wrong with your code here. Your indentation for one. Also wondering why your functions are all in another function. You also create a bunch of functions but never call most of them. And have some functions that do not seem to exist. There are also a lot of logic errors here and there.
Try this instead:
# numpy is a package that has a lot of helpful functions and lets you manipulate
# numbers and arrays in many more useful ways than the standard Python list allows you to
import numpy as np
def show_board(brd):
print(brd[0]+'|'+brd[1]+'|'+brd[2])
print(brd[3]+'|'+brd[4]+'|'+brd[5])
print(brd[6]+'|'+brd[7]+'|'+brd[8])
print()
def player_input():
marker = ''
while marker != 'x' and marker != 'o':
marker = input('Do you want to be x or o?: ')
player1 = marker
if player1 == 'x':
player2 ='o'
else:
player2 = 'x'
player_markers = [player1,player2]
return player_markers
def choose_number(brd):
while True:
try:
val = int(input())
if brd[val-1] == "_":
return val
else:
print('\nNumber already taken. Please choose another number:')
except ValueError:
print('\nYou did not enter a number. Please enter a valid number:')
def is_game_over(winner, brd):
for a, b, c in winner:
if brd[a] != "_" and (brd[a] == brd[b] == brd[c]):
print("{} wins!\n".format(brd[a]))
print("Congrats\n")
return True
if 9 == sum((pos == 'x' or pos == 'o') for pos in brd):
print("The game ends in a tie\n")
return True
# I split this function in two because the "is_game_over" code was included here
# instead of being by itself.
def game_over(winner, brd, player_markers):
last = 0
# The first player is the one stored in "player_markers[0]"
player = player_markers[0]
# There are nine turns so that is what this is for. It has nothing to do with
# 'x' or 'o'. And one more turn is added for the "is_game_over" to work in
# case of a tie.
for i in range(10):
if is_game_over(winner, brd):
break
print()
print("{0} pick your move [1-9]:".format(player))
brd[choose_number(brd)-1] = player
show_board(brd)
# This is added to change from one player to another
# by checking who was the last one (look up ternary operators)
player = player_markers[1] if last==0 else player_markers[0]
last = 1 if last==0 else 0
def tic_tac_toe():
brd = ["_"] * 9
end = False
winner = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,8),(3,6,9),(1,5,9),(3,5,7))
winner = np.array([list(elem) for elem in winner]) - 1
player_markers = player_input()
show_board(brd)
game_over(winner, brd, player_markers)
while True:
tic_tac_toe()
if input("Play again (y/n)\n") != "y":
break

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')

Categories