Skip to content

Instantly share code, notes, and snippets.

@mdvsh
Last active May 5, 2021
Embed
What would you like to do?
Games, written in python : Hangman, Hunt The Wumpus (CLI), TicTacToe
# Import modules here
import time
import random
import sys
goalWord = ""
shownWord = ""
guess = ""
correctLetters = ""
incorrectLetters = ""
lives = 7
length = len(goalWord)
correctPercentage = 0
lettersLeftToGuess = ""
win = False
uniqueChar = 0
title = """
___ ___ ___ ___ ___ ___ ___
/__/\\ / /\\ /__/\\ / /\\ /__/\\ / /\\ /__/\\
\\ \\:\\ / /::\\ \\ \\:\\ / /:/_ | |::\\ / /::\\ \\ \\:\\
\\__\\:\\ / /:/\\:\\ \\ \\:\\ / /:/ /\\ | |:|:\\ / /:/\\:\\ \\ \\:\\
___ / /::\\ / /:/~/::\\ _____\\__\\:\\ / /:/_/::\\ __|__|:|\\:\\ / /:/~/::\\ _____\\__\\:\\
/__/\\ /:/\\:\\ /__/:/ /:/\\:\\ /__/::::::::\\ /__/:/__\\/\\:\\ /__/::::| \\:\\ /__/:/ /:/\\:\\ /__/::::::::\\
\\ \\:\\/:/__\\/ \\ \\:\\/:/__\\/ \\ \\:\\~~\\~~\\/ \\ \\:\\ /~~/:/ \\ \\:\\~~\\__\\/ \\ \\:\\/:/__\\/ \\ \\:\\~~\\~~\\/
\\ \\::/ \\ \\::/ \\ \\:\\ ~~~ \\ \\:\\ /:/ \\ \\:\\ \\ \\::/ \\ \\:\\ ~~~
\\ \\:\\ \\ \\:\\ \\ \\:\\ \\ \\:\\/:/ \\ \\:\\ \\ \\:\\ \\ \\:\\
\\ \\:\\ \\ \\:\\ \\ \\:\\ \\ \\::/ \\ \\:\\ \\ \\:\\ \\ \\:\\
\\__\\/ \\__\\/ \\__\\/ \\__\\/ \\__\\/ \\__\\/ \\__\\/
He doesn't know that your IQ may lead to his demise.
"""
print(title)
goalWord = str(input("Player 1, Enter Word >>> "))
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "y", "v",
"w", "x", "y", "z"]
for letter in letters:
if letter in goalWord:
uniqueChar += 1
hang_boi_stages = [
"""
+---+
| |
|
|
|
|
=========
Hey Waddup Bruv ! How You Doin' ?
""",
"""
+---+
| |
O |
|
|
|
=========
Bro WTH ! Why's there's a noose around mah Neck!?
""",
"""
+---+
| |
O |
| |
| |
|
|
=========
Dude Seriously ! What are you doing ????
""",
"""
+---+
| |
O |
/| |
| |
|
|
=========
Aww Crap ! You're trying to hang me! right ?
""",
"""
+---+
| |
O |
/|\\ |
| |
|
|
=========
Bro You should've given up by now YO! SRSLY...
""",
"""
+---+
| |
O |
/|\\ |
| |
/ |
|
=========
Ok Ok! Go On! You are of no use.... You'll kill me I'm sure now!
""",
"""
+---+
| |
O |
/|\\ |
| |
/ \\ |
|
=========
________
||
||
------
||
||
|| in the CHATS!
"""
]
def guessLetter():
global guess
global correctLetters
global incorrectLetters
global lives
global correctPercentage
global win
if win == False:
if lives >= 1:
guess = input("What letter would you like to guess: ")
if "IWIN" in guess: # Little cheat code!
win = True
if len(guess) == 1 and guess in goalWord:
if guess not in correctLetters:
correctLetters = guess + " " + correctLetters # Keep track of correct letters
for letter in guess:
correctPercentage += 1
else:
lives += -1
else:
if len(guess) != 1:
lives += -1
if len(guess) == 1:
if guess not in incorrectLetters:
incorrectLetters = guess + " " + incorrectLetters
lives += -1
else:
lives += -1
else:
print(hang_boi_stages[6])
print("GAME-OVER\nThe word was \"" + goalWord +"\"")
exit()
def draw_boi():
if lives >= 1:
print(hang_boi_stages[(abs(7-lives))])
def showIncorrectGuesses():
if lives > 0:
print("\nIncorrect guesses: " + str(incorrectLetters))
def showProgress():
global guess
global shownWord
global length
global correctPercentage
global correctLetters
global win
global uniqueChar
if lives >= 1 and win == False:
shownWord = goalWord
for letter in shownWord:
if letter in correctLetters:
print(" " + letter + " ")
else:
print(" _ ")
print()
if correctPercentage == uniqueChar:
win = True
def winScreen():
println("Ahh! You saved the Hang Boi! Great Job\n Player 2 Wins!")
print("CONGRATULATIONS\nYou guessed the word \"" + goalWord + "\" correctly \nYOU WIN!")
time.sleep(2)
sys.exit()
while lives >= 0:
while not win:
draw_boi()
showProgress()
showIncorrectGuesses()
guessLetter()
else:
winScreen()
break
'''
Project : Hunt The Wumpus - CMD Edition
@author : pseudocodenerd
Game Description from Wiki :
Hunt the Wumpus is a text-based adventure game developed by Gregory Yob in 1973.
In the game, the player moves through a series of connected caves, arranged in a dodecahedron,
as they hunt a monster named the Wumpus.
The turn-based game has the player trying to avoid fatal bottomless pits and "super bats" that will move them around the cave system;
the goal is to fire one of their "crooked arrows" through the caves to kill the Wumpus.
The string outputs are the same as the original BASIC game.
It has a 2 levels : 1. Amateur Hunter 2. The Great White Hunter.
DISCLAIMER : OOP has been extensively ustilised.
'''
#getting the required packages
import random, sys, time
'''-------------------------BUILDER FUNCTIONS-------------------------------------'''
#defining the room. A room has a number associated with it.
class Room:
def __init__(self, **kwargs):
self.name = ''
self.number = 0
self.room_desc = ""
self.attached_to = []
for key, value in kwargs.items():
setattr(self, key, value)
def __str__(self):
return str(self.number)
def add_connect(self, arg_connect):
if arg_connect not in self.attached_to:
self.attached_to.append(arg_connect)
def remove_connect(self, arg_connect):
if arg_connect in self.attached_to:
self.attached_to.remove(arg_connects)
def get_connects(self):
return self.attached_to
def get_number_of_connects(self):
return len(self.attached_to)
def is_connect_valid(self, arg_connect):
return arg_connect in self.attached_to
def describe(self):
if len(self.room_desc) > 0:
print(self.room_desc)
else:
print("You are in room {}.\nAvailable passages are {}".format(self.number, self.attached_to))
#defining the various entities in a room i.e. Wumpus, Player, pits and bats. A room has a number associated with it.
class Entity:
def __init__(self, **kwargs):
self.location = 0
for key, value in kwargs.items():
setattr(self, key, value)
def get_current_location(self):
return self.location.number
def move(self, new_position):
if new_position.number in self.location.attached_to or new_position == self.location:
self.location = new_position
return True
else:
return False
def is_move_valid(self, new_position):
return new_position.number in self.location.attached_to or new_position == self.location
def wakeup(self, the_cave):
if random.randint(0, 3): # Setting probability of moving correctly to 0.75
self.location = the_cave[random.choice(self.location.attached_to) - 1]
def is_hit(self, the_room):
return self.location == the_room
#creating the cave
def create_cave():
# 20 since dodecahedron.
for number in range(20):
Cave.append(Room(number = number + 1))
# Connecting graph vertices together.
for ver, room in enumerate(Cave):
# right
if ver == 9:
room.add_connect(Cave[0].number)
elif ver == 19:
room.add_connect(Cave[10].number)
else:
room.add_connect(Cave[ver +1].number)
#left
if ver == 0:
room.add_connect(Cave[9].number)
elif ver == 10:
room.add_connect(Cave[19].number)
else:
room.add_connect(Cave[ver -1].number)
#connect to the room in the other ring
if ver < 10:
room.add_connect(Cave[ver +10].number) # me --> room
Cave[ver +10].add_connect(room.number) # room --> me
def generate_entities(the_cave):
Entities = []
Samples = random.sample(the_cave, 6)
for room in Samples:
Entities.append(Entity(location = room))
return Entities
'''-------------------------PLAYER FUNCTIONS-------------------------------------'''
Cave = []
create_cave()
# Make player, wumpus, bats, pits and put into cave.
Wumpus, Player, Pit1, Pit2, Bats1, Bats2 = generate_entities(Cave)
Arrows = 5
print("""\n Welcome to the cave, Great White Hunter.
You are hunting the Wumpus.
On any turn you can move or shoot.
Commands are entered in the form of ACTION LOCATION
IE: 'SHOOT 12' or 'MOVE 8'
type 'HELP' for instructions.
'iquit' to end the game.
""")
diffi = str(input("Enter Difficulty Level (easy/medium/EPIC) : "))
if diffi == "easy":
Arrows = 12
elif diffi[0] == "m":
Arrows = 8
elif diffi[0] == "E":
Arrows = 4
elif diffi == "iquit":
sys.exit()
else:
print("No Difficulty specified.\n Using default settings.")
Arrows = 5
while True:
Player.location.describe()
#Check each <Player.location.connects_to> for hazards.
for room in Player.location.attached_to:
if Wumpus.location.number == room:
print("I smell a Wumpus!")
if Pit1.location.number == room or Pit2.location.number == room:
print("I feel a draft!")
if Bats1.location.number == room or Bats2.location.number == room:
print("Bats nearby!")
raw_command = input("\n> ")
command_list = raw_command.split(' ')
command = command_list[0].upper()
if len(command_list) > 1:
try:
move = Cave[int(command_list[1]) -1]
except:
print("\n **What??")
continue
else:
move = Player.location
if command == 'HELP' or command == 'H':
show_instructions()
continue
elif command == 'QUIT' or command == 'Q':
print("\nOK, Bye.")
time.sleep(3)
sys.exit()
elif command == 'MOVE' or command == 'M':
if Player.move(move):
if Player.location == Wumpus.location:
print("... OOPS! YOU BUMPED A WUMPUS!")
Wumpus.wakeup(Cave)
else:
print("\n **You can't get there from here")
continue
elif command == 'SHOOT' or command == 'S':
if Player.is_move_valid(move):
print("\n-Twang-")
if Wumpus.location == move:
print("\n Good Shooting!! You hit the Wumpus. \n Wumpi will have their revenge.\n")
time.sleep(3)
sys.exit()
else:
print("\n Stop trying to shoot through walls.")
Wumpus.wakeup(Cave)
Arrows -= 1
if Arrows == 0:
print("\n You are out of arrows\n Better luck next time\n")
time.sleep(3)
sys.exit()
else:
print("\n Say Again?")
continue
if Player.location == Bats1.location or Player.location == Bats2.location:
print("ZAP--SUPER BAT SNATCH! ELSEWHEREVILLE FOR YOU!")
Player.location = random.choice(Cave)
if Player.location == Wumpus.location:
print("TROMP TROMP - WUMPUS GOT YOU!\nGAME OVER!")
time.sleep(3)
sys.exit()
elif Player.location == Pit1.location or Player.location == Pit2.location:
print("YYYIIIIEEEE . . . FELL INTO A PIT!\nGAME OVER!")
time.sleep(3)
sys.exit()
else: # Keep playing
pass
'''
PvC Tic Tac Toe Game.
(AI)
'''
from random import randint
print("TicTacToe\nWelcome, You are X. The computer is O.\n\nLet's Start.")
game_board = [" ", " ", " ",
" ", " ", " ",
" ", " ", " "]
temp_board = [" ", " ", " ",
" ", " ", " ",
" ", " ", " "]
def temp_row_check(a, one, two, three):
if a == temp_board[one] == temp_board[two] == temp_board[three]:
return True;
def main_check(a):
if temp_row_check(a,0,3,6) == True:
return True
elif temp_row_check(a,1,4,7) == True:
return True
elif temp_row_check(a,2,5,8) == True:
return True
elif temp_row_check(a,0,1,2) == True:
return True
elif temp_row_check(a,3,4,5) == True:
return True
elif temp_row_check(a,6,7,8) == True:
return True
elif temp_row_check(a,0,4,8) == True:
return True
elif temp_row_check(a,2,4,6) == True:
return True
else:
return False
def check_freepos(freepos):
for i in freepos:
temp_board[i] = "O"
if main_check("O") == True:
return True
break
else:
return False
break
temp_board[i] = " "
def display_board():
print("+-----------+")
print("Board move grid:\n 0 1 2\n 3 4 5\n 6 7 8")
print("=================")
print("|",game_board[0], "|",game_board[1], "|",game_board[2], "|")
print("-------------")
print("|",game_board[3], "|",game_board[4], "|",game_board[5], "|")
print("-------------")
print("|",game_board[6], "|",game_board[7], "|",game_board[8], "|")
def check_row(a, one, two, three):
if a == game_board[one] == game_board[two] == game_board[three]:
return True;
display_board()
def check_all(a):
if check_row(a,0,3,6) == True:
return True
elif check_row(a,1,4,7) == True:
return True
elif check_row(a,2,5,8) == True:
return True
elif check_row(a,0,1,2) == True:
return True
elif check_row(a,3,4,5) == True:
return True
elif check_row(a,6,7,8) == True:
return True
elif check_row(a,0,4,8) == True:
return True
elif check_row(a,2,4,6) == True:
return True
else:
return False
play = True
def ai_move():
freepos = []
check = False
check2 = False
k = 0
for i in range(0,9):
if game_board[i] != "X" and game_board[i] != "O":
freepos.append(i)
for i in range(0,9):
temp_board[i] = game_board[i]
for i in freepos:
temp_board[i] = "X"
if main_check("X") == True:
k = i
check = True
check2 = True
break
else:
check = False
temp_board[i] = " "
if check == False:
for i in freepos:
temp_board[i] = "O"
if main_check("O") == True:
return int(i)
break
else:
return freepos[randint(0, (len(freepos) - 1))]
break
temp_board[i] = " "
else:
if check_freepos(freepos) == True:
for i in freepos:
temp_board[i] = "O"
if main_check("O") == True:
return int(i)
break
else:
return freepos[randint(0, (len(freepos) - 1))]
break
temp_board[i] = " "
else:
return int(k)
def play_game():
freepos = []
for i in range(0,9):
if game_board[i] != "X" and game_board[i] != "O":
freepos.append(i)
if len(freepos) == 0 and check_all("O") == False and check_all("X") == False:
return True
else:
return False
while play == True:
uspos = int(input("Enter position:"))
if game_board[uspos] != "X"and game_board[uspos] != "O" and play_game() == False:
game_board[uspos] = "X"
if check_all("X") == True:
display_board()
print("You win! Congratulations")
break
elif check_all("O") == True:
display_board()
print("F.\nYou lose.")
break
if play_game() == False:
oppos = ai_move()
game_board[oppos] = "O"
display_board()
if check_all("X") == True:
print("You win! Congratulations")
break
elif check_all("O") == True:
print("F.\nYou lose.")
break
else:
display_board()
print("GG! It's a draw.")
break
else:
print("Sorry, that spot has already been taken. :-(")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment