Hi there,
I am making a snake game in python. My game over function thrwos an error though. I have attached a screenshot of the error an my code. the game should be over when the head of the snake collides with the rest of the snake. Can you help fixing it? also where exactly should i call the game_over function, is it it correct in my code?
thanks you so much in advance
my code:
import snakelib
from snakelib import SnakeUserInterface
import importlib
width = 0 # initialized in play_snake
height = 0 # initialized in play_snake
ui = None # initialized in play_snake
SPEED = 1
direction = "r"
keep_running = True
#WIDTH = 10
#HEIGHT = 10
#SCALE = 0.75
#ui = SnakeUserInterface(WIDTH,HEIGHT,SCALE)
#ui.set_animation_speed(5)
class Coordinate:
def __init__(self,x,y):
self.x = x
self.y = y
def equals(self, coordinate):
if self.x == coordinate.x and self.y == coordinate.y:
return True
def shift(self,x_shift,y_shift):
self.x += x_shift
self.y += y_shift
def copy(self):
return Coordinate(self.x, self.y)
class CoordinateSnake:
def __init__(self):
self.coordinate_row = [] # (0, 2), (0, 1), (0, 0)
def add(self, coordinate):
self.coordinate_row.append(coordinate)
def addFront(self, coordinate):
self.coordinate_row.insert(0, coordinate)
def removeTail(self):
self.coordinate_row.pop(-1)
def contains(self, coordinate):
for el in self.coordinate_row:
if coordinate.equals(el):
return True
return False
head = Coordinate(1,0)
tail = Coordinate(0,0)
body = CoordinateSnake()
body.addFront(tail)
body.addFront(head)
apple = Coordinate(5,5)
def draw():
global head, tail, body, apple, CoordinateSnake
ui.clear()
for coord in body.coordinate_row:
ui.place(coord.x, coord.y, ui.SNAKE)
ui.place(apple.x,apple.y,ui.FOOD)
ui.show()
def generate_apple():
global apple, CoordinateSnake, Coordinate
nrFreeSpots = (width * height) - len(body.coordinate_row)
apple_spot = ui.random(nrFreeSpots)
i = 0
for y in range(height):
for x in range(width):
if not body.contains(Coordinate(x,y)):
#print(i, x, y)
if i == apple_spot:
apple = Coordinate(x,y)
return
i = i + 1
def process_event(event):
if event.name == 'alarm' and event.data == "refresh":
process_alarm()
draw()
elif event.name == "arrow":
process_arrow(event.data)
def process_arrow(data):
global direction
if data == "l" and direction != "r":
direction = "l"
elif data == "r" and direction != "l":
direction = "r"
elif data == 'u' and direction != "d":
direction = "u"
elif data == 'd' and direction != "u":
direction = "d"
def process_alarm():
global head,body,apple
move()
#game_over()
if head.x == width:
head.x = 0
if head.x < 0:
head.x = width - 1
if head.y == height:
head.y = 0
if head.y < 0:
head.y = height -1
game_over() #might be needed here instead. Depends on the tests
CoordinateSnake.addFront(body,head)
if apple.x == head.x and apple.y == head.y:
generate_apple()
else:
CoordinateSnake.removeTail(body)
game_over()
def move():
global direction, head
head = Coordinate.copy(head)
if direction == "r":
Coordinate.shift(head,1,0)
if direction == "l":
Coordinate.shift(head,-1,0)
if direction == "u":
Coordinate.shift(head,0,-1)
if direction == "d":
Coordinate.shift(head,0,1)
#draw()
def game_over():
global head, tail
#tmp_head = body.coordinate_row[0]
#tmp_body = body.coordinate_row[1:]
tmp_head = body.coordinate_row[-1]
tmp_body = body.coordinate_row[:-1]
for l in tmp_body:
if tmp_head.equals(l):
ui.set_game_over()
ui.show
return
def play_snake(init_ui):
global width, height, ui, keep_running
ui = init_ui
width, height = ui.board_size()
generate_apple()
draw()
while keep_running:
event = ui.get_event()
process_event(event)
# make sure you handle the quit event like below,
# or the test might get stuck in an infinite loop
if event.name == "quit":
keep_running = False
if __name__ == "__main__":
# do this if running this module directly
# (not when importing it for the tests)
ui = snakelib.SnakeUserInterface(10, 10)
ui.set_animation_speed(SPEED)
play_snake(ui)
Step by stepSolved in 3 steps with 2 images
- Need guidance on how to use Tkiner in visual studio. The tkiner program doesn't run, it shows as a syntax error. Code: from tkinter import* import tkinter.messagebox class Library: def __init_(self,root): self.root = root self.root.title("Library Inventory System") self.root.geometry("1350x750+0+0") BookId = StringVar() AuthorFullName=StringVar() PublicationYear=StringVar() BookTitle=StringVar() num_copies=StringVar() #===================Frames==========================# MainFrame = Frame(self.root) MainFrame.grid() TitleFrame = Frame(MainFrame, bd=2, padx=40, pady=8, bg="Cadet blue", relief=RIDGE) TitleFrame.pack(side=TOP) self.libTitle =Label(TitleFrame, font=('arial',46,'bold'),text="Library Inventory System") self.libTitle.grid(sticky=W) ButtonFrame…arrow_forwardHello, This is part of my hangman simulation in C++. If you compile and run it and type "Easy," the code should run. If you run it though, the body of the hangman doesn't align when you guess wrong. Could you help me with that and implement an if statement to repeat the program if user wants to play again? #include <iostream> #include <cstdlib> #include <ctime> #include <string> #include <iomanip>using namespace std; const int MAX_TRIES = 5;char answer; int letterFill(char, string, string&); int main() { string name; char letter; int num_of_wrong_guesses = 0; string word; srand(time(NULL)); // ONLY NEED THIS ONCE! // welcome the user cout << "\n\nWelcome to hangman!! Guess a fruit that comes into your mind."; // Ask user for for Easy, Average, Hard string level; cout << "\nChoose a LEVEL(E - Easy, A - Average, H - Hard):" << endl; cin >> level; // compare level if (level == "Easy") {//put all the string inside…arrow_forwardYou are hired by a game design company and one of their most popular games is The Journey. The game has a ton of quests, and for a player to win, the player must finish all the quests. There are a total of N quests in the game. Here is how the game works: the player can arbitrarily pick one of the N quests to start from. Once the player completes a quest, they unlock some other quests. The player can then choose one of the unlocked quests and complete it, and so on. For instance, let’s say that this game had only 4 quests: A, B, C, and D. Let’s say that after you complete • quest A, you unlock quests [B, D]. • quest B, you unlock quests [C, D]. • quest C, you unlock nothing [ ]. • quest D, you unlock quest [C]. Is this game winnable? Yes, because of the following scenario: The player picks quest A to start with. At the end of the quest A, the unlocked list contains [B, D]. Say that player chooses to do quest B, then the…arrow_forward
- Program in C++ & Visual Studio not Studio Code Everyone has played Yahtzee... Right? There are so many better dice games, but my family likes this one the best. A YouTube video that describes Yahtzee can be found here. The basic rules are as follows: At the start of your turn you roll five normal everyday six sided dice. In the course of your turn you would choose to reroll any of the dice up to two more times. We are more concerned in this problem with the dice at the completion of your turn. This website gives a great rundown of the probabilities of Yahtzee that you will need. NOTE: You may ONLY use a set and map data structure to complete the solution to this problem Let’s see what results the dice give us using the following data structures and process: Prompt the user to enter five valid numbers (Range: One to six inclusive on both ends) Each time the user enters a valid number, “place” it into a map of integersCreate and use a set of integers with your data to…arrow_forwardHelp with codearrow_forwardA retail company assigns a $5000 store bonus if monthly sales are $100,000 or more. Additionally, if their sales exceed 125% or more of their monthly goal of $90,000, then all employees will receive a message stating that they will get a day off. Step 3: Complete the pseudocode by writing the missing lines. When writing your modules and making calls, be sure to pass necessary variables as arguments and accept them as reference parameters if they need to be modified in the module. (Reference: Writing a Decision Structure in Pseudocode, page 118). Module main () //Declare local variables Declare Real monthlySales //Function calls Call getSales(monthlySales) ______________________________________________________ ______________________________________________________ End Module //this module takes in the required user input Module getSales(Real Ref monthlySales) Display “Enter the total sales for…arrow_forward
- MipMaps I Suppose that a pixel projects to an area of 10x28 texels in a texture map. From what mipmap level does the texture unit look up the texture value for this pixel, if the texture unit is using "nearest" lookup for mipmaps? Enter a single integer that is the mipmap level. A/arrow_forwardImage one is my code, I wanted to make some change to the blue part's code. The code I written in red(see image 1) is the method to check that an integer has exactly 5 digits is provided for you (fiveDigits). You just need to call it appropriately in your code(the part in blue square)! Notice that the fiveDigits method returns a boolean - think carefully about how you should use this return type to reprompt the user until they enter a valid zip code. And I want the same output be like (see image 2) for the invalid zip code part: I should only reprompt the user with the message "Invalid zip-code, enter valid zip-code: " until they enter a valid zip code. Similarly, if the user enters an invalid pain level, you should reprompt the user with the message "Invalid pain level, enter valid pain level (1-10): " until they enter a valid pain level. For example(image2)arrow_forwardHey im stuck on my assignment. It is supposed to be in javascript code and i forgot to specify that. Please Help!!! window.addEventListener("DOMContentLoaded", domLoaded); function domLoaded() { // TODO: Complete the function } function convertCtoF(degreesCelsius) { // TODO: Complete the function } function convertFtoC(degreesFahrenheit) { // TODO: Complete the function } HTML code <!DOCTYPE html> <html lang="en"> <title>Temperature Converter</title> <scriptsrc="convert.js"></script> <style> body { font-family:Arial, Helvetica, sans-serif; } label { display:block; } #errorMessage { color:red; } </style> <body> <h1>Temperature Converter</h1> <p> <labelfor="cInput">Celsius:</label> <inputid="cInput"type="text"> </p> <p> <labelfor="fInput">Fahrenheit:</label> <inputid="fInput"type="text"> </p>…arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education