Answer To: CPSC 231 - Fall XXXXXXXXXXUniversity of Calgary cpsc 231 assignment #5 Taffy Tangle If you’ve ever...
Snehil answered on Nov 23 2020
PlayGame.py
import random;
import time;
from turtle import *
from Tokens import *
grid = []
num_rows = 9
num_cols = 7
score = 0
score_needed=100
def check_valid_moves():
for i in range (0,num_rows):
for j in range(0,num_cols):
if is_valid_position(i+1,j):
swap_grid_val([i,j],[i+1,j])
if len(check_combo_at(i,j))>0 or len(check_combo_at(i+1,j))>0:
swap_grid_val([i,j],[i+1,j])
return True
swap_grid_val([i,j],[i+1,j])
if is_valid_position(i,j+1):
swap_grid_val([i,j],[i,j+1])
if len(check_combo_at(i,j))>0 or len(check_combo_at(i,j+1))>0:
swap_grid_val([i,j],[i,j+1])
return True
swap_grid_val([i,j],[i,j+1])
return False
def create_grid():
for i in range(0,num_rows):
line = []
for j in range(0,num_cols):
line.append(0)
grid.append(line)
fill_empty_cells()
if check_valid_moves()==False:
print("Initial grid invalid")
grid.clear()
create_grid()
def fill_empty_cells():
for i in range(0,num_rows):
j=0
while j < num_cols:
if grid[i][j]==0:
grid[i][j] = random.randint(1,6)
if len(check_combo_at(i,j))==0:
j+=1
else:
grid[i][j]=0
else:
j+=1
def is_valid_position(i,j):
return not (i<0 or i>=num_rows or j<0 or j>=num_cols)
def color_at(i,j):
if is_valid_position(i,j):
return grid[i][j]
else:
return -1
def check_combo_at(i,j):
if color_at(i,j)<=0:
return []
combo_list=[]
m=i-1
while is_valid_position(m,j) and color_at(i,j)==color_at(m,j):
combo_list.append([m,j])
m-=1
combo_list.append([i,j])
m=i+1
while is_valid_position(m,j) and color_at(i,j)==color_at(m,j):
combo_list.append([m,j])
m+=1
if len(combo_list) >= 3:
return combo_list
combo_list=[]
n=j-1
while is_valid_position(i,n) and color_at(i,j)==color_at(i,n):
combo_list.append([i,n])
n-=1
combo_list.append([i,j])
n=j+1
while is_valid_position(i,n) and color_at(i,j)==color_at(i,n):
combo_list.append([i,n])
n+=1
if len(combo_list) >= 3:
return combo_list
return []
grid_size = 100 # pixels
window_height = grid_size * num_rows + 50
window_width = grid_size * num_cols +8
font_size = 18 # size of characters for the text
def create_drawing_canvas():
# Set up the drawing window with enough space for the grid
setup(window_width, window_height)
setworldcoordinates(0, 0, window_width, window_height)
tracer(False)
bgcolor('light grey')
home()
def draw_tokens_in_grid():
reset()
tracer(0,0)
hideturtle()
penup()
for i in range(0,num_rows):
for j in range (0,num_cols):
if grid[i][j]>0:
draw_tokens[grid[i][j]-1](j*grid_size,i*grid_size)
goto(30,num_rows*grid_size+15)
color('black')
write("Score : "+str(score), align ='left', font=('Arial', font_size, 'normal'))
update()
previous_selection = []
cur_selection = []
def set_selected(y,x):
pencolor("red")
...