Here is a program I did for my coding class. I'm new at this so I'm learning as I go. I have everything I need so far except a way to exit the game at any point. I have a def move_between_rooms function I created where I thought I could put the exit, but I can't seem to get it to work correctly. The game itself works well, I just don't have an exit. Any help is appreciated. And please go easy on me as it's my first full program.
import time
import sys
import colorama
from colorama import Fore, Back, Style
colorama.init()
def main_menu():
# Print instructions and intro
fprint(Fore.YELLOW + "Dragon Adventure Game!",3)
print_slow(Fore.BLUE + "You are John Snow, the Dragon Slayer,\n" \
"The Evil Queen is holding the town hostage with her Dragon.\n" \
"You have been summoned by the King to slay the Mighty Dragon.\n" \
"You MUST collect all 6 items to slay the Dragon, or perish in a ball of flames.\n" \
"Move commands: go South, go North, go East, go West, Exit\n" \
"Add to Inventory: get 'item name'" + Fore.RESET)
def move_between_rooms(current_room, move, rooms):
# move to corresponding room
current_room = rooms[current_room][move]
return current_room
def replay():
return input(Fore.BLUE + "Do you want to play again? Enter Yes or No: " +
Fore.RESET).lower().startswith('y')
def exit():
sys.exit()
def fprint(str, delay = 0):
print("\n" + str)
time.sleep(delay)
def print_slow(str, delay = 0.01):
for letter in str:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(delay)
print("\n")
def get_item(current_room, move, rooms, inventory):
# add item to inventory and remove it from the room
inventory.append(rooms[current_room]['item'])
del rooms[current_room]['item']
def main():
# dictionary of connecting rooms with items
rooms = {
'Black Hall': {'South': 'Galley', 'North': 'Kings Quarters', 'East': 'Dungeon',
'West': 'Throne Room'},
'Galley': {'North': 'Black Hall', 'East': 'Armory', 'item': 'Oathkeeper'},
'Armory': {'West': 'Galley', 'item': 'Shield'},
'Kings Quarters': {'South': 'Black Hall', 'East': 'Maesters Library', 'item': 'Kings
Crown'},
'Maesters Library': {'West': 'Kings Quarters', 'item': 'Spell Book'},
'Throne Room': {'East': 'Black Hall', 'item': 'Fire Stone'},
'Dungeon': {'West': 'Black Hall', 'North': 'Dragons Lair', 'item': 'Armor'},
'Dragons Lair': ''
}
s = ' '
# list for storing player inventory
inventory = []
# starting room
current_room = "Black Hall"
# show the player the main menu
main_menu()
while True:
# handle the case when player encounters the 'villain'
if current_room == 'Dragons Lair':
# winning case
if len(inventory) == 6:
print_slow(Fore.YELLOW + "Congratulations you have Slain the Dragon and saved
the town!\n" \
"Thank you for playing!" + Fore.RESET)
if replay():
main()
if not replay():
break
# losing case
else:
print_slow(Fore.YELLOW + "\nOh dear! You did not collect all of the items!
\n"\
"You were caught by the Evil Queen and set on fire by her Dragon! \n" \
"The Dragon escaped and set the town on fire! \n" \
"Thank you for playing!" + Fore.RESET)
if replay():
main()
if not replay():
break
# Tell the user their current room, inventory and prompt for a move, ignores case
print(Fore.GREEN + "You are in the " + current_room)
print(inventory)
# tell the user if there is an item in the room
if current_room != 'Dragons Lair' and 'item' in rooms[current_room].keys():
print("In the room, there is a {}".format(rooms[current_room]['item']))
print(Fore.YELLOW + "------------------------------" + Fore.RESET)
move = input(Fore.YELLOW + "Enter your move:\n-->" ' ' + Fore.RESET).title().split()
# handle if the user enters a command to move to a new room
if len(move) >= 2 and move[1] in rooms[current_room].keys():
current_room = move_between_rooms(current_room, move[1], rooms)
continue
# handle if the user enter a command to get an item
elif len(move[0]) == 3 and move[0] == 'Get' and ' '.join(move[1:]) in
rooms[current_room]['item']:
print(Fore.YELLOW + "You added the {} to your
inventory".format(rooms[current_room]['item']))
print("------------------------------" + Fore.RESET)
get_item(current_room, move, rooms, inventory)
continue
# handle if the user enters an invalid command
else:
fprint(Fore.YELLOW + "You can't go that way, please try again" + Fore.RESET,1)
continue
main()
Related
So I am trying to make this continue from get_burger_choice to get_burger price to where it would flow and finish the program. I am trying to write this program to where I could get the type of burger then the price from get_burger_price. Heres the problem, I do not know how to intergrate it towards doing that. I am completely stuck after the part where it says "no" at the end part of get_burger_choice to where I can transition to get_burger_price
Here is the code that I used : the part highlighted is where Im having trouble transitioning:I would like it to where if the user says no, it would ask if they would like to see the price, and it would transition towards get_burger_price
def get_burger_choice():
SIZE = 3
burgers = ["Cheesy", "Regular", "Veggie" ]
search = True
while search == True:
index = 0
found = False
print("What type of burger would you like?")
searchValue = input()
while found == False and index <= SIZE - 1:
if burgers[index].lower()==searchValue.lower():
found = True
else:
index = index + 1
if found:
print("That is on our menu")
else:
print("That is not in our menu")
print("Do you want see another burger? yes/no: ")
tryagain = input()
if tryagain.lower() =='no':
print("Would you like to see the price? yes or no: ")
if
def price_burger(burger_choice, burger_price):
if burger_price == 'cheesy':
burger_price = 3.00
elif burger_choice == 'regular':
burger_price = 2.00
elif burger_choice == 'veggie':
burger_price = 2.00
else:
print("we do not have that, sorry")
return burger_price
def total_price(burger_price, burger_choice=None):
print("The burger cost $", burger_price)
def closing(burger_choice):
if burger_choice == 'cheesy':
print("Nice selection, This is our best!")
else:
print("enjoy!")
def main(burger_price = 0):
choice = "yes"
while choice != "no":
burger_choice = get_burger_choice()
burger_price = price_burger(burger_choice,burger_price)
total_price(burger_price)
closing(burger_choice)
choice = input("\nWould you like to try again? yes or no: ")
main()
I was wondering how I'm supposed to get my "balance" variable to change depending on the value added or subtracted to it each time, without resetting for the next loop.
At the moment it will add or subtract a given value and return the correct number but on the next loop it will use the original base value instead of using the new value from the previous loop.
import time
print ("Welcome to balance tracker!")
sBal=float(input ("Starting balance: "))
float(sBal)
transactionAmounts = []
transactionTypes = []
print ("Your current balance is", '$',sBal)
while True:
input("Press enter to continue")
print ("""
------------
[A]ddition
[S]ubtraction
[H]istory
[I]nformation
[Q]uit
------------
""")
choice=input("What would you like to do? ")
choice = choice.upper()
if choice == "A":
aval=float(input ("Enter amount you would like to add here: "))
nBal=(sBal)+(aval)
transactionTypes.append('Addition')
transactionAmounts.append(float(aval))
balance = float(sBal) + aval
print ("Your current balance is $",balance)
elif choice == "S":
aval=input("Enter amount you would like to subtract here: ")
nBal=float(sBal)-float(aval)
transactionTypes.append('Subtraction')
transactionAmounts.append (float(aval))
balance = float(sBal) - aval
print ("Your current balance is $",balance)
elif choice == "H":
aCount = 1
tCount = 0
for i in transactionAmounts:
print ('Transaction',aCount,':',transactionTypes[tCount],i)
aCount = aCount + 1
tCount = tCount + 1
elif choice == "Q":
break
else:
print ("invalid choice")
The solution to your problem is that when your assigning your balance variable, your adding sBal(starting balance) every time to the amount they would like to add... This is causing the balance to always be set back to the starting balance plus or minus the amount added. Try defining sBal as balance also like so...
balance = float(input("Starting balance: ")) #line 5
float(sBal) #<<<can be deleted #line 6
Also don't forget to alter anywhere in the code that calls sBal to call balance.
print("Your current balance is ", "$", difference) #line 9
balance = float(balance) (+ or -) aval #lines 30 and 37
Also you can delete your nBal(new balance) as it is never called.
I am playing Garry's Mod and I'm trying to make an e2 chip that allows me to add guns to a price list with for example "!name store name" and then "+ AK47- $500". This is what I have so far and I can't seem to figure out how to make the screen say what I say!
#name manual prices screen
#inputs Screen:wirelink
#outputs
#persist A:array Cname:string [M1 M2 M3 M4]:array
#trigger
runOnChat(1)
Say = owner():lastSaid():explode(" ")
if(Say[1,string] == "+")
{
chatClk(owner())
hideChat(1),Screen:writeString("Prices:" ,1,3,100,5,0)
}
if(Say[1,string] == "!name")
{
Name = owner():lastSaid():explode(" ")(Say[2,string])
print(Name:name() + " added")
M4[M4:count()+1,entity] = Player
Screen[2041] = 1
}
interval(100)
I am in dire need of help with a for loop. I'm trying to go through a for loop in Lua with the Corona SDK, but I am doing something wrong but I don't know what. See below for my code:
function moveLift(event)
for j=1,4,1 do
if event.phase == "began" then
markY = event.target.y
elseif event.phase == "moved" then
local y = (event.y - event.yStart) + markY
event.target.y = y
elseif event.phase == "ended" then
if (hasCollided( event.target, hotSpots[j] )) then
print("hasCollided with floor: ", hotSpots[j].floor)
if (event.target.destination == hotSpots[j].floor) then
print("correct floor")
succesfullPassengers = succesfullPassengers + 1
if succesfullPassengers == PASSENGER_AMOUNT then
print("game over")
end
else
print("Wrong! elevator has collided with floor: ", hotSpots[j].floor)
end
end
end
return true
end
end
What I'm trying to do here is checking when I drag and drop an elevator on screen on what floor it has landed. I've created hotspots (basically hitboxes and currently serving as art placeholder) and placed them in the hotSpot table like this:
-- Create elevator hotspots
for k=1,4,1 do
hotSpots[k] = display.newRect( gameAreaGroup, 0, 0, 50, 75 )
hotSpots[k].alpha = 0.25 --Show hotspots with alpha
hotSpots[k].floor = k -- The floor id
print("Created hotspot on floor: ",hotSpots[k].floor)
hotSpots[k].x = display.contentWidth *0.5
hotSpots[k].y = firstFloor - (FLOOR_HEIGHT * k)
hotSpots[k]:setFillColor( 255,0,0 )
hotSpots[k]:addEventListener( "tap", returnFloor ) -- Check floor value
gameAreaGroup:insert(hotSpots[k])
end
I check if every hotspot has a unique floor value with a test function called returnFloor, which they have (1,2,3,4). When I drag and drop my elevator on the first floor, I receive the message "Wrong! elevator has collided with floor: 1", but on any other floor I receive the message: "hasCollided with floor: 1". So there must be something wrong with the for loop in my moveLift function because it only returns floor 1 and not any other floor.
PS: the correct floor is 4, the top floor.
You have "return true" inside your for loop, so it will never get past j=1. I think you may need to move that statement up inside the last if statement, or below the "end" that follows it (without knowing the full logic, I'm not sure what the returned value is used for).
Last lines of code should not be end end return true end end but
end end end return true end so the return is after the loop has completed.
I am working on a larger project to write a code so the user can play Connect 4 against the computer. Right now, the user can choose whether or not to go first and the board is drawn. While truing to make sure that the user can only enter legal moves, I have run into a problem where my function legal_moves() takes 1 positional argument, and 0 are given, but I do not understand what I need to do to male everything agree.
#connect 4
#using my own formating
import random
#define global variables
X = "X"
O = "O"
EMPTY = "_"
TIE = "TIE"
NUM_ROWS = 6
NUM_COLS = 8
def display_instruct():
"""Display game instructions."""
print(
"""
Welcome to the second greatest intellectual challenge of all time: Connect4.
This will be a showdown between your human brain and my silicon processor.
You will make your move known by entering a column number, 1 - 7. Your move
(if that column isn't already filled) will move to the lowest available position.
Prepare yourself, human. May the Schwartz be with you! \n
"""
)
def ask_yes_no(question):
"""Ask a yes or no question."""
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question,low,high):
"""Ask for a number within range."""
#using range in Python sense-i.e., to ask for
#a number between 1 and 7, call ask_number with low=1, high=8
low=1
high=NUM_COLS
response = None
while response not in range (low,high):
response=int(input(question))
return response
def pieces():
"""Determine if player or computer goes first."""
go_first = ask_yes_no("Do you require the first move? (y/n): ")
if go_first == "y":
print("\nThen take the first move. You will need it.")
human = X
computer = O
else:
print("\nYour bravery will be your undoing... I will go first.")
computer = X
human = O
return computer, human
def new_board():
board = []
for x in range (NUM_COLS):
board.append([" "]*NUM_ROWS)
return board
def display_board(board):
"""Display game board on screen."""
for r in range(NUM_ROWS):
print_row(board,r)
print("\n")
def print_row(board, num):
"""Print specified row from current board"""
this_row = board[num]
print("\n\t| ", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num], "|", this_row[num],"|")
print("\t", "|---|---|---|---|---|---|---|")
# everything works up to here!
def legal_moves(board):
"""Create list of column numbers where a player can drop piece"""
legals = []
if move < NUM_COLS: # make sure this is a legal column
for r in range(NUM_ROWS):
legals.append(board[move])
return legals #returns a list of legal columns
#in human_move function, move input must be in legal_moves list
print (legals)
def human_move(board,human):
"""Get human move"""
legals = legal_moves(board)
print("LEGALS:", legals)
move = None
while move not in legals:
move = ask_number("Which column will you move to? (1-7):", 1, NUM_COLS)
if move not in legals:
print("\nThat column is already full, nerdling. Choose another.\n")
print("Human moving to column", move)
return move #return the column number chosen by user
def get_move_row(turn,move):
move=ask_number("Which column would you like to drop a piece?")
for m in range (NUM_COLS):
place_piece(turn,move)
display_board()
def place_piece(turn,move):
if this_row[m[move]]==" ":
this_row.append[m[move]]=turn
display_instruct()
computer,human=pieces()
board=new_board()
display_board(board)
move= int(input("Move?"))
legal_moves()
print ("Human:", human, "\nComputer:", computer)
Right down the bottom of the script, you call:
move= int(input("Move?"))
legal_moves()
# ^ no arguments
This does not supply the necessary board argument, hence the error message.