Kids Programming fun Activities Programs — Answers
Tic Tac Toe Game :
Explanation: This code creates a simple Tic Tac Toe game using Python. The game board is represented as a 3x3 list, and each player is assigned a symbol (‘X’ or ‘O’). The code uses a while loop to prompt the players to take turns entering their moves, and checks for a win condition after each turn. The print_board
function is used to display the current state of the board, and the is_winner
function is used to check for a win condition. The game ends when one player wins, or the board is filled and no player has won.
def print_board(board):
for row in board:
print(row)
def is_winner(board, player):
for row in board:
if row.count(player) == 3:
return True
for col in range(3):
if board[0][col] == player and board[1][col] == player and board[2][col] == player:
return True
if board[0][0] == player and board[1][1] == player and board[2][2] == player:
return True
if board[0][2] == player and board[1][1] == player and board[2][0] == player:
return True
return False
board = [ [' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
players = ['X', 'O']
current_player = players[0]
while True:
print_board(board)
row = int(input("Enter row: "))
col = int(input("Enter column: "))
if board[row][col] != ' ':
print("That space is already taken!")
continue
board[row][col] = current_player
if is_winner(board, current_player):
print(f"{current_player} wins!")
break
if all(' ' not in row for row in board):
print("It's a tie!")
break
current_player = players[1] if current_player == players[0] else players[0]
Hangman :
import random
words = ['apple', 'banana', 'cherry', 'donut', 'elephant', 'frog', 'giraffe', 'house', 'ice cream', 'jacket']
word = random.choice(words)
letters_guessed = set()
max_guesses = 6
while max_guesses > 0:
print("Guess a letter:")
guess = input().lower()
letters_guessed.add(guess)
if guess not in word:
max_guesses -= 1
print(f"Incorrect! You have {max_guesses} guesses left.")
if max_guesses == 0:
print(f"Sorry, you lose! The word was '{word}'.")
else:
print("Correct!")
if all(letter in letters_guessed for letter in word):
print(f"Congratulations, you win! The word was '{word}'.")
break
print(f"Letters guessed: {' '.join(letters_guessed)}")
Explanation: This code creates a simple Hangman game using Python. The game randomly chooses a word from a list, and the player must guess letters in the word. The player has a limited number of guesses (6 in this case), and if they fail to guess the word within the limit, they lose.
Happy Reading…Comments welcomed.