jeudi 5 août 2021

putting in a loop and how to repeat

I've just started learning and I've only learnt the basics but this is my current code. I need to put it in a loop and ask the user to place the number for up to 8 times.

num_list = ['1','2','3','4','5',]
import random
num = random.choice(num_list)

table = [[' ', ' ', ' ', ' '],
         [' ', ' ', ' ', ' '],
         [' ', ' ', ' ', ' '],
         [' ', ' ', ' ', ' ']]

ss = {"W1":[0,0],
                "W2":[1,0],
                "W3":[2,0],
                "W4":[3,0],
                "X1":[0,1],
                "X2":[1,1],
                "X3":[2,1],
                "X4":[3,1],
                "Y1":[0,2],
                "Y2":[1,2],
                "Y3":[2,2],
                "Y4":[3,2],
                "Z1":[0,3],
                "Z2":[1,3],
                "Z3":[2,3],
                "Z4":[3,3]}



ans = input('where would you like to place it: ')

index_ = ss[ans][0]
columns_ = ss[ans][1]
table[index_][columns_] = num
print(table)

This code below here is supposed to make sure the user is placing the number adjacent to another number. How do I make sure it only starts to check on the 2nd turn onwards? And how do I get it to repeat the turn if it is not adjacent? I also wanted to put the code above into functions and call it at the end to make it neater but I'm not sure what to put in and what to not.

def moveandclip(n, x, y):
   n[0] = max(0, min(n[0] + x, 3))
   n[1] = max(0, min(n[1] + y, 3))
   return n

above = moveandclip(ss[ans], 0 ,1)
below = moveandclip(ss[ans], 0 ,-1)
left = moveandclip(ss[ans], -1 ,0)
right = moveandclip(ss[ans], 1 ,0)

if above == '' and below == '' and left == '' and right == '':
    print('It must be placed adjacent to another number.')
    repeat the turn
else:
    continue to next turn

Aucun commentaire:

Enregistrer un commentaire