Fight simulator with random numbers - python

I'm trying to create a function that simulates a fight. So far I have a list and something that picks at random one of them that I found in another post. I can't seem to make an if statement that prints out “Hit!” or “Dodge!” or “Critical Hit!” when it chooses the respective word because it gives a syntax error for whatever reason. Can anyone help me? What do I do so I can make the if statement?
Health = 10
dodge = 1
dmg = 1
hit = dmg + 1
crhit = hit * 2
def fight():
while 1 == 1:
global Health
global dodge
global hit
global dmg
chances = [hit, hit, dodge, crhit, hit]
from random import choice
fight()

You have only imported the function choice, you still have to call it:
from random import choice # This makes it so we can use the function in the script.
Health = 10
dodge = 1
dmg = 1
hit = dmg + 1
crhit = hit * 2
def fight():
while 1:
mychoice = choice(chances) # We call the function. It gets a random value from the list
if mychoice == hit: # Create an if/elif for each possible outcome
dostuff()
elif ...
fight()
Then you can use an if/elif structure to do stuff with each option
Also, those global statements are not needed, as you actually aren't modifying the variables themselves (Unless you plan on doing this later).
while 1 == 1 can simply be written as while 1, as that can also be considered True.

I'm not gonna give away the entire answer, since you should work at that, but doing random.choice(testList) returns a random element from the list, you can use these to get one from hit, dodge and crhit. You can just write three if-elif statements to check for each. Short examples (you should get your answer from here),
>>> varOne = 2
>>> varTwo = 3
>>> varThree = 4
>>> from random import choice
>>> testVar = choice([varOne, varTwo, varThree])
>>> if testVar == varOne:
print 'abc'
elif testVar == varTwo:
print 'def'
else:
print 'ghi'
abc

Related

In Python, connect 4 game, check for win function does not work

I am writing a connect 4 game in python but checkforwin function isn't working, it is like it does not exists for some reason,when it is called and it is supposed to return True it does nothing, here is my code (I have added some comments to the function that isn't working):
# "\u25A1" == small square
mainList = [["\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1"],
["\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1"],
["\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1"],
["\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1"],
["\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1"],
["\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1","\u25A1"]]
def drawBoardFunc():
for i in range(6):
for j in range(7):
print(mainList[i][j],end='')
print("")
def checkForWinX(): #Here is the problem this function does nothing
#Horizontal win for "X"
for i in range(5,-1,-1):
for j in range(4):
if (mainList[i][j]=="X" and mainList[i][j+1]=="X"
and mainList[i][j+2]=="X" and mainList[i][j+3]=="X"):
return True
def checkForWinO(): #Here again the same problem
#Horizontal win for "O"
for i in range(5,-1,-1):
for j in range(4):
if (mainList[i][j]=="O" and mainList[i][j+1]=="O" and
mainList[i][j+2]=="O" and mainList[i][j+3]=="O"):
return True
drawBoardFunc()
#This list stores the row that its about to put a mark
checkRowList = [5,5,5,5,5,5,5]
player = 1
while True:
print("Player's",player,"turn")
chosenColumn = int(input("Please choose a column from 0 to 6 to play:\n"))
if checkRowList[chosenColumn] == -1:
print("Column full, please choose another column")
else:
if player == 1:
row = checkRowList[chosenColumn]
mainList[row][chosenColumn] = "Χ"
checkRowList[chosenColumn] -= 1
player = 2
drawBoardFunc()
win = checkForWinX() #Here it is called for "X"
if win==True:
print("Player one win!")
break
elif player == 2:
row = checkRowList[chosenColumn]
mainList[row][chosenColumn] = "Ο"
checkRowList[chosenColumn] -= 1
player = 1
drawBoardFunc()
if checkForWinO()==True: #Here it is called for "O" (in a little different way)
print("Player two win!")
break
I have two same checkforwin functions that make the same work, one for player "X" and one for player "O" so I refer as it is only one, I hope that it is clear, if you want more details let me know and please help.
edit: I forgot to say that this program is a work in progress and I only check for horizontal win condition.
This is a very unfortunate error, but it appears to be the following.
In your while loop, you have the following line
mainList[row][chosenColumn] = "Χ"
And in your function to check if the X player has won, you check if the cell is equal to X, like so.
mainList[i][j]=="X"
Now, the reason that the function does not return true is because the X you assign in the while loop is not the same X that you check against in the checkForWinX function. Somehow you accidently copied/used a unusual X from somewhere else.
>>> "X" == "Χ"
False
>>> "X".encode('utf-8') # this is the one you use in checkForWinX
b'X'
>>> "Χ".encode('utf-8') # this is the one you assign to mainList[row][chosenColumn]
b'\xce\xa7'
Depending on your browser, you can use ctrl+f (find) to look for X and you'll see that not each X lights up.

Is there a way to make a multiplayer dice game where the players have turns rolling and the scores tally?

I'm trying to make a code for a multiplayer dice rolling game where the user can input how many players.
I want the code to repeat until a player reaches 100 points and go on a cycle between all the players.
I've tried all sorts of functions/modules for this and asked peers and some teachers, searched online for this and all over stack overflow but couldn't find an answer.
playerPoints = {}
toRoll = ""
minPlayers = 2
maxPlayers = 4
winner = 100
double1 = 25
def players(numberOfPlayers):
numberOfPlayers = 0
while numberOfPlayers not in (str(i) for i in range (minPlayers,maxPlayers)):
numberOfPlayers = int(numberOfPlayers)
for i in range(numberOfPlayers):
playerPoints["score{}".format(i+1)] = 0
return numberOfPlayers
def diceroll():
die1 = randint(1,6)
die2 = randint(1,6)
return die1, die2
roll = 0
while roll not in (str(i) for i in toRoll):
roll = input("Press enter to roll both dice")
if roll == toRoll:
print(str(die1) + " and " + str(die2))
break
I want the code to continue however I am stuck at this point where the code only asks how many players are there and then breaks.
I called the function by doing:
numberOfPlayers = input("How many players are there? (2-4)")
players(numberOfPlayers)
diceroll(die1, die2)
roll()
Possible fix for your problem
There are all kinds of return statements in your code which makes it impossible for some code to be executed. Like in the diceroll function where you return die1 and die2 in:
return die1, die2
The code after that line is never exectuted because the function returns some values.
You say that you execute the function like so:
numberOfPlayers = input("How many players are there? (2-4)")
players(numberOfPlayers)
diceroll(die1, die2)
roll()
However, the diceroll function takes zero parameters, while you give it two (die1 and die2), this won't work. Also I don't see a roll function in your code, so that will give you an error as well.
How I would have done it
So, I know StackOverflow is not the place where we write code for you. But since there were all kinds of things in your code that I found weird. I have rewritten the code as how I would have done it:
import random
playerPoints = []
minPlayers = 2
players = 0
maxscore = 100
amountOfDice = 2
gameRound = 0
def setPlayers():
while True:
players = input("How many players are playing?\n")
if players.isdigit():
players = int(players)
if minPlayers <= players:
for i in range(players):
playerPoints.append(0)
return players
def diceroll(player, amountOfDice):
throw = 0
print("\tPlayer {0}s turn:".format(player + 1))
for i in range(amountOfDice):
die = random.randint(1, 6)
print("\t\tPlayer {0} has thrown die {1} which landed on {2}".format(player + 1, i + 1, die))
throw += die
playerPoints[player] += throw
print("\tPlayer {0}s score is now: {1}".format(player + 1, playerPoints[player]))
return throw
def checkWin(maxscore):
for player in range(players):
if (playerPoints[player] >= maxscore):
print("Player {0} wins!".format(player + 1))
return True
return False
if __name__ == "__main__":
players = setPlayers()
while True:
gameRound += 1
print("Round: {0}".format(gameRound))
for i in range(players):
diceroll(i, amountOfDice)
if (checkWin(maxscore)):
break
Now, first off, I removed some restrictions in the players function (and changed the name to setPlayers). Your code didn't have a check if the input was a number, which could result in an error. I also removed the restriction of 4 players, because the code works with every amount (if 2 or higher ofcourse).
The diceroll function now takes the player that will roll as an argument as well as the amount of dice that will be rolled.
I also added the checkWin function which checks if a player has won. It takes the maximum score as an argument.
Now this probably isn't the fastest code, however I think its understandable. If you have any questions about it, feel free to ask.

When attempting to define a global variable anywhere I get 'invalid syntax' [duplicate]

This question already has answers here:
Invalid syntax on '=' when using global
(1 answer)
Python - Change variable outside function without return
(4 answers)
Closed 2 months ago.
I am currently trying to make a hangman game. I have defined the variable 'lives' outside any functions, yet when trying to use it inside the start_game function the editor says that the variable is defined but never used. However when I try to declare it as global, whether it be inside or outside the function, it gives me an 'invalid syntax' error- specifically at the assignment operator '='.
import random
words = "dog cat log hog etc" # <-- just a huge string of a bunch of words
words = words.split()
word = random.choice(words)
# Difficulties: Easy:12 Medium:9 Hard:6
lives = 0
current = "_" * len(word)
def gameLoop():
while current != word and lives > 0:
print("Guess a letter. If you wish to exit the game, enter 'exit'")
input("")
print(lives)
def start_game():
while True:
print("Welcome to Hangman! What game mode would you like to play? Easy, medium, or hard?")
game_mode = str.lower(input(""))
if game_mode == "easy":
lives = 12
gameLoop()
break
elif game_mode == "medium":
lives = 9
gameLoop()
break
elif game_mode == "hard":
lives = 6
gameLoop()
break
start_game()
While I was writing this question, I realized what I was doing wrong, so I decided to go ahead and answer this myself.
When you define a variable as global, you don't want to assign the variable a variable then and there like so:
global lives = 0
That will give you an error. Why? When you want to define a variable as global, you are telling the computer, "Hey, this variable right here is used globally, not locally." The issue with the above line of code is that you are also assigning the variable a value when all you should be doing at that point is telling the computer that the variable is global. If you want to assign a value to the variable (whether it's for the first time or a reassignment) then you need to assign the value on a different line of code.
When I looked this up I didn't find anything explicitly saying this, so I hope this helps out anyone new to coding with python or someone who forgot how it worked like I did.
First of all, the global statement is a declaration, not an executable statement. It simply tells the interpreter to look in the module namespace rather than the function-call namespace. It need only be used inside a function.
Outside, the local and the global namespaces are the same thing (the module namespace), so the global statement does nothing.
The statement must be the keyword global followed by a comma-separated list
of names to be treated as global. If you want to assign a value to any name, global or not, you must do so in a separate assignment statement.
You perhaps want something more like the code below, which will "work" (I realise this is only a partial program in development) as you want it. I fixed the indentation to conform to PEP 8, as my old eyes found it too hard to read the code otherwise!
import random
words = "tom dick harry".split()
word = random.choice(words)
# Difficulties: Easy:12 Medium:9 Hard:6
lives = 0
current = "_" * len(word)
def gameLoop():
global lives
while current != word and lives > 0:
print("Guess a letter. If you wish to exit the game, enter 'exit'")
input("")
print(lives)
def start_game():
global lives
while True:
print(
"Welcome to Hangman! What game mode would you like to play? Easy, medium, or hard?"
)
game_mode = str.lower(input(""))
if game_mode == "easy":
lives = 12
gameLoop()
break
elif game_mode == "medium":
lives = 9
gameLoop()
break
elif game_mode == "hard":
lives = 6
gameLoop()
break
start_game()

Simpler If Statements

I have very little coding experience with Python, and am making a game for a Python coding class. I don't know any complicated stuff except this.
Is there a way to simplify the if statements from the code provided below to possibly one single if statement to reduce repetition? I have many more of these that will have to do many more rather than 4 numbers. Thanks.
import random
hero = random.randint(1,4)
if hero == 1:
print 'Marth'
elif hero == 2:
print 'Lucina'
elif hero == 3:
print 'Robin'
else:
print 'Tiki'
Use random.choice
import random
hero = ['Marth', 'Lucina', 'Robina', 'Tiki']
print(random.choice(hero))
import random
hero_list = ['Marth', 'Lucina', 'Robin', 'Tiki']
print hero_list[random.randint(0, len(hero_list)-1)]
import random
def GetHeroName(x):
return {
1 : 'Marth',
2 : 'Lucina',
3 : 'Robin'
}.get(x, 'Tiki')
hero = random.randint(1,4)
print GetHeroName(hero)
Note: the get(x, 'Tiki') statement is saying get x, but if that fails default to 'Tiki'.

Python2.7/Confused with variables

initial_p = input("Enter the initial point")
def game():
x = 1
guess = input("Guess value")
if guess == 1:
initial_p += 2
else:
initial_p -= 2
game()
replay = raw_input("Do you want to try it again? Y/N")
if replay == 'Y':
game()
each game needs 2 points
I made it really simple just to explain this stuff easily
So to play each game, it requires you to have at least 2 points otherwise it becomes game over
if you guess right, you earn 2 points
if not, you lose 2 points.
with the outcome(points), you can either play again or quit
if you play again, you pay two points
HOWEVER, when you play for the second time or more, that line
initial_p += 2 and initial_p -= 2 still have points that you typed in the very beginning
The quick and dirty response is to change to the following.
def game(initial_p):
#Your Code
return initial_p
initial_p = game(initial_p)
Basically, you're placing the global variable as a local variable and reassigning the global.
This should also happen at the very bottom as well.
Also, you can just ask for the input inside of the function, and have a default argument of initial_p.
For example,
def game(first_time=True)
#Ask for input with if first_time:
return initial_p
And modify some global point value or something from the return.
Sorry if this is sloppy, was written on my mobile.

Categories

Resources