I've been working on a program for the Microbit inspired by some basic blocks script I saw a few years back. The functionality of the AI controlled pixel and the player controlled pixel work as intended--which one annoying, and game breaking bug--the player ship resets to its spawn position whenever the AI ship completes its function.
I suspect this is because I have an assigned position for the ship in the beginning of the code, where it is then modified in the function itself. Removing this results in an error where a variable is not referenced--however, I cannot leave the problem alone. I welcome any guidance. The code is below.
from microbit import *
import random
enemyXpos = 4
playerXpos = 2
while True:
display.set_pixel(enemyXpos,0,4)
display.set_pixel(playerXpos,4,6)
def laser(laserXpos, laserYpos):
laserXpos = playerXpos
laserYpos = 3
for i in range (4):
display.set_pixel(laserXpos,laserYpos,9)
if laserYpos > 0:
display.set_pixel(laserXpos,laserYpos,0)
laserYpos -= 1
display.set_pixel(laserXpos,laserYpos,9)
if laserYpos == 0 and laserXpos == enemyXpos:
display.show(all_booms, delay=200)
score = score + 1
continue
elif laserYpos == 0:
display.set_pixel(bombXpos,bombYpos,0)
laserYpos = newlaserYpos
sleep (200)
def enemy_left(enemyXpos, playerXpos):
enemyXpos = 4
for i in range (4):
display.clear()
enemyXpos -= 1
display.set_pixel(enemyXpos,0,4)
display.set_pixel(playerXpos,4,6)
if button_a.is_pressed() and button_b.is_pressed():
laser(laserXpos,laserYpos)
elif button_a.is_pressed() and playerXpos > 0:
playerXpos -= 1
elif button_b.is_pressed() and playerXpos < 4:
playerXpos += 1
sleep(200)
def enemy_right(enemyXpos, playerXpos):
enemyXpos = 0
for i in range (4):
display.clear()
enemyXpos += 1
display.set_pixel(enemyXpos,0,4)
display.set_pixel(playerXpos,4,6)
if button_a.is_pressed() and button_b.is_pressed():
laser(laserXpos,laserYpos)
elif button_a.is_pressed() and playerXpos > 0:
playerXpos -= 1
elif button_b.is_pressed() and playerXpos < 4:
playerXpos += 1
sleep(200)
enemy_left(enemyXpos, playerXpos)
enemy_right(enemyXpos, playerXpos)
Related
while phealth > 0
while choice !a:
if choice.lower() == "a":
print('You attack the',name,"and do",pstrength,"damage!")
if random.random() < crit_chance:
print('You got a critical hit +5 more damage')
mhealth = mhealth - pstrength - 5
print(mhealth)
else:
mhealth = mhealth - pstrength
penergy = penergy - pstrength
print(mhealth)
if penergy <= 0:
print('You ran out of energy but thankfully the old man saved but you lost',random.randint(0, pcoins),'coins.')
coins = 0
if mhealth <= 0:
print('You killed the enemy and gained 1 coin')
pcoins = pcoins + 1
The code just keeps going. I would rather want it to reset at the beginning of the loop after the enemy has died.
This is not a full version of the code!!!
As posted by #ewz93 the code needed a reset message at the end!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So I've been trying to make this turn-based battle and I ran into a slight issue. I can't seem to use the variables that are defined within the if statement. I tried declaring them global but that didn't work. Is there any way to solve this problem while still using if statements?
Here the code that I'm having issues with:
import time
from random import randint
import copy
health = randint(100, 400)
speed = randint(50, 100,)
damage = randint(50, 200)
totalhealth = copy.deepcopy(health)
def stats():
print("Damage:",damage)
print("Health:",totalhealth, "|", health)
print("Speed:",speed)
if spawn == "mandrake":
spawnh = 200
spawnspeed = 50
spawnspeed = 50
eelement = "earth"
buff = "heal self"
gold = randint(10,20)
ms = 3
x = True
ss = 0
s = 0
ms = 0
m = 0
spawn = "mandrake"
while x == True:
battle = input("""
Inventory(1)
Run(2)
Attack(3)
Defend(4)
Skills(5)""")
stats()
if battle == '3':
if ss > 99 and spawnh > 0:
print(spawn, "dealt", spawndamage)
time.sleep(3)
ss -= 100
health = health - spawndamage
ms += 1
if s >= 100:
print("you dealt", damage)
time.sleep(3)
spawnh = spawnh - damage
s -= 100
if s <= 100 and spawnh > 0:
print("you prepare to attack")
time.sleep(3)
s += speed
if ss <= 100 and spawnh > 0:
print(spawn, "prepares to attack")
ss += spawnspeed
if ss >= 100 and spawnh > 0:
print(spawn, "dealt", damage)
time.sleep(3)
ss = ss - 100
health = health - spawndamage
if health <= 0:
print("you died!")
time.sleep(3)
if spawnh <= 0:
print("you are victorious!")
x = False
if spawnspeed < 100 and spawnh > 0:
print(spawn, "prepares to attack")
ss += spawnspeed
if health <= 0:
print("you died!")
time.sleep(3)
exit()
exit()
if spawnh <= 0:
print("you are victorious!")
x = False
You're trying to access a variable before it's been declared.
You've got if spawn == "mandrake": before you declare spawn, move spawn = "mandrake" above the if statement.
I made this simulation as a discordpy cog, but the bot goes offline and the console is open and don't do anything if I write or quit it...
At an amount of 15000 the bot crashes, what can I do, why it crashs?
There are discord emojies, which are selected randomly and there are different chances with the numbers etc. I hope somebody can help me here!
#bot.command()
async def simulate(self, ctx, amount):
wnitro = 0
wkey = 0
wgold = 0
wred = 0
wblue = 0
wgreen = 0
wgrey = 0
for zaehler in range(1, int(amount)):
drehungen = randint(5, 20)
gone = randint(1, 1000)
gtwo = randint(1, 1000)
gthree = randint(1, 1000)
gfour = randint(1, 1000)
gfive = randint(1, 1000)
gsix = randint(1, 1000)
gseven = randint(1, 1000)
geight = randint(1, 1000)
gnine = randint(1, 1000)
randomitem = [gone, gtwo, gthree, gfour, gfive, gsix, gseven, geight, gnine]
slots = []
for item in range(len(randomitem)):
if randomitem[item] >= 950:
slots.append("<a:classic:802844186026049546>")
elif randomitem[item] >= 850:
slots.append("<a:geld:770235576539676682>")
elif randomitem[item] >= 800:
slots.append("<a:goldendia:802976550995755019>")
elif randomitem[item] >= 650:
slots.append("<a:darkbluedia:802976435500875836>")
elif randomitem[item] >= 500:
slots.append("<a:reddia:802873281841463296>")
elif randomitem[item] >= 300:
slots.append("<a:greendia:802875898353156138>")
else:
slots.append("<a:greydia:802977070627553311>")
cdrehung = 1
nitroextra = randint(1, 100)
keyextra = randint(1, 10)
coinsextra = randint(1, 5)
coins2extra = randint(1, 2)
i = 0
while i < drehungen:
if cdrehung == 0:
gewinn = slots[4]
elif cdrehung == 1:
gewinn = slots[5]
elif cdrehung == 2:
gewinn = slots[6]
elif cdrehung == 3:
gewinn = slots[7]
elif cdrehung == 4:
gewinn = slots[8]
elif cdrehung == 5:
gewinn = slots[0]
elif cdrehung == 6:
gewinn = slots[1]
elif cdrehung == 7:
gewinn = slots[2]
elif cdrehung == 8:
gewinn = slots[3]
cdrehung -= 9
cdrehung += 1
i += 1
if i == drehungen:
if gewinn == "<a:classic:802844186026049546>":
if nitroextra == 1:
wnitro += 1
else:
drehungen += 1
elif gewinn == "<a:geld:770235576539676682>":
if keyextra == 1:
wkey += 1
else:
drehungen += 1
elif gewinn == "<a:goldendia:802976550995755019>":
if coinsextra == 1:
wgold += 1
else:
drehungen += 1
elif gewinn == "<a:darkbluedia:802976435500875836>":
if coins2extra == 1:
wblue += 1
else:
drehungen += 1
elif gewinn == "<a:reddia:802873281841463296>":
wred += 1
elif gewinn == "<a:greendia:802875898353156138>":
wgreen += 1
elif gewinn == "<a:greydia:802977070627553311>":
wgrey += 1
await ctx.send(f"There are the results out of `{str(amount)}x` spins: {str(wnitro)}x Nitro, {str(wkey)} Key, {str(wgold)} <a:goldendia:802976550995755019>, {str(wblue)} <a:darkbluedia:802976435500875836>, {str(wred)} <a:reddia:802873281841463296>, {str(wgreen)}<a:greendia:802875898353156138>, {str(wgrey)}<a:greydia:802977070627553311>")
thanks to everyone who helps c:
Update: I take it back, theoretically your slots could all be the same thing, or a combination of things that cause drehungen to always implement. You really need to reconsider the logic on your loop.
Update: actually that is false, you do update cdrehung which updates gewinn... this is pretty convoluted, but it does seems like it should have to end at some point. That being said this loop is a bit complicated, I would consider some debug messages for all these different variables to figure out what is going on.
Just looking at it, inside your while loop the state of gewinn doesn't change, or any of the other items (wnitro wkey wgold wblue)... sooo if that is the case it could mean that drehungen is always being incremented... which means i == drehungen is always true... which means an infinite loop.
Im getting this error when inputting my code in codewars. "Traceback:in module
in damaged_or_sunk
IndexError: list index out of range". However, when I try my code in spyder3, it works just fine. there are no indicators as to where this error is in the function damaged_or_sunk though.
def damaged_or_sunk (board, attacks):
a = sum(x.count(1) for x in board)
b = sum(x.count(2) for x in board)
c = sum(x.count(3) for x in board)
a1 = 0
b1 = 0
c1 = 0
points = 0
sunk = 0
damaged = 0
not_touched = 0
for each in attacks:
rand_row = each[0]
rand_col = each[1]
if board[rand_row][rand_col] == 1:
a1 += 1
elif board[rand_row][rand_col] == 2:
b1 += 1
elif board[rand_row][rand_col] == 3:
c1 += 1
else:
pass
if a1 == a:
points += 1
sunk += 1
elif a1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
if b1 == b:
points += 1
sunk += 1
elif b1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
if c1 == c:
points += 1
sunk += 1
elif c1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
return '{\'sunk\': %s, \'damaged\': %s, \'not_touched\': %s, \'points\': %s}' %(sunk, damaged, not_touched, points)
The couples in attacks contains (x, y) coordinates which must be list index.
I make the assumption that they are randomly generated, make sure that:
0 <= x < len(board[0])
0 <= y < len(board)
all( len(board[0]) == len(board[row]) for row in board)
I'm learning python still so the rest of my code may be flawed but my main problem is I cant disable this button when the Wood and Stone variable are at 0. I've tried using a while statement that runs the button.config(state=DISABLED) command when stone > 0 and wood > 0 but that didn't seem to work.
from tkinter import *
from tkinter import tkk
class main:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.CraftPickaxe = Button(frame, text = 'Pickaxe', command = self.craftPick)
self.CraftPickaxe.pack()
###RESOURCES###
self.wood = 1
self.stone = 1
self.pickaxe = 0
def craftPick(self):
self.stone -= 1
self.wood -= 1
self.pickaxe += 1
print(self.stone)
print(self.wood)
print(self.pickaxe)
def loop(self):
while True:
if self.stone < 0 and self.wood < 0:
self.CraftPickaxe.config(state=DISABLED)
elif self.stone > 0 and self.wood > 0:
self.CraftPickaxe.config(state=NORMAL)
root = Tk()
b = main(root)
root.mainloop()
EDIT:
what I think is happening now is that its not constantly checking the variables to see if it goes below zero and therefore not disabling at all. What I'm thinking may need to happen is a check that runs in the craftPick function.
I think that your problem is that your variable is 0 and not a negative number.
So when you check if your variable is less than 0 it won't disable it because your variable is not smaller than 0, it is exactly 0.
Try with this better
while True:
if self.stone < 1 and self.wood < 1:
self.CraftPickaxe.config(state=DISABLED)
elif self.stone > 0 and self.wood > 0:
self.CraftPickaxe.config(state=NORMAL)
Also, you must avoid the loop.
def craftPick(self):
self.stone -= 1
self.wood -= 1
self.pickaxe += 1
if self.stone < 1 and self.wood < 1:
self.CraftPickaxe.config(state=DISABLED)
elif self.stone > 0 and self.wood > 0:
self.CraftPickaxe.config(state=NORMAL)