How To +1 A Previous Assignment (Python 3.3) - python

NOTE:
This is not a duplicate of
Python integer incrementing with ++
I triedw_sword += 1 and it still showed up as 0.
Okay so this is my code as of now.
#creates random monsters with xp points, leveling up player, and adding upgrades
#imports
from clint.textui import colored, puts
import random
def game():
sticks = 2
stumps = 2
stone = 0
iron = 0
gold = 0
diamond = 0
platinum = 0
w_sword = 0
w_shield = 0
items = ('sticks:' + str(sticks) + ' stumps:' + str(stumps) + ' stone:' + str(stone) + ' iron:' + str(iron) + ' gold:' + str(gold) + ' diamond:' + str(diamond) + ' platinum:' + str(platinum) + ' Wooden sword(s):' + str(w_sword) +
' wooden shield(s):' + str(w_shield))
#start of the game
def start_game():
print(' Hello player! Welome to a text based game involving killing monsters, leveling up, crafting weapons, and upgrading weapons!!!')
print(' To get started enter in (i)inventory (c)craft items (d)description of items (m)types of monsters or (f)fight monsters.')
print(' ENTER (help) FOR HOW THE GAME WORKS')
print(' ENTER(?) FOR TO PRINT THIS AGAIN')
print(' WHILE YOU ARE IN A CATEGORY SUCH AS (i)inventory PRESS (?) CAN BE USED TO GO BACK AND GO TO ANOTHER CATEGORY')
start_game()
main_In = input()
level = 0
Pxp = 0
gold = 0
if main_In == ('c'):
ws_sticks = 2
ws_stumps = 1
def craft():
print('Would you like to craft an item??')
print('( Red = uncraftable )')
print('( Green = craftable )')
print('( Type items in lowercase )')
if sticks < ws_sticks:
puts(colored.red('Wooden sword'))
else:
puts(colored.green('Wooden sword'))
if stumps < ws_stumps:
puts(colored.red('Wooden shield'))
else:
puts(colored.green('Wooden shield'))
craft()
C_item = input()
def re_craft():
print('press ENTER to go back to the start screen, or enter c to craft an(other) item.')
cor_go = input()
if cor_go == ('c'):
craft()
C_item = input()
else:
game()
if C_item == ('no'):
print('press ENTER to go back to the start screen')
input()
game()
if C_item == ('wooden sword') and sticks >= ws_sticks:
print('Wooden sword added to your inventory')
re_craft()
if C_item == ('wooden sword') and sticks < ws_sticks:
print('You need ' + str(ws_sticks - sticks) + ' stick(s) to craft a wooden sword')
re_craft()
if C_item == ('wooden shield') and stumps >= ws_stumps:
print('Wooden shield added to your inventory')
re_craft()
if C_item == ('wooden shield') and stumps < ws_stumps:
print('You need' + str(ws_stump - stumps) + ' stumps to craft a wooden shield.')
re_craft()
while ('Wooden shield added to your inventory'):
w_shield = +1
while ('Wooden sword added to your inventory'):
w_sword = +1
if main_In == ('i'):
puts(colored.yellow('Level: ' + str(level)))
puts(colored.yellow('xp: ' + str(Pxp)))
puts(colored.yellow('gold:' + str(gold)))
puts(colored.yellow('Items: ' + str(items)))
puts(colored.yellow('press ENTER to return to the start screen'))
input()
game()
if main_In == ('?'):
game()
game()
Now as you can see, w_sword and w_shield are both = to 0 correct?
Right around where it says w_sword = +1 and w_shield = +1 is where I think the problem is.
When you run the program, enter c, and then craft a wooden sword/shield, it should automatically add 1 to w_sword/w_shield once you go to your (i)inventory. But for some reason when you go back to your (i)inventory, w_sword/w_shield (depending on which one you crafted) comes up as 0.
I thought this code would work mostly because in the items assignment, it contains str(w_sword) and str(w_shield) and the others. So when you craft and item like a wooden sword or wooden shield then it str(w_shield) or str(w_sword) should come up as 1.
Does anyone know what my problem is??
I use python 3.3 as said in the title.

The syntax is w_sword += 1 , not w_sword =+ 1.

Related

Error with a player turn ending loop in the Zombie Dice game

I'm trying to develop a code for the zombie dice game.
My problem is when the first player replies that he doesn't want to continue playing.
The game ends and I can't get the second player to play. Can someone help me?
import random
print("========== ZOMBIE DICE (PROTÓTIPO SEMANA 4) ==========")
print("========= WELCOME TO THE ZOMBIE DICE GAME! ========")
numeroJogadores = 0
while numeroJogadores < 2:
numeroJogadores = int(input("Enter the number of players: "))
print(numeroJogadores)
if numeroJogadores < 2:
print("NOTICE: You must have at least 2 players to continue!")
listaJogadores = []
for i in range(numeroJogadores):
nome = str(input("\nEnter player name: " + str(i+1) + ": "))
listaJogadores.append(nome)
print(listaJogadores)
dadoVerde = ("brain", "steps", "brain", "shot", "steps", "brain")
dadoAmarelo = ("shot", "steps", "brain", "shot", "steps", "brain")
dadoVermelho = ("shot", "steps", "shot", "brain", "steps", "shot")
listaDados = [dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde,
dadoAmarelo, dadoAmarelo, dadoAmarelo, dadoAmarelo,
dadoVerde, dadoVermelho, dadoVermelho]
print("\nSTARTING THE GAME...")
jogadorAtual = 0
dadosSorteados = []
tiros = 0
cerebros = 0
passos = 0
while True:
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
for i in range (3):
numeroSorteado = random.randint(0, 12)
dadoSorteado = listaDados[numeroSorteado]
if (dadoSorteado == dadoVerde):
corDado = "Green"
elif (dadoSorteado == dadoAmarelo):
corDado = "Yellow"
else:
corDado = "Red"
print("Dice Drawn: ", corDado)
dadosSorteados.append(dadoSorteado)
print("\nThe faces drawn were: ")
for dadoSorteado in dadosSorteados:
numeroFaceDado = random.randint(0,5)
if dadoSorteado[numeroFaceDado] == "brain":
print("- brain (you ate a brain)")
cerebros = cerebros + 1
elif dadoSorteado[numeroFaceDado] == "tiro":
print("- shot (you got shot)")
tiros = tiros + 1
else:
print("- steps (a victim escaped)")
passos = passos + 1
print("\nCURRENT SCORE: ")
print("brins: ", cerebros)
print("shots: ", tiros)
if cerebros >= 13:
print("Congratulations, you've won the game!")
break
elif tiros >= 3:
print("You lost the game!")
break
else:
continuarTurno = str(input("\nNOTICE: Do you want to continue playing dice? (y=yes / n=no)")).lower()
if continuarTurno == "n":
jogadorAtual = jogadorAtual + 1
dadossorteados = 0
tiros = 0
cerebros = 0
passos = 0
if jogadorAtual > numeroJogadores:
print("Finalizing the game prototype")
else:
print("Starting another round of the current turn")
dadossorteados = []
print("======================================================")
print("===================== END OF THE GAME ====================")
print("======================================================")
Does anyone know what I'm doing wrong?
I'm new as a programmer. If anyone knows how to help me with this problem, I would be grateful.
EDIT: Well now the code just works. I can switch players just fine, but if you go through all the characters it crashes again since jogadorAtual gets too big for listaJogadores. I don't quite understand the game, but assuming you want to start back with the first player, an elegant way you can accomplish that is by doing modulus with the % operator, which divides two numbers but returns the remainder. If you divide the number of players by the size of listaJogadores, you'll always get a number inside listaJogadores's range.
# Change this...
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
# ...to this
print("PLAYER TURN: ", listaJogadores[jogadorAtual % len(listaJogadores)])
If that's not what you need for your game, let me know.
Original answer: Is the game ending or is it crashing? When I run the game, it always crashes with:
File "C:\Users\me\Desktop\Untitled-1.py", line 56, in <module>
diceDrawns.append(diceDrawn)
AttributeError: 'int' object has no attribute 'append'
This is because after looping, you try to do diceDrawns.append(), but you've already replaced the diceDrawns list with an integer on line 87. I'm not sure if you meant to replace diceDrawn instead, but that's definitely the source of the problem.
An unrelated note: You can do += as a shorthand way to increment a variable by a certain amount, so you can replace a lot of instances of things like currentPlayer = currentPlayer + 1 with currentPlayer += 1, and the same can be done with any operator, so you could also do things like -= or *=

Modifying a list outside a 'While' loop after running it through the 'While' loop

I'm currently trying to create my own game of TicTacToe from the ground up and I'm currently having difficulty with a 'while' loop corresponding to a list that I have created.
I'm using the following list:
board = [1,2,3,4,5,6,7,8,9]
to mark all 9 slots on a 3x3 game of TicTacToe.
However when player one makes a move(in slot '1' for example) the list should be changed to show
board = [X,2,3,4,5,6,7,8,9]
This should continue on until all 9 indexes(I believe is the appropriate term) within the list should be taken up by either 'X' or 'O' which will equal a tie in the game!
For now I'm just experimenting as I go along so pardon the rest of the code but the full code I'm using is:
board = [1,2,3,4,5,6,7,8,9]
def CreateBoard(board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
PlayerOne = 'X'
Turn = 'player one'
GameRunning = True
while [0] == 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 in board == True:
if Turn == 'player one':
letter = 'X'
Move = input("Please pick where to go next: ")
Move = int(Move)
if Move in board:
board.insert(Move, letter)
board.remove(Move)
print(board)
Turn = 'player two'
else:
print("This move is invalid")
if Turn == 'player two':
letter = 'O'
Move = input("Pick where to go next: ")
Move = int(Move)
if Move in board:
board.insert(Move, letter)
board.remove(Move)
print(board)
Turn = 'player one'
else:
print("This move is invalid")
The output I get as I go along are:
I'm guessing the while loop is running the list that's outside of the loop but I'm trying to find a way to change that!
I've also not yet worked out why its printing 'That move is invalid'!
The issue with your while loop is that non-zero integers are always considered to be "true". Therefore
while [0] == 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 in board == True:
actually means "while the list containing 0 is equal to the integer 1 (always false), or 2 (true), or 3 (true)... or 9 in (board) (true if 9 is still on the board), then enter the block."
I believe that you meant was more:
while any((cell in range(1,10) for cell in board)):
which means while any cell in the board is in the range from 1 (inclusive) to 10 (exclusive), then enter the block.
Take a look at this code:
player = [
{"name": "Player One", "letter": "X"},
{"name": "Player Two", "letter": "O"},
]
def print_board(board):
def print_vbars():
print(" | |")
def print_hbars():
print("-----------")
print_vbars()
for row in range(3):
print(" {} | {} | {}".format(*(board[row*3 : row*3+3])))
print_vbars()
print_hbars()
print_vbars()
print_vbars()
def final_state(board):
winning_combinations = (
(0,1,2), # Horizontal top row
(3,4,5), # Horizontal middle row
(6,7,8), # Horizontal bottom row
(0,3,6), # Vertical left row
(1,4,2), # Vertical middle row
(2,5,7), # Vertical right row
(0,4,8), # Downward diagonal
(2,4,6), # Upward diagonal
)
for letter in ("X", "O"):
for combination in winning_combinations:
row_state = (board[index] for index in combination)
if all(map(lambda cell: letter == cell, row_state)):
return "{} wins".format(letter)
if all(map(lambda cell: cell in ("X", "O"), board)):
return "Game is a draw."
return False
def play_game():
board = list(range(9))
starting_player = 0
turn = 0
active_player = starting_player
while final_state(board) is False:
turn += 1
print("Turn {}:".format(turn))
print_board(board)
name, letter = player[active_player]["name"], player[active_player]["letter"]
move = None
while move is None:
try:
move = input("{} please make your move: ".format(name))
move = int(move)
if move in board:
board[move] = letter
print("{} played {} on {}.".format(name, letter, move))
active_player = 1 - active_player
else:
print("Move {} is invalid.".format(move))
move = None
except Exception as e:
print("Move {} is invalid.".format(move))
move = None
print_board(board)
print(final_state(board))
if __name__ == "__main__":
play_game()

Python 2.7.3 Code Loops Without a While Loop

I am relatively new to programming, so don't be surprised if there are some minor hiccups in the code, but the problem that is happening is that this code seems to loop itself, the whole thing and I don't understand why. I looked at the actual code that runs this function but it seemed fine. So I cannot find any error in this code that makes it loop itself. (If the problem isn't in this code then the looping code it beneath it)
def thebeast(yourhp):
foe = "Thisisirrelevant"
enemy = int(random.randint(1,4))
if enemy == 1:
foe = "skeleton"
elif enemy == 2:
foe = "man with crazy eyes"
else:
foe = "dog, a big and scary dog"
monsteract = 1
dmg = 0
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print " C O M B A T"
time.sleep(0.1)
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print "You encounter a " + foe
time.sleep(0.5)
while monsteract == 1:
comb = str(input("What do you do to the " + foe + "?" + " Do you feel like jabbing it or stabbing it?"))
if comb in ["s", "S", "Stab", "STAB", "stab"]:
if spear == 1:
dmg = int(random.randint(1,4))
elif sword == 1:
dmg = int(random.randint(1,3))
else:
dmg = int(random.randint(1,5))
elif comb in ["j", "J", "Jab", "JAB", "jab"]:
if spear == 1:
dmg = int(random.randint(1,3))
elif sword == 1:
dmg = int(random.randint(1,4))
else:
dmg = int(random.randint(1,5))
if dmg == 1:
print "You slay the " + foe + " with graceful ease"
time.sleep(0.5)
monsteract = 0
else:
enemydmg = int(random.randint(1,3))
print "The " + foe + " strikes you for " + str(enemydmg) + " damage"
time.sleep(0.3)
print "That didn't work out as planned, but you pull yourself together and prepare to strike the " + foe
time.sleep(0.3)
yourhp = yourhp - enemydmg
if yourhp < 0:
yourhp = 0
print "You have " + str(yourhp) + " health left"
time.sleep(0.3)
if yourhp < 1:
print "The " + foe + " has slain you, well done, you're dead, on the bright side the innocent "
print foe + " is still alive! Every life counts, even that of a " + foe + "."
monsteract = 0
return thebeast(yourhp)
Looping code:
def randomevents(yourhp):
turn = 10
while turn > 0:
time.sleep(0.1)
happening = int(random.randint(1,6))
time.sleep(0.1)
if yourhp < 1:
turn = 0
print "You managed to escape the dungeon, by dying that is"
elif happening == 1:
turn = turn - 1
thebeast(yourhp)
elif happening == 2:
item(sword, spear)
turn = turn - 1
elif happening in [3, 4, 5]:
friend()
turn = turn - 1
print "Well done! You escaped the dungeon! (Either by running out of it, or by having your soul sent to another world)"
useless = str(input("Are you satsified with yourself?: "))
Thank you!
Look at your return statement at the end of thebeast. At the end of the function, you call the function again! Since this happens every time you call it, you will never stop calling it (until you hit the maximum recursion depth). Considering that you don't capture the return value of thebeast in randomevents, you should consider it not returning anything.

Python making GUI windows

I wrote a program that makes 3 things which user may choose:
def createLeague(): #creates a list with all teams
file = open('league1.txt', 'r')
teams = []
for line in file:
team = line.split()
teams.append(team)
file.close()
return teams
def getTeam(teams): #this function gets a team that user inputs
result = ' '
choice = input('Enter the team: ')
checkforteam = False
for line in teams:
team = line[0]
if choice == team: #check for input team in all lines
result = team
games = line[1]
wins = line[2] #assign all statistics to the variables with
draws = line[3] #appropriate names
loses = line[4]
checkforteam = True
if checkforteam: #if it is True, it will return the team. If False, returns an error message
print(result, games, wins, draws, loses)
else:
print('No such a team')
def getWinner(teams): #returns a leader
winner = ' '
result = 0
loses = 100
for team in teams:
points = int(team[2])*3 + int(team[3])
lose = int(team[4])#counting all points
if points > result: #find a team with maximum points
result = points
winner = team[0]
loses = lose
elif points == result:
if lose < loses:
winner = team[0]
print('Winner: ', winner)
print('Points: ', result)
def updateScore(teams): #update the table
firsteam = input('Home: ')
secondteam = input('Away: ')
goal1 = int(input('Goals scored by home: '))
goal2 = int(input('Goals scored by away: '))
f = open('nhl.txt', 'w')
for team in teams:
komanda = team[0]
matches = int(team[1])
wins = int(team[2])
draws = int(team[3])
loses = int(team[4])
if firsteam == komanda:
if goal1 > goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
elif secondteam == komanda:
if goal1 < goal2:
matches += 1
wins += 1
elif goal1 == goal2:
matches += 1
draws += 1
else:
matches += 1
loses += 1
newline = komanda+ ' '+ str(matches) + ' ' +str(wins)+ ' '+ str(draws) + ' '+ str(loses)+ '\n'
f.write(newline)
f.close()
print('Saved')
teams = createLeague()
loop = 1 #variable that makes 'while' working until user wants to close the program
while loop == 1:
print('0. Exit')
print('1. Find a team')
print('2. Get a leader')
print('3. Update the results')
x = input('Choose: ')
if x == '1':
getTeam(teams)
elif x == '2':
getWinner(teams)
elif x == '3':
updateScore(teams)
elif x == '0':
print('Goodbye!')
loop = 0
else:
print('Wrong!')
Now I want that when I choose 1, 2 or 3 in IDLE, there will be a GUI window appeared where the function that called in while loop will work. I am stucked about it. How I can do it? Please, just show an example for one of the function.

Why is Int() conversion not working? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Post can be closed. Turns out I messed up something unknown, because now I retried and the int() function is working as I wanted.
`
`
This is a small piece of code that I wrote:
def damagecalculating(self):
self.damage = random.randrange(1,100) * self.weapondamage / 5
self.damage = int(self.damage)
(used long words here to make clear what I am doing)
So what I'm doing is calculating the damage a player does in an attack. but I want an integer and not a float so had to add the extra line.
This returns a float for some reason:
self.damage = int((random.randrange(1,100) * self.weapondamage) / 5)
I don't understand that, because what I see is that random.randrange(1,100) is calculated, then self.wepdamage is found and thus the formula becomes, for example: 55 * 10 / 5.
Why would this return a float in the first place (I found it has something to do with the /)? And why does int() not work? because int(55*10/5) does return an integer.
I did already find http://www.stackoverflow.com/questions/17202363/int-conversion-not-working but this does not answer my question as to why or if this can be done in one line.
Edit:
I don't really see why this would be needed but this is the full code as some requested. Please note that I'm very new to programming and there is probably a bunch of stuff that can be done better. Also it's far from done.
import random
class playerstats:
def usepotion(self):
heal = random.randrange(100,500)
self.health = self.health + heal
self.pots -= 1
print('The potion healed', str(heal) +'!')
print(self.name, 'now has', str(self.health), 'health.')
def minushealth(self, amount):
self.health = self.health - amount
def damagecalc(self): ### HERE IS THE PROBLEM ###
self.damage = random.randrange(1,100) * self.wepdamage / 5
self.damage = int(self.damage)
name = ''
health = 0
weapon = ''
wepdamage = 5
damage = 0
pots = 0
def printdata():
print(player.name, 'health =', player.health)
print(player.name, 'potions =', player.pots)
print()
print(opp.name, 'health =', opp.health)
print(opp.name, 'potions =', opp.pots)
print()
def setgamedata():
player.name = input('Set player name: ')
player.health = int(input('Set player health (1000): '))
player.weapon = input('Set player weapon name: ')
player.wepdamage = int(input('Set player damage multiplier (5 = normal): '))
player.pots = int(input('Set number of potions for player: '))
print()
opp.name = input('Set opponent name: ')
opp.health = int(input('Set opponent health (1000): '))
opp.weapon = input('Set opponent weapon name: ')
opp.wepdamage = int(input('Set opponent damage multiplier (5 = normal): '))
opp.pots = int(input('Set number of potions for opponent: '))
print()
def resetgamedata():
player.name = input('Player name currently is: ' + player.name + '. Set player name: ')
player.health = int(input('Player health currently is: ' + str(player.health) + '. Set player health (1000): '))
player.weapon = input('Player weapon currently is', player.weapon, 'Set player weapon name: ')
player.wepdamage = int(input('Player damage multiplier currently is: ' + str(player.wepdamage) + '. Set player damage multiplier: '))
player.pots = int(input('Player currently has ' + str(player.pots) + ' potions. Set player potions: '))
print()
opp.name = input('Opponent name currently is: ' + opp.name + '. Set opponent name: ')
opp.health = int(input('Opponent health currently is: ' + str(opp.health) + '. Set opponent health (1000): '))
opp.weapon = input('Opponent weapon currently is', opp.weapon, 'Set opponent weapon name: ')
opp.wepdamage = int(input('Opponent damage multiplier currently is: ' + str(opp.wepdamage) + '. Set opponent damage multiplier: '))
opp.pots = int(input('Opponent currently has ' + str(opp.pots) + ' potions. Set opponent potions: '))
print()
def menuoptions():
print('1. Start new game')
print('9. Quit')
print()
def battleoptions():
print('1. Attack')
print('2. Use potion')
print('3. Change stats')
print('9. Abandon game')
print()
### ACTUAL GAME CODE STARTS HERE ###
# Set objects
player = playerstats()
opp = playerstats()
print('- - - - - - - - - - - - - - - -\n')
print('Welcome to the game!\n\n')
print('Entering main menu\n')
while True:
menuoptions()
choice=int(input('Enter number: '))
print()
while True:
if choice == 1:
setgamedata()
print('Starting game now!')
while player.health > 1 and opp.health > 1:
battleoptions()
choice = int(input('Enter number: '))
print()
# Execute player move
if choice == 1:
printdata()
elif choice == 2:
player.usepotion()
elif choice == 3:
resetgamedata()
elif choice == 9:
print('Quit game')
input('Press enter to return to main screen')
break
else:
print('No valid choice made')
# Execute opponent move
if opp.health < 200:
oppmove = 1
else:
oppmove = 0
if oppmove == 1:
opp.usepotion()
else:
print('nothing here')
##### ATTACK PLAYER
### SOMETHING HERE WHEN PERSON REACHED < 0 HEALTH
if choice == 9:
print('\nQuit?! Okay fine\n')
print('Your stuff was not saved, good luck with that.\n')
input('Press enter to close screen')
import sys
sys.exit()
input('')
The issue you are experiencing is that in Python 3.x the division operator / performs true division - that is, the returned value is float. If you want the behaviour of Python 2.x, that is integer division use the // operator. Note, that the // division result will be int if the dividend and divisor are integers.
>>> 5 / 10
0.5
>>> 5 // 10
0
>>> type(5 // 10)
<class 'int'>
For floats, the // operator still returns a float:
>>> 5.0 // 10
0.0
>>> 5 // 10.0
0.0

Categories

Resources