Is the code generating a new card every time choosemove() and then creating a new card again and adding on top if you hit again like its supposed to?
Basically, I need lose() to run when newtotalplayercardvalue > 21 so it shows the player lost, but it just lets you "hit" endlessly for some reason. Thanks in advance!
import random
def win():
print ("")
print("You won!")
menu()
def lose():
print ("")
print("You lost!")
menu()
def numbertocard(card):
if card == 11:
card = "J"
elif card == 12:
card = "Q"
elif card == 13:
card = "K"
elif card == 14:
card = "A"
else:
card = card
return card
def cardtonumber(cardvalue):
if cardvalue == "J":
cardvalue == 10
elif cardvalue == "Q":
cardvalue == 10
elif cardvalue == "K":
cardvalue = 10
elif cardvalue == "A":
cardvalue = 11
else: cardvalue = cardvalue
return (cardvalue)
def hit():
print("")
global totalplayercardvalue
newcard = random.randint(1,14)
new_card_name = numbertocard(newcard)
print(f"You got a {new_card_name}")
newtotalplayercardvalue = newcard + totalplayercardvalue
if newtotalplayercardvalue > 21:
lose()
else:
choosemove()
def stand():
global totalplayercardvalue
global totaldealercardvalue
global dealercard2
print(f"The dealer's second card is a {dealercard2}")
if totalplayercardvalue > totaldealercardvalue:
win()
elif totaldealercardvalue > totalplayercardvalue:
lose()
def choosemove():
print("")
choice = input("Would you like to hit or stand? \n")
if choice == "hit":
hit()
elif choice == "stand":
stand()
else:
print("""Please only enter "hit" or "stand" """)
choosemove()
def startgame():
global totalplayercardvalue
global totaldealercardvalue
playercard1 = random.randint(1,14)
p_card1_name = numbertocard(playercard1)
print(f"Your first card is {p_card1_name}")
print("")
playercard2 = random.randint(1,14)
p_card2_name = numbertocard(playercard2)
print(f"Your second card is {p_card2_name}")
print("")
dealercard1 = random.randint(1,14)
d_card1_name = numbertocard(dealercard1)
dealercard2 = random.randint(1,14)
totalplayercardvalue = playercard2 + playercard2
totaldealercardvalue = dealercard1 + dealercard2
if totalplayercardvalue == 21 and totaldealercardvalue == 21:
tie()
elif totalplayercardvalue == 21:
win()
elif totaldealercardvalue == 21:
lose()
else:
print(f"The dealer's first card is a {d_card1_name}")
choosemove()
def menu():
play_game = input("Would you like to start a round? y/n: \n")
if play_game == "y":
startgame()
else:
print("""Say "y" """ )
menu()
menu()
First things first, your program isnt well formatted, there is no seperation between the way that global variables and local variables are defined. It's standard practice to define global variables in Uppercase. Will make life easier for you.
As to what the endless hitting is, you aren't updating the totalplayercard variable in hit. You just define newtotalplayercardvalue, check if that is greater than 21 else choosing move, it doesn't update the global variable instead try
def hit():
print("")
global totalplayercardvalue
newcard = random.randint(1,14)
new_card_name = numbertocard(newcard)
print(f"You got a {new_card_name}")
totalplayercardvalue += newcard
if totalplayercardvalue > 21:
lose()
else:
choosemove()
IDK how black jack works however this is the reason that I can see
This is a game of war.
I tried to add the code which it should ask the user if they want to play again.
It starts the game again but never resets the player's cards and so they have more than 26 cards each time it plays again.
I cant understand what should i add to reset the cards each time the player wants to play again
more than 26 cards
import random
values = {"Two":2, "Three":3, "Four":4, "Five":5, "Six":6,
"Seven":7, "Eight":8, "Nine":9, "Ten":10, "Jack":11,
"Queen":12, "King":13, "Ace":14}
suits = ("Hearts", "Diamonds", "Clubs", "Spades")
ranks = ("Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack",
"Queen", "King", "Ace")
class Card:
def __init__(self,suit,rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
def __str__(self):
return self.rank + " of " + self.suit
class Deck:
def __init__(self):
self.all_cards = []
for suit in suits:
for rank in ranks:
created_card = Card(suit,rank)
self.all_cards.append(created_card)
def shuffle(self):
random.shuffle(self.all_cards)
def deal_one(self):
return self.all_cards.pop()
class Player:
def __init__(self, name):
self.name = name
self.all_cards = []
def remove_one(self):
return self.all_cards.pop(0)
def add_cards(self, new_cards):
if type(new_cards) == type([]):
self.all_cards.extend(new_cards)
else:
self.all_cards.append(new_cards)
def __str__(self):
return f"{self.name}"
#*****SCRIPT*****#
player_one = Player(input("Player One: Enter Name "))
player_two = Player(input("Player Two: Enter Name "))
play_again = True
while play_again:
game_on = True
round_num = 0
new_deck = Deck()
new_deck.shuffle()
for x in range(26):
player_one.add_cards(new_deck.deal_one())
player_two.add_cards(new_deck.deal_one())
print(f"player one cards: {len(player_one.all_cards)}")
print(f"player two cards: {len(player_two.all_cards)}")
while game_on:
round_num += 1
print(f"Round Number: {round_num}")
if len(player_one.all_cards) == 0:
print(f"{player_one} is out of cards! \n{player_two} won the game!! \nGAME OVER")
game_on = False
a = input("Do you want to play agian? ")
if a == "Y":
play_again = True
else:
play_again = False
break
if len(player_two.all_cards) == 0:
print(f"{player_two} is out of cards! \n{player_one} won the game!! \nGAME OVER")
game_on = False
a = input("Do you want to play agian? ")
if a == "Y":
play_again = True
else:
play_again = False
break
player_one_cards = []
player_one_cards.append(player_one.remove_one())
player_two_cards = []
player_two_cards.append(player_two.remove_one())
at_war = True
while at_war:
if player_one_cards[-1].value > player_two_cards[-1].value:
player_one.add_cards(player_one_cards)
player_one.add_cards(player_two_cards)
at_war = False
elif player_one_cards[-1].value < player_two_cards[-1].value:
player_two.add_cards(player_two_cards)
player_two.add_cards(player_one_cards)
at_war = False
else:
print("****WAR HAS BEGUN****")
if len(player_one.all_cards) < 5:
print(f"{player_one} is unable to play war! \n{player_two} won! \nGAME OVER")
game_on = False
a = input("Do you want to play agian? ")
if a == "Y":
play_again = True
else:
play_again = False
break
elif len(player_two.all_cards) < 5:
print(f"{player_two} is unable to play war! \n{player_one} won! \nGAME OVER")
game_on = False
a = input("Do you want to play agian? ")
if a == "Y":
play_again = True
else:
play_again = False
break
else:
for num in range(5):
player_one_cards.append(player_one.remove_one())
player_two_cards.append(player_two.remove_one())
I believe that your problem is that you have state stored in each Player object that you aren't resetting before the next game. I ran your code, reproduced the problem, and then fixed it as follows:
I added this method to your Player class:
def reset(self):
self.all_cards = []
I added calls to this method at the beginning of each new game:
while play_again:
player_one.reset()
player_two.reset()
After doing this, your code seemed to be much better behaved. I'm not sure if it was doing everything right on subsequent games, but the card counts didn't grow beyond 52 cards like they did with the original version.
I am developing a rock paper scissors on python and I am stuck.
I made a class that cycles between (rock, paper, and scissors ), I want the computer to know it's previous play.
for instance ( first round computer played rock, in the next round it should play paper)
but I don't know how to call the learn function to make it work
class Player:
def __init__(self):
self.score = 0
def move(self):
return 'rock'
def learn(self, my_move, their_move):
self.my_move = my_move
self.their_move = their_move
def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def play_round(self):
move1 = input("Pick something!\n")
move2 = self.p2.move()
print(f"Player 1: {move1} Player 2: {move2}")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
if beats(move1, move2):
self.p1.score += 1
print ("You win")
print ("Human score = " + str(self.p1.score) + " " + "Computer score = " + str(self.p2.score) )
elif beats(move2,move1):
self.p2.score += 1
print ("Computer wins")
print ("Human score = " + str(self.p1.score) + " " + "Computer score = " + str(self.p2.score) )
else:
print ("Draw")
print ("Human score = " + str(self.p1.score) + " " + "Computer score = " + str(self.p2.score) )
def play_game(self):
print("Game start!")
for round in range(3):
print(f"Round {round}:")
self.play_round()
print("Game over!")
class human_player(Player):
def move(self):
return input("Pick something!\n")
class randomplayer(Player):
def move(self):
return random.choice(moves)
class repeat(Player):
def move(self):
return 'rock'
class cycleplayer(Player):
def move(self):
# calling my_move from the Player class
if self.learn.my_move == "rock" or "paper" or "scissors" :
return 'rock'
elif self.their_move == 'rock':
return "paper"
elif self.their_move == 'paper':
return "scissors"
elif self.their_move == 'scissors':
return "rock"
if HumanPlayer_choice == "cycle" :
game = Game(Player(), cycleplayer())
game.play_game()
This is the error I am getting.
Exception has occurred: AttributeError 'function' object has no
attribute 'my_move'
I know that I need to utilize the init function with the learn function to make it work but I not sure how.
The problem is on this line:
if self.learn.my_move == "rock" or "paper" or "scissors" :
learn function does not have an attribute named my_move. What you meant to do is probably
if self.my_move == "rock" or self.my_move == "paper" or self.my_move == "scissors" :
Note that you have to add self.my_move == before "paper" and "scissors"; otherwise it is evaluated like:
if (self.my_move == "rock") or ("paper") or ("scissors"):
and since non-empty strings are always evaluated as True, this if case is rendered useless.
As #DmitryErohin mentioned, there is a better way of achieving that without repeating yourself:
if (self.my_move in ("rock", "paper", "scissors")):
This is much less verbose and a lot more readable
There were a few problems in your code as far as I could follow. Take a look at the example below based on your code. There's some logic I could not follow so it may not behave exactly as you want. Suggestions:
as you just want to store the previous move for the cycle_player move, store it in the cycle object (instance) not on the Player
as the move method varies make it's implementation specific to a child class (e.g. human_player, random_player, cycle_player)
some methods are better as static rather than recreated in each instance methods
import random
class Player:
def __init__(self):
self.score = 0
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
#staticmethod
def check_result(a, b): #Return win, draw, loose for a over b
if (a == b):
return 'draw'
if (a == 'rock' and b == 'scissors') or (a == 'scissors' and b == 'paper') or (a == 'paper' and b == 'rock'):
return 'win'
return 'loose'
def play_round(self):
#move1 = input("Pick something!\n")
move1 = self.p1.move()
move2 = self.p2.move()
print(f"Player 1: {move1} Player 2: {move2}")
result = Game.check_result(move1, move2) # a over b
if result == 'win':
self.p1.score += 1
print ("You win")
elif result == 'loose':
self.p2.score += 1
print ("Computer wins")
else:
print ("Draw")
print ("Human score = " + str(self.p1.score) + " " + "Computer score = " + str(self.p2.score))
def play_game(self):
print("Game start!")
for round in range(3):
print(f"Round {round + 1}:")
self.play_round()
print("Game over!")
class human_player(Player):
def move(self):
return input("Pick something!\n") #TODO validate input
class random_player(Player): #Option in game for computer to make random moves
def move(self):
return random.choice(["scissors","paper","rock"])
class repeat_player(Player): #Option
def move(self):
return 'rock'
class cycle_player(Player):
def __init__(self):
self.previous_move = None
super().__init__()
def move(self):
# calling my_move from the Player class
if self.previous_move is None :
next_move = 'rock'
elif self.previous_move == 'rock':
next_move = "paper"
elif self.previous_move == 'paper':
next_move = "scissors"
elif self.previous_move == 'scissors':
next_move = "rock"
self.previous_move = next_move
return next_move
#game = Game(human_player(), random_player())
#game = Game(human_player(), repeat_player())
game = Game(human_player(), cycle_player())
game.play_game()
I'm trying to get this RPG program to work, but I can't figure it out. I run it and well, you will see when you run the program. For some reason when I run this it stops at 1,2,3,4 after every move I make. Am I not returning anything? What am I doing wrong here, and how can I improve my organization and code in the future?
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == input('1'):
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == input('2'):
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == input('3'):
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == input('4'):
Loop = False
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
The problem is you are using input() in if statement. Whenever interpreter tries to check if condition is true or not it executes the input() which demands an input even when you didn't expect it. In one of the methods your input was in wrong order so I fixed that too. So correct code should be :-
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run \n')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
elif choice == '2':
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
elif choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
Loop = False
def enemy_battle(character, enemy):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
You didn't need two classes here clearly. But I suppose you might be thinking of adding some more features in future I guess. You can study more about oop and inheritance and figure out a smarter solution in general. I think you should focus on basics. Also try not to name the temporary variable same as that of class. It is a very hastly written code imo. But I fixed it's working.
Looks interesting, send me a copy after you finish will ya?
so basically you use too much input()
you have to enter a value for every input() function
you need to organize your code, maybe look at how others write their code
this is a quick fix, but it doesn't mean that this is the standard, you still have a lot to learn
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball','iceblock']
Loop = True
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = character(30, 30, 5, 0, 10) # enemy
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == '2':
print('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
spellchoice = input()
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
print("You cowardly run away")
exit()
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
else:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
I'm getting the above error in my code. It's just a simple text-based game.
Here's the code:
import os
import sys
import random
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.attack = 10
self.gold = 0
self.potions = 0
class Goblin:
def __init__(self, name):
self.name = name
self.maxhealth = 50
self.health = self.maxhealth
self.attack = 5
self.goldgain = 10
GoblinIG = Goblin("Goblin")
class Zombie:
def __init__(self, name):
self.name = name
self.maxhealth = 70
self.health = self.maxhealth
self.attack = 7
self.goldgain = 15
ZombieIG = Zombie("Zombie")
def main():
#os.system("cls")
print("Welcome to my game!")
print("1) Start")
print("2) Load")
print("3) Exit")
option = input("-> ")
if option == "1":
start()
elif option == "2":
pass
elif option == "3":
pass
else:
main()
def start():
#os.system("cls")
print("Hello, what is your name?")
option = input("-> ")
global PlayerIG
PlayerIG = Player(option)
start1()
def start1():
#os.system("cls")
print("Name: %s" % PlayerIG.name)
print("Attack: %s" % PlayerIG.attack)
print("Gold: %i" % PlayerIG.gold)
print("Potions: %i" % PlayerIG.potions)
print("Health: %i/%i" % (PlayerIG.health, PlayerIG.maxhealth))
print("1) Fight")
print("2) Store")
print("3) Save")
print("4) Exit")
option = input("-> ")
if option == "1":
prefight()
elif option == "2":
store()
elif option == "3":
pass
elif option == "4":
sys.exit()
else:
start1()
def prefight():
global enemy
enemynum = random.randint(1,2)
if enemynum == 1:
enemy = GoblinIG
else:
enemy = ZombieIG
fight()
def fight():
print("%s vs %s" % (PlayerIG.name, enemy.name))
print("%s's Health: %s/%s %s Health: %i/%i" % (PlayerIG.name, PlayerIG.health, PlayerIG.maxhealth, enemy.name, enemy.health, enemy.maxhealth))
print("Potions Left: %s\n" % PlayerIG.potions)
print("1) Attack")
#Implement defend system
print("2) Drink Potion")
print("3) Run")
option = input()
if option == "1":
attack()
elif option == "2":
drinkPotion()
elif option == "3":
run()
else:
fight()
def attack():
global PlayerAttack
global EnemyAttack
PlayerAttack = random.randint(PlayerIG.attack / 2, PlayerIG.attack)
EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
if PlayerAttack == PlayerIG.attack / 2:
print("You missed!")
else:
enemy.health -= PlayerAttack
print("You dealt %i damage!" % PlayerAttack)
option = input(" ")
if enemy.health <= 0:
win()
if EnemyAttack == enemy.attack/2:
print("The enemy missed!")
else:
PlayerIG.health -= EnemyAttack
print("The enemy dealt %i damage!" % EnemyAttack)
option = input("")
if PlayerIG.health <= 0:
dead()
else:
fight()
def drinkPotion():
if PlayerIG.potions == 0:
print("You don't have any potions!")
else:
PlayerIG.health += 50
if PlayerIG.health >= PlayerIG.maxhealth:
PlayerIG.health = PlayerIG.maxhealth
print("You drank a potion!")
option = input(" ")
fight()
def run():
runnum = random.randint(1,3)
if runnum == 3:
print("You have ran away!")
option = input(" ")
start1()
else:
print("You've failed to run away!")
option = input(" ")
EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
if EnemyAttack == enemy.attack/2:
print("The enemy missed!")
else:
PlayerIG.health -= EnemyAttack
print("The enemy dealt %i damage!" % EnemyAttack)
option = input(" ")
if PlayerIG.health <=0:
dead()
else:
fight()
def win():
enemy.health = enemy.maxhealth
PlayerIG.gold -= enemy.goldgain
print("You have defeated the %s!" % enemy.name)
print("You found %i gold!" % enemy.goldgain)
option = input(" ")
start1()
def dead():
print("You have died!")
option = input(" ")
def store():
pass
main()
I get the error in def run(), in the else: statement. The line that goes like: EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
Any ideas? Should I elaborate more on my issue? Thanks :)
Use EnemyAttack = random.randint(math.floor(enemy.attack / 2), enemy.attack), or use math.ceil() to round the result of enemy.attack / 2.
randrange() expects whole integers. The error is occurring because the result of enemy.attack / 2 isn't a whole number; it has decimal places whenever enemy.attack is odd. One option is to scale randrange() after it is calculated if you need decimal results.
For example: 0.5*randrange(2*(enemy.attack/2), 2*enemy.attack), which can be simplified into 0.5*randrange(enemy.attack, 2*enemy.attack)