def spawnMouseFood(): global spawnFood global pos if(spawnFood): spawnedFood = Food() spawnedFood.setPos(pos[0], pos[1], map) foodList.append(spawnedFood)
def _initEntities(self): self.player = Player(self) self.entities = [ self.player, Food.randomFood(self), Food.randomFood(self), ]
def add_food(self, b_name, b_quantity): b = Food(name= b_name, quantity= int(b_quantity)) self.response.write("> A quantidade de " + b.name + " eh: " + str(b.quantity)) b.put()
def __init__(self): """Constructor""" self.speed = START_SPEED # will increase game speed every 10 times we eat self.eaten = 0 # defining the outer wall blocks self.wallblock = pygame.Surface(( BLOCK_SIZE, BLOCK_SIZE, )) self.wallblock.set_alpha(255) self.wallblock.fill(BLUE) self.wallblockdark = pygame.Surface(( BLOCK_SIZE_INNER, BLOCK_SIZE_INNER, )) self.wallblockdark.set_alpha(255) self.wallblockdark.fill(BLUE_DARK) # initialize pygame, clock for game speed and screen to draw pygame.init() # initializing mixer, sounds, clock and screen pygame.mixer.init() self.eatsound = pygame.mixer.Sound("snakeeat.wav") self.crashsound = pygame.mixer.Sound("snakecrash.wav") self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode(( (WIDTH + 2) * BLOCK_SIZE, (HEIGHT + 2) * BLOCK_SIZE, )) pygame.display.set_caption("snake") font = pygame.font.SysFont(pygame.font.get_default_font(), 40) self.gameovertext = font.render("GAME OVER", 1, WHITE) self.starttext = font.render("PRESS ANY KEY TO START", 1, WHITE) self.screen.fill(BLACK) # we need a snake and something to eat self.snake = Snake(self.screen, WIDTH // 2, HEIGHT // 2) self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1) # food should not appear where the snake is while self.food.get_pos() in self.snake.pos_list: self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1) # only queue quit and and keydown events # pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN]) pygame.event.set_blocked([ pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP, pygame.MOUSEBUTTONDOWN, ])
def loop(self): """The game's main loop""" while True: # check crash or move outside the limits if self.snake.outside_limits(WIDTH, HEIGHT) or self.snake.crashed: self.crashsound.play() return # draw screen with snake and foods self.food.draw() self.snake.draw() self.draw_walls() pygame.display.flip() # check if snake eates if self.food.get_pos() == self.snake.get_head_pos(): self.eatsound.play() self.snake.grow() # food should not appear where the snake is self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1) while self.food.get_pos() in self.snake.pos_list: self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1) self.eaten += 1 # increase game speed if self.eaten % SPEED_INC == 0: self.speed += SPEED_TICK # game speed control self.clock.tick(self.speed) # get the next event on queue event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: actmotdir = self.snake.motion_dir if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_UP and actmotdir != DOWN: self.snake.motion_dir = UP elif event.key == pygame.K_DOWN and actmotdir != UP: self.snake.motion_dir = DOWN elif event.key == pygame.K_RIGHT and actmotdir != LEFT: self.snake.motion_dir = RIGHT elif event.key == pygame.K_LEFT and actmotdir != RIGHT: self.snake.motion_dir = LEFT # remove the snake and make movement self.snake.remove() self.snake.move()
def addFood(self, x, y=None, num = 1): # If no y was given then use the standard food distance above the tank if(y is None): y = self.height - self.foodDistance else: y = Util.clamp(self.tank.box.bottom, y, self.height) # Make sure the food will go in the tank x = Util.clamp(self.tank.box.left, x, self.tank.box.right) # Add the foods for _ in range(num): newFood = Food(world=self) newFood.pos = Vector2D(x, y) self.food.append(newFood)
def runTest(self): # Generate an XML file first. foods = {} for i in range(20): food = Food("Testfood " + str(i)) food.energy = 100 * i foods[food.name] = food gen = FoodDBGenerator(); gen.generate(XML_FILE, foods) # Now read. db = FoodDB() self.parser.setContentHandler(db) self.parser.parse(XML_FILE) assert len(db.getFoods()) == 20 os.remove(XML_FILE)
class ConsumerDB(saxutils.DefaultHandler): def __init__(self, from_time = None, to_time = None): self.search_from_time = from_time self.search_to_time = to_time self.days = {} def startElement(self, name, attrs): self.cur_val = "" if name == "day": date = attrs.get("date", None) date = xml.utils.iso8601.parse(date) if self.search_from_time and date < self.search_from_time: return if self.search_to_time and date > self.search_to_time: return date = datetime.date.fromtimestamp(date) self.cur_day = Day(date) elif name == "food": ftime = attrs.get("time", None) ftime = xml.utils.iso8601.parse(ftime) if self.search_from_time and ftime < self.search_from_time: return if self.search_to_time and ftime > self.search_to_time: return self.cur_food = Food(attrs.get("name", None)) time = datetime.datetime.fromtimestamp(ftime, tz.LocalTimezone()) self.cur_food.set_time(time) def characters(self, chr): self.cur_val = self.cur_val + chr def endElement(self, name): if name == "day": self.days[self.cur_day.date.ctime()] = self.cur_day elif name == "food": self.cur_day.add_food(self.cur_food) elif name == "weight": self.cur_day.set_weight(atof(self.cur_val)) elif name == "quantity": self.cur_food.quantity = atof(self.cur_val) elif name == "energy": self.cur_food.energy = atoi(self.cur_val) def getDays(self): return self.days
def load_game(self): loaded_dict = LoadGame.load() self.current_level_map_index = loaded_dict["level"] self.init_resources() self.snake.load_snake_from_coord(loaded_dict["snake"]) self.food = Food(loaded_dict["food"], 1) self.move_direction = loaded_dict["direction"] self.reload_game = False self.start()
def setUp(self): self.tester = Food(models.connect()) self.info = { "name": "peanut butter", "quantity": 100, "calories": 578, "proteins_g": 29.1, "carbs_g": 11.8, "fats_g": 46.1 }
def __init__(self, screen): self.screen = screen self.segments = [] self.blockSize = 20 self.segmentLife = 3 self.stillPlaying = True self.padding = 3 self.food = Food(self.screen) self.randomizeFood() self.score = 0 self.insert(Segment()) self.paused = False self.messages = []
def start(self): clock = pygame.time.Clock() game_over = False won = True first_load = True while not game_over: clock.tick(self.speed) for event in pygame.event.get(): self.event_handler(event) if self.reload_game: break if not self.pause: background = self.level.render() self.snake.render(background) if self.food == None: position = self.generate_free_position() self.food = Food(position, 1) background.blit(self.food.image, self.food.rect) self.screen.fill((0, 0, 0)) self.screen.blit(background, (0, 0)) self.screen.blit(self.score.image, self.score.rect) pygame.display.flip() if first_load: first_load = False self.pause = True continue not_collide = self.snake.update(self.move_direction) if not not_collide or self.level.collide(self.snake.position): game_over = True won = False if self.food.rect.colliderect(self.snake.head.rect): self.snake.grow(self.food.grow_rate) self.score.add(100) self.food = None if self.snake.length() == self.won_grow_rate: game_over = True if self.reload_game: self.load_game() elif won and game_over: self.load_next_level() elif game_over: print("Game over")
def runTest(self): # Generate an XML file first. days = {} for f in range(20): curtime = datetime.datetime(2005, 6, f + 1, 0, 0, 0, 0, tz.LocalTimezone()) day = Day(curtime) day.set_weight(100) for i in range(20): food = Food("Testfood " + str(i)) food.quantity = 10 + i food.energy = 100 * i food.time = curtime day.add_food(food) days[curtime.ctime()] = day gen = ConsumerDBGenerator(); gen.generate(XML_FILE, days) # Now read. db = ConsumerDB() self.parser.setContentHandler(db) self.parser.parse(XML_FILE) assert len(db.getDays()) == 20 os.remove(XML_FILE)
def get_food_from_form(self): foodname = self.comboboxentry_food.get_text() if len(foodname) <= 0: return hour = int(self.spinbutton_hour.get_value()) minute = int(self.spinbutton_minute.get_value()) time = datetime.time(hour, minute, 0, 0, tz.LocalTimezone()) date = self.get_calendar_date() date = date.combine(date, time) quantity = round(self.spinbutton_quantity.get_value(), 2) food = Food(foodname) food.set_quantity(quantity) food.set_energy(self.spinbutton_energy.get_value()) food.set_time(date) return food
def startElement(self, name, attrs): self.cur_val = "" if name == "day": date = attrs.get("date", None) date = xml.utils.iso8601.parse(date) if self.search_from_time and date < self.search_from_time: return if self.search_to_time and date > self.search_to_time: return date = datetime.date.fromtimestamp(date) self.cur_day = Day(date) elif name == "food": ftime = attrs.get("time", None) ftime = xml.utils.iso8601.parse(ftime) if self.search_from_time and ftime < self.search_from_time: return if self.search_to_time and ftime > self.search_to_time: return self.cur_food = Food(attrs.get("name", None)) time = datetime.datetime.fromtimestamp(ftime, tz.LocalTimezone()) self.cur_food.set_time(time)
import time from food import Food from scoreboard import Scoreboard from snake import Snake screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake Game") screen.tracer( 0 ) # turns the animation off to make all the snake segments line up. 0 sets it off snake = Snake() food = Food() score = Scoreboard() screen.listen() screen.onkeypress(snake.up, "Up") screen.onkeypress(snake.down, "Down") screen.onkeypress(snake.left, "Left") screen.onkeypress(snake.right, "Right") game_is_running = True while game_is_running: screen.update() # Update method will refresh the screen with all segments time.sleep(0.07) # Animate ths snake to make it appear it is moving faster snake.move_snake() # When the snake eats food if snake.head.distance(food) < 20:
class Game: """The main class that makes up the game""" def __init__(self): """Constructor""" self.speed = START_SPEED # will increase game speed every 10 times we eat self.eaten = 0 # defining the outer wall blocks self.wallblock = pygame.Surface(( BLOCK_SIZE, BLOCK_SIZE, )) self.wallblock.set_alpha(255) self.wallblock.fill(BLUE) self.wallblockdark = pygame.Surface(( BLOCK_SIZE_INNER, BLOCK_SIZE_INNER, )) self.wallblockdark.set_alpha(255) self.wallblockdark.fill(BLUE_DARK) # initialize pygame, clock for game speed and screen to draw pygame.init() # initializing mixer, sounds, clock and screen pygame.mixer.init() self.eatsound = pygame.mixer.Sound("snakeeat.wav") self.crashsound = pygame.mixer.Sound("snakecrash.wav") self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode(( (WIDTH + 2) * BLOCK_SIZE, (HEIGHT + 2) * BLOCK_SIZE, )) pygame.display.set_caption("snake") font = pygame.font.SysFont(pygame.font.get_default_font(), 40) self.gameovertext = font.render("GAME OVER", 1, WHITE) self.starttext = font.render("PRESS ANY KEY TO START", 1, WHITE) self.screen.fill(BLACK) # we need a snake and something to eat self.snake = Snake(self.screen, WIDTH // 2, HEIGHT // 2) self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1) # food should not appear where the snake is while self.food.get_pos() in self.snake.pos_list: self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1) # only queue quit and and keydown events # pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN]) pygame.event.set_blocked([ pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP, pygame.MOUSEBUTTONDOWN, ]) def draw_walls(self): """Draw all walls of the game surface""" # left and right walls for y in range(HEIGHT + 1): # pylint: disable=invalid-name self.screen.blit(self.wallblock, ( 0, y * BLOCK_SIZE, )) self.screen.blit(self.wallblockdark, ( 5, y * BLOCK_SIZE + 5, )) self.screen.blit(self.wallblock, ( (WIDTH + 1) * BLOCK_SIZE, y * BLOCK_SIZE, )) self.screen.blit(self.wallblockdark, ( (WIDTH + 1) * BLOCK_SIZE + 5, y * BLOCK_SIZE + 5, )) # upper and bottom walls for x in range(WIDTH + 2): # pylint: disable=invalid-name self.screen.blit(self.wallblock, ( x * BLOCK_SIZE, 0, )) self.screen.blit(self.wallblockdark, ( x * BLOCK_SIZE + 5, 5, )) self.screen.blit(self.wallblock, ( x * BLOCK_SIZE, (HEIGHT + 1) * BLOCK_SIZE, )) self.screen.blit(self.wallblockdark, ( x * BLOCK_SIZE + 5, (HEIGHT + 1) * BLOCK_SIZE + 5, )) def loop(self): """The game's main loop""" while True: # check crash or move outside the limits if self.snake.outside_limits(WIDTH, HEIGHT) or self.snake.crashed: self.crashsound.play() return # draw screen with snake and foods self.food.draw() self.snake.draw() self.draw_walls() pygame.display.flip() # check if snake eates if self.food.get_pos() == self.snake.get_head_pos(): self.eatsound.play() self.snake.grow() # food should not appear where the snake is self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1) while self.food.get_pos() in self.snake.pos_list: self.food = Food(self.screen, 1, HEIGHT + 1, 1, WIDTH + 1) self.eaten += 1 # increase game speed if self.eaten % SPEED_INC == 0: self.speed += SPEED_TICK # game speed control self.clock.tick(self.speed) # get the next event on queue event = pygame.event.poll() if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: actmotdir = self.snake.motion_dir if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_UP and actmotdir != DOWN: self.snake.motion_dir = UP elif event.key == pygame.K_DOWN and actmotdir != UP: self.snake.motion_dir = DOWN elif event.key == pygame.K_RIGHT and actmotdir != LEFT: self.snake.motion_dir = RIGHT elif event.key == pygame.K_LEFT and actmotdir != RIGHT: self.snake.motion_dir = LEFT # remove the snake and make movement self.snake.remove() self.snake.move() def game_over(self): """When crashed print "game over" and wait for Esc key""" self.clock.tick(LONG) self.snake.draw() self.draw_walls() for pos in self.snake.pos_list[1:]: self.screen.blit(self.snake.backblock, ( pos[1] * BLOCK_SIZE, pos[0] * BLOCK_SIZE, )) pygame.display.flip() self.clock.tick(SHORT) while True: self.screen.blit(self.gameovertext, ( (WIDTH - 4) * BLOCK_SIZE / 2, HEIGHT * BLOCK_SIZE / 2, )) pygame.display.flip() event = pygame.event.wait() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() def start(self): """The game starts here""" # press any key to start!!! self.draw_walls() self.screen.blit(self.starttext, ( (WIDTH - 10) * BLOCK_SIZE / 2, HEIGHT * BLOCK_SIZE / 2, )) pygame.display.flip() waiting = True while waiting: event = pygame.event.wait() if event.type == pygame.KEYDOWN: waiting = False self.screen.fill(BLACK) # main loop self.loop() self.game_over()
from turtle import Screen import time from snake import Snake from food import Food from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Anshika's Snake Game") screen.tracer(0) snake = Snake() food = Food() scoreboard = Scoreboard() screen.listen() screen.onkey(snake.up, 'Up') screen.onkey(snake.down, 'Down') screen.onkey(snake.left, 'Left') screen.onkey(snake.right, 'Right') game_on = True while game_on: screen.update() time.sleep(0.1) snake.move() #detect collision with food if snake.head.distance(food) < 15: snake.extend()
from turtle import Screen, Turtle from snake import Snake from food import Food from scoreboard import Scoreboard import time screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake Game by Christian Norton") screen.tracer(0) snake = Snake() food = Food() scoreboard = Scoreboard() screen.listen() screen.onkey(snake.up, "w") screen.onkey(snake.down, "s") screen.onkey(snake.right, "d") screen.onkey(snake.left, "a") is_on = True while is_on: screen.update() time.sleep(0.1) snake.move() # Snake has reached the food and has grown longer. if snake.head.distance(food) < 15: food.move_food()
import pygame from control import Control from snake import Snake from gui import Gui from food import Food pygame.init() window = pygame.display.set_mode((441,441)) pygame.display.set_caption("Змейка") control = Control() snake = Snake() gui = Gui() food = Food() gui.init_field() food.get_food_position(gui) var_speed = 0 while control.flag_game: gui.check_win_lose(window) control.control() window.fill(pygame.Color("Black")) if gui.game == "GAME": snake.draw_snake(window) food.draw_food(window) elif gui.game == "WIN": gui.draw_win(window) elif gui.game == "LOSE": gui.draw_lose(window) gui.draw_indicator(window)
from turtle import Turtle, Screen from time import sleep from snake import Snake from food import Food from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake Game") screen.tracer(0) # Initializing Object Block snake = Snake() food = Food() scoreboard = Scoreboard() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") screen.update() game_on = True while game_on: screen.update() sleep(0.1) snake.move()
import mlab from food import Food mlab.connect() # 1. Create: # 1.1. Create a food: f = Food( title="Banh canh", link= "https://static1.squarespace.com/static/52d3fafee4b03c7eaedee15f/t/5a0a08cbec212d1131d5d33d/1510607073306/banh-canh-2.jpg" ) # 1.2. Save it: # f.save() # 2. Read: # 2.1. Get cursor: f_objects = Food.objects() # Lazy loading # Consider as a list # 2.2. Process cursor: # f_first = f_objects[0] # Actual data transfering # print(f_first, f_first.title, f_first.link) # print(len(f_objects)) # Slow # print(f_objects.count()) # for f in f_objects: # print(f.title) # print(f.link) # print("------------------") # 3. Update:
def addIng(self, instructIndex, ingNo, desc): thisFood = Food(desc, ingNo, instructIndex) self.m[ingNo] = thisFood self.adjList.append([])
def create_food(foods, ssettings): food = Food(ssettings) foods.add(food)
def quit_game(): global game_is_on game_is_on = False screen = Screen() screen.setup(width=1280, height=800) screen.bgcolor("black") screen.title("Snake Game") screen.listen() screen.tracer(0) snake = Snake(3) food = Food() scoreboard = Scoreboard() game_is_on = True while game_is_on: screen.update() sleep(0.2) screen.onkey(snake.left, "a") screen.onkey(snake.right, "d") screen.onkey(snake.up, "w") screen.onkey(snake.down, "s") snake.move() # Detect collision with food. if food.relocate(snake.head.xcor(), snake.head.ycor()): snake.add_snake() scoreboard.score += 1
from drink import Drink from food import Food food1 = Food('Sandwich', 5, 330) food2 = Food('Chocolate Cake', 4, 450) food3 = Food('Cream Puff', 2, 180) foods = [food1, food2, food3] drink1 = Drink('Coffee', 3, 180) drink2 = Drink('Orange Juice', 2, 350) drink3 = Drink('Espresso', 3, 30) drinks = [drink1, drink2, drink3] print('Food') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print('Drinks') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') order = int(input('Enter food item number: ')) selected_food = foods[order] order = int(input('Enter drink item number: ')) selected_drink = drinks[order] count = int(
# Import class Food dan class Drink from food import Food from drink import Drink # Buat instance class Food dan berikan ke variable food1 food1 = Food('Roti Lapis',5) # Panggil method info dari food1 dan cetak nilai return print (food1.info()) # Buat instance class Drink dan berikan ke variable drink1 drink1 = Drink('Kopi',3) # Panggil method info dari drink1 dan cetak nilai return print (drink1.info())
from snake import Snake from food import Food from scoreboard import ScoreBoarde import time screen = Screen() screen.setup(width=600, height=600) screen.tracer(0) screen.bgcolor("Black") screen.title("Welcome to the Snake game") screen.listen() snake = Snake() food = Food() score_board = ScoreBoarde() game_on = True while game_on: screen.update() time.sleep(0.1) snake.move() # Storing high score in high_score.txt with open("high_score.txt", mode="w") as score_file: score_file.write(str(score_board.high_score)) # Detect collision with food
def message(score): root = tkinter.Tk() root.withdraw() messagebox.showinfo(title='You lost', message='Your score is ' + str(score)) width = 500 height = 500 rows = 20 size_row = width // rows win = pygame.display.set_mode((width, height)) pygame.display.set_caption("Snake game") s = Snake() f = Food(size_row) def update_scr(win): global s, size_row, f, rows win.fill((127, 127, 127)) s.draw(win, size_row) f.draw(win) pygame.display.update() clock = pygame.time.Clock() f.pickLocation(rows, s.tail) while True: pygame.time.delay(80) clock.tick(100)
class Game: num_enemies = 20 # we could attach this to a difficulty scale gamestate = {} # dictionary containing information about the game # we pass this info to other objects so they can know # what's going on in the game without directly accessing # each other's info. starting_ammo = 3 def __init__(self, screen): self.gamestate["gameover"] = False # define the game borders self.gamestate['min_x'] = -screen.window_width() / 2 self.gamestate['max_x'] = screen.window_width() / 2 self.gamestate['min_y'] = -screen.window_height() / 2 self.gamestate['max_y'] = screen.window_height() / 2 self.gamestate['enemies'] = [] # list of enemy positions self.gamestate['enemy_radius'] = Enemy.radius # the collision box self.gamestate['food_radius'] = Food.radius # the collision box self.gamestate['bullet_radius'] = Bullet.radius self.me = Player( starting_ammo=self.starting_ammo) # initialize the player self.gamestate[ 'score'] = self.me.score # get player's initial score (0) self.gamestate['lives'] = self.me.lives self.bullets = [] self.gamestate['bullets'] = [] self.food = Food(self.gamestate) # initialize the food self.gamestate['food'] = self.food._food.pos() # get the food position self.enemies = [] # initialize list of enemies for _ in range(self.num_enemies): self.enemies.append(Enemy( self.gamestate)) # create enemies one by one # add each enemy's initial position to gamestate self.gamestate['enemies'].append(self.enemies[-1]._enemy.pos()) # create the scoreboard self.scoreboard = Scoreboard(self.gamestate) # player controls def move(self, x, y): self.me.update_destination((x, y)) def shoot(self, x, y): self.me.shoot(x, y) if self.me.score > 0 and not self.gamestate["gameover"]: self.create_bullet(*self.me._player.pos(), self.me._player.heading()) self.me.score -= 1 # iterate over list of enemies and call their update methods def move_enemies(self): for enemy in self.enemies: enemy.update(self.gamestate) # gather information from game objects every frame and update info def update_gamestate(self): new_enemies = [] positions = [] for e in self.enemies: if not e.dead: new_enemies.append(e) positions.append(e._enemy.pos()) if len(self.enemies) != len(new_enemies): self.update_score = True self.enemies = new_enemies self.gamestate["enemies"] = positions # gather enemy positions self.gamestate["food"] = self.food._food.pos() # get food position self.gamestate["score"] = self.me.score # get current score self.gamestate['lives'] = self.me.lives new_bullets = [] positions = [] for bullet in self.bullets: if not bullet.dead: new_bullets.append(bullet) positions.append(bullet._bullet.pos()) self.bullets = new_bullets self.gamestate["bullets"] = positions # alternate ways of doing this: # self.bullets = [b for b in self.bullets if not b.dead] # self.gamestate["bullets"] = [b._bullet.pos() for b in self.bullets] # self.bullets = filter(lambda x: not x.dead, self.bullets) # self.gamestate["bullets"] = [b._bullet.pos() for b in self.bullets] def create_bullet(self, x, y, angle): self.bullets.append(Bullet(x, y, angle)) self.gamestate["bullets"].append((x, y)) def gameOver(self, win): msg = "YOU WIN" if win else "GAME OVER" self.gamestate["gameover"] = True for e in self.enemies: e.dead = True self.me._player.hideturtle() self.food._food.hideturtle() self.gameover = turtle.Turtle() self.gameover.color("white") self.gameover.penup() self.gameover.hideturtle() self.gameover.setx(self.gameover.xcor() - 200) self.gameover.write(msg, font=("Arial", 50, "bold")) def update(self): self.update_score = False self.move_enemies() self.me.update(self.gamestate) for bullet in self.bullets: bullet.update(self.gamestate) # if the player's score has increased since the last frame, # then reset the food position. # debug note: the reason this wasn't working before is because we hadn't updated the player score yet! # self.me.score updates after self.me.update() runs. That's why I moved that line to above. # Now, the order is as follows: # 1. move all the enemies # 2. move the player (and check for collisions with enemies and food, possibly increasing the score) # 3. move the food if the player picked it up # 4. update the gamestate (including new score) # 5. update the scoreboard using the updated gamestate if self.me.score > self.gamestate["score"]: self.food.reset(self.gamestate) self.update_score = True if self.me.score < self.gamestate["score"]: self.update_score = True if self.me.lives != self.gamestate["lives"]: self.update_score = True self.update_gamestate() if self.update_score and not self.gamestate["gameover"]: self.scoreboard.update(self.gamestate) if self.gamestate["lives"] == 0 and not self.gamestate["gameover"]: self.gameOver(win=False) if len(self.gamestate["enemies"] ) == 0 and not self.gamestate["gameover"]: self.gameOver(win=True)
from snake import Snake from food import Food pygame.init() screen = pygame.display.set_mode((400, 300)) myfont = pygame.font.SysFont('Comic Sans MS', 20) textsurface = myfont.render('0', False, (255, 255, 255)) done = False color = (0, 128, 255) clock = pygame.time.Clock() s = Snake(map_dimensions=(400,300)) f = Food() food_eaten = False f.generate(s.position) GAME_OVER = False UP_DIR = False DOWN_DIR = True RIGHT_DIR = False LEFT_DIR = False while not done and not GAME_OVER: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True
def logic(self): if self.frame_count % 1000 == 0: for i in range( randint(self.min_food_count * 2, self.min_food_count * 5)): if len(self.food) < self.min_food_count: x = randint(0, width - 10) + 5 y = randint(0, height - 10) + 5 r, g, b = randint(0, 255), randint(0, 255), randint(0, 255) f = Food(x, y, (r, b, g)) self.food.append(f) # mouse_x = pygame.mouse.get_pos()[0] # mouse_y = pygame.mouse.get_pos()[1] keys = pygame.key.get_pressed() left = keys[pygame.K_LEFT] right = keys[pygame.K_RIGHT] up = keys[pygame.K_UP] turn_speed = math.pi / 80 if left: self.player.head.angle -= turn_speed if right: self.player.head.angle += turn_speed # Boost if "up" arrow key is held if up: if len(self.player.tail) > 7: # Chance of player losing a segment of tail if they boost chance = 5000 if randint(0, 100000) < chance: self.player.tail.pop() self.player.speed = 4 else: self.player.speed = 2 # dx = mouse_x - self.seg.x # dy = mouse_y - self.seg.y # new_angle = math.atan2(dy, dx) # self.seg.angle = new_angle # self.seg.speed = 5 # self.seg.update() # Make the snake follow the mouse # dx = mouse_x - self.player.head.x # dy = mouse_y - self.player.head.y # new_angle = math.atan2(dy, dx) # self.player.head.angle = new_angle self.player.head.speed = self.player.speed # Slithering effect for i in range(len(self.player.tail)): if i == 0: dx = self.player.head.x - self.player.tail[i].x dy = self.player.head.y - self.player.tail[i].y else: dx = self.player.tail[i - 1].x - self.player.tail[i].x dy = self.player.tail[i - 1].y - self.player.tail[i].y new_angle = math.atan2(dy, dx) self.player.tail[i].angle = new_angle self.player.tail[i].speed = self.player.speed # Stop game if player touches edges if self.collision_edges(self.player.head.x, self.player.head.y, self.player.head.size): global running running = False # Add a segment to player's tail if the player touches food for food in self.food: if self.collision_circle(food.x, food.y, food.size, self.player.head.x, self.player.head.y, self.player.head.size): seg = Segment(self.player.tail[len(self.player.tail) - 1].x, self.player.tail[len(self.player.tail) - 1].y, self.player.seg_size, self.player.color) self.player.tail.append(seg) self.food.remove(food) # Stop snake if it touches the mouse # if self.collision_circle( # mouse_x, mouse_y, -5, # self.player.head.x, self.player.head.y, self.player.head.size # ): # self.player.head.speed = 0 # for seg in self.player.tail: # seg.speed = 0 # Limit distance between each tail segment for i in range(len(self.player.tail)): tail = self.player.tail limit = 12 if i == 0: x1 = self.player.head.x y1 = self.player.head.y r1 = self.player.head.size - limit x2 = tail[i].x y2 = tail[i].y r2 = tail[i].size - limit else: x1 = tail[i - 1].x y1 = tail[i - 1].y r1 = tail[i - 1].size - limit x2 = tail[i].x y2 = tail[i].y r2 = tail[i].size - limit if self.collision_circle(x1, y1, r1, x2, y2, r2): tail[i].speed = 0 # Update player's variables self.player.update() self.frame_count += 1
from score_board import Score from deadline import Deadline screen = Screen() score = Score() screen.bgcolor("black") screen.setup(600, 600) screen.title("Snake and Food") screen.tracer(0) screen.listen() deadline = Deadline() snake = Snake() food = Food() def start_game(): is_on = True while is_on: screen.update() time.sleep(0.08) snake.move() if snake.head.distance(food) <= 15: food.refresh() snake.extend() score.increment_score()
screen = Screen() screen.setup(width=SCREEN_SIZE, height=SCREEN_SIZE) screen.bgcolor('black') screen.title('Snake Game') screen.tracer(0) screen.listen() # Snake setup snake = Snake() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") # Food setup food = Food(GAME_BARRIER) def move_snake(): """while the game is on, updates the screen according to the game's set SPEED and moves the snake""" while game_on: screen.update() time.sleep(SPEED) detect_collision() snake.move() def detect_collision(): """triggers game_over when snake collides either with the game_barrier or it's own tail. Adds a score point in case of collision with food.""" # with food
class Snake(): def __init__(self, board_size, brain=None): if brain == None: _input_nodes = 5 _output_nodes = 4 self.brain = NeuralNetwork([_input_nodes] + hidden_layers + [_output_nodes]) else: self.brain = brain self.direction = "up" self.growcount = 1 self.death_cause = "None" self.board_size = board_size self.x = self.board_size // 2 self.y = self.board_size // 2 self.alive = True self.length = 5 self.food = Food(self.board_size) self.lifetime = 0 self.fitness = 0 self.tail = [[self.x, self.y - 4], [self.x, self.y - 3], [self.x, self.y - 2], [self.x, self.y - 1]] self.vector = [] self.left_to_live_start = 200 self.left_to_live = self.left_to_live_start self.parts = [[self.x, self.y - 4], [self.x, self.y - 3], [self.x, self.y - 2], [self.x, self.y - 1], [self.x, self.y]] # Add food positions and lengths for each move self.move_history = { "fitness": self.fitness, "moves": self.parts, "food_position": [[self.food.x, self.food.y] for i in range(len(self.parts))], "length": [self.length for i in range(len(self.parts))] } def think(self): outputs = self.brain.think(self.look()).flatten().tolist() self.direction = ["up", "down", "left", "right"][outputs.index(max(outputs))] def move(self): #vector = [delta_x, delta_y] self.lifetime += 1 self.left_to_live -= 1 if self.left_to_live <= 0: self.alive = False self.death_cause = "timeout" world.timeout += 1 if self.direction == "up": self.vector = [0, -1] elif self.direction == "down": self.vector = [0, 1] elif self.direction == "left": self.vector = [-1, 0] elif self.direction == "right": self.vector = [1, 0] if self.x == self.food.x and self.y == self.food.y: self.eat() while ([self.food.x, self.food.y] in self.tail): self.food.respawn() if [self.x, self.y] in self.tail: self.alive = False self.death_cause = "ranIntoSelf" world.ranIntoSelf += 1 if self.x >= self.board_size or self.y >= self.board_size or self.x < 0 or self.y < 0: self.alive = False self.death_cause = "wallCrash" world.wallCrash += 1 if self.alive: #Add new part self.tail.insert(0, [self.x, self.y]) #Remove last tail part self.tail.pop() self.x += self.vector[0] self.y += self.vector[1] self.move_history["moves"].append([self.x, self.y]) self.move_history["food_position"].append( [self.food.x, self.food.y]) self.move_history["length"].append(self.length) def eat(self): for _ in range(self.growcount): self.length += 1 #Append tail so this part is removed instead of actual tail self.tail.append([-1, -1]) self.left_to_live = self.left_to_live_start self.food.respawn() def calc_fitness(self): self.fitness = self.lifetime * self.lifetime * 2**math.floor( self.length) self.fitness = self.lifetime + (2**(self.length - 5) + ( (self.length - 5)**2.1) * 500) - (((self.length - 5)**1.2) * ((0.25 * self.lifetime)**1.3)) self.move_history["fitness"] = self.fitness return self.fitness def look(self): #Left, right, up, food inputs = [0, 0, 0, 0, 0] if [self.x - 1, self.y] in self.tail: inputs[0] = 1 if [self.x + 1, self.y] in self.tail: inputs[1] = 1 if [self.x, self.y - 1] in self.tail: inputs[2] = 1 if [self.x, self.y + 1] in self.tail: inputs[3] = 1 inputs[4] = np.arctan2((self.x - self.food.x), (self.y - self.food.y)) / 360 """ base_value = 0 distances = [ [base_value, base_value, base_value, base_value, base_value, base_value, base_value, base_value], [base_value, base_value, base_value, base_value, base_value, base_value, base_value, base_value], [base_value, base_value, base_value, base_value, base_value, base_value, base_value, base_value] ] ###### DEPRECATED ######### Wall and Tail combined into one # Check distance to the walls # These are the first 8 distances # UP # Top wall position is 0, so the y postion should be the distance #distances[0][0] = self.y # DOWN # Bottom wall position is the board size, so the distance should be board size - current position #distances[0][1] = self.board_size - self.y # LEFT # Left wall is 0, so the x postion should be the distance #distances[0][2] = self.x # RIGHT # Right wall is board size, so the distance should be board size - current position #distances[0][3] = self.board_size - self.x ###### DEPRECATED ######### # DOWN-LEFT #TEST, SHOW DIRECTION OF FOOD # self.x < food_x = food is to the right # self.x > food_x = food is left # self.y < food_y = food is below # self.y > food_y = food is above if self.x < self.food.x and self.y < self.food.y: distances[0] = [2 for i in range(len(distances[0]))] if self.x > self.food.x and self.y < self.food.y: distances[0] = [4 for i in range(len(distances[0]))] if self.x < self.food.x and self.y > self.food.y: distances[0] = [8 for i in range(len(distances[0]))] if self.x > self.food.x and self.y > self.food.y: distances[0] = [10 for i in range(len(distances[0]))] # DOWN-RIGHT # UP-LEFT # UP-RIGHT # Check distance to an obstacle (Wall and Tail) # These are the second 8 distances # UP # Find the closest distance of the parts that is above the current y position and is on the same x pos distances[1][0] = min([self.y - part[1] for part in self.tail if self.y > part[1] and self.x == part[0]] + [base_value]) # Wall distances[1][0] = min(self.y, distances[1][0]) # DOWN # Find the closest part that is below the current y position and is on the same x pos distances[1][1] = min([part[1] - self.y for part in self.tail if self.y < part[1] and self.x == part[0]] + [base_value]) # Wall distances[1][1] = min(self.board_size - self.y, distances[1][1]) # LEFT # Find the closest part that is to the left of the current x pos and on the same y pos distances[1][2] = min([self.x - part[0] for part in self.tail if self.x > part[0] and self.y == part[1]] + [base_value]) # Wall distances[1][2] = min(self.x, distances[1][2]) # RIGHT # Find the closest part that is to the right of the current x pos and on the same y pos distances[1][3] = min([part[0] - self.x for part in self.tail if self.x < part[0] and self.y == part[1]] + [base_value]) # Wall distances[1][3] = min(self.board_size - self.x, distances[1][3]) # Diagonals if (any([abs(part[0] - self.x) == abs(part[1] - self.y) for part in self.tail])): # DOWN-LEFT distances[1][4] = min([(abs(part[0] - self.x) + abs(part[1] - self.y)) if part[0] > self.x and part[1] < self.y else base_value for part in self.tail]) # DOWN-RIGHT distances[1][5] = min([(abs(part[0] - self.x) + abs(part[1] - self.y)) if part[0] > self.x and part[1] > self.y else base_value for part in self.tail]) # UP-LEFT distances[1][6] = min([(abs(part[0] - self.x) + abs(part[1] - self.y)) if part[0] < self.x and part[1] < self.y else base_value for part in self.tail]) # UP-RIGHT distances[1][7] = min([(abs(part[0] - self.x) + abs(part[1] - self.y)) if part[0] < self.x and part[1] > self.y else base_value for part in self.tail]) # Check distances to food # These are the third 8 distances # UP # Check if the food is at the same x then if it is upwards then assign the distance otherwise assign the base value distances[2][0] = (self.y - self.food.y) if self.food.x == self.x and self.y > self.food.y else base_value # DOWN # Check if the food is at the same x then if it is downards the assign the distance otherwise assign the base value distances[2][1] = (self.food.y - self.y) if self.food.x == self.x and self.y < self.food.y else base_value # LEFT # Check if the food is at the same y then if it is to the left assign the distance otherwise assign the base value distances[2][2] = (self.x - self.food.x) if self.food.y == self.y and self.x > self.food.x else base_value # RIGHT # Check if the food is at the same y then if it is to the right assign the distance otherwise assign the base value distances[2][3] = ( self.food.x - self.x) if self.food.y == self.y and self.x < self.food.x else base_value if abs(self.food.x - self.x) == abs(self.food.y - self.y): # DOWN-LEFT if (self.food.x > self.x and self.food.y < self.y): distances[2][4] = abs(self.food.x - self.x) + abs(self.food.y - self.y) # DOWN-RIGHT if (self.food.x > self.x and self.food.y > self.y): distances[2][5] = abs(self.food.x - self.x) + abs(self.food.y - self.y) # UP-LEFT if (self.food.x < self.x and self.food.y < self.y): distances[2][6] = abs(self.food.x - self.x) + abs(self.food.y - self.y) # UP-RIGHT if (self.food.x < self.x and self.food.y > self.y): distances[2][7] = abs(self.food.x - self.x) + abs(self.food.y - self.y) # Distances is 3x8 dimensional matrix # Make it into a column vector instead distances = np.array(distances).reshape(1, -1) print(distances) assert(distances.shape == (1, 24)) """ inputs = np.array(inputs).reshape(1, -1) return inputs def mutate(self): self.brain.mutate() def crossover(self, other_parent): # Create 2 children children_brains = self.brain.crossover(other_parent.brain) children = [] for child_brain in children_brains: children.append(Snake(self.board_size, child_brain)) return children
class Game(object): def __init__(self, screen_height, screen_width): pygame.init() self.screen_height = screen_height self.screen_width = screen_width self.level_maps = ("./data/level1.map", "./data/level2.map", "./data/level3.map") self.current_level_map_index = 0 self.pause = False self.won_grow_rate = 10 height_width = (self.screen_height, self.screen_width) self.screen = pygame.display.set_mode(height_width) pygame.display.set_caption("PySnake") self.score = Score((0, 500)) self.reload_game = False self.speed = 5 def init_resources(self): self.level = Level(self.level_maps[self.current_level_map_index]) self.snake = Snake((64, 64)) self.move_direction = Direction.RIGHT self.food = None def start(self): clock = pygame.time.Clock() game_over = False won = True first_load = True while not game_over: clock.tick(self.speed) for event in pygame.event.get(): self.event_handler(event) if self.reload_game: break if not self.pause: background = self.level.render() self.snake.render(background) if self.food == None: position = self.generate_free_position() self.food = Food(position, 1) background.blit(self.food.image, self.food.rect) self.screen.fill((0, 0, 0)) self.screen.blit(background, (0, 0)) self.screen.blit(self.score.image, self.score.rect) pygame.display.flip() if first_load: first_load = False self.pause = True continue not_collide = self.snake.update(self.move_direction) if not not_collide or self.level.collide(self.snake.position): game_over = True won = False if self.food.rect.colliderect(self.snake.head.rect): self.snake.grow(self.food.grow_rate) self.score.add(100) self.food = None if self.snake.length() == self.won_grow_rate: game_over = True if self.reload_game: self.load_game() elif won and game_over: self.load_next_level() elif game_over: print("Game over") def event_handler(self, event): if event.type == QUIT: sys.exit(0) elif event.type == KEYDOWN: key = pygame.key.get_pressed() new_direction = self.move_direction if key[pygame.K_LEFT]: new_direction = Direction.LEFT elif key[pygame.K_RIGHT]: new_direction = Direction.RIGHT elif key[pygame.K_UP]: new_direction = Direction.UP elif key[pygame.K_DOWN]: new_direction = Direction.DOWN elif key[pygame.K_p]: self.pause = not self.pause elif key[pygame.K_s]: self.pause = True level = self.current_level_map_index snake = self.snake.get_snake_coords() food = self.food.get_food_position() direction = self.move_direction SaveGame.save(level, snake, food, direction) elif key[pygame.K_l]: self.reload_game = True oposide_direction = self.opposite_direction(self.move_direction) if not oposide_direction == new_direction: self.move_direction = new_direction def opposite_direction(self, direction): if direction == Direction.UP: return Direction.DOWN elif direction == Direction.DOWN: return Direction.UP elif direction == Direction.LEFT: return Direction.RIGHT elif direction == Direction.RIGHT: return Direction.LEFT def generate_free_position(self): x, y = None, None while x is None or self.level.collide((x, y)) or self.snake.collide((x, y)): x = random.randrange(0, self.level.width - 32, 2) y = random.randrange(0, self.level.height - 32, 2) return (x, y) def load_next_level(self): if len(self.level_maps) - 1 == self.current_level_map_index: print("Game over, you win") return self.current_level_map_index += 1 self.init_resources() self.start() def get_current_level_map(self): return self.level_maps[self.current_level_map_index] def load_game(self): loaded_dict = LoadGame.load() self.current_level_map_index = loaded_dict["level"] self.init_resources() self.snake.load_snake_from_coord(loaded_dict["snake"]) self.food = Food(loaded_dict["food"], 1) self.move_direction = loaded_dict["direction"] self.reload_game = False self.start()
from food import Food from drink import Drink food1 = Food('サンドイッチ', 500, 330) food2 = Food('チョコケーキ', 400, 450) food3 = Food('シュークリーム', 200, 180) foods = [food1, food2, food3] drink1 = Drink('コーヒー', 300, 180) drink2 = Drink('オレンジジュース', 200, 350) drink3 = Drink('エスプレッソ', 300, 30) drinks = [drink1, drink2, drink3] print('食べ物メニュー') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print('飲み物メニュー') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') food_order = int(input('食べ物の番号を選択してください: ')) selected_food = foods[food_order]
def spawn_test_food(): food = Food() food.setPos(300, 300, map) foodList.append(food)
"""Gets random locations on the screen that are multiples of 30""" # Chooses random coordinates x = random.randint(0, width - 30) y = random.randint(0, height - 30) # Makes it a multiple of 30 x = x - (x % 30) y = y - (y % 30) return x, y snake = Snake(SCREEN, SNAKE_IMAGE, [180, 180]) snakes = [snake] food = Food(SCREEN, FOOD_IMAGE, get_random_pos()) # Pygame event loop running = True while running: SCREEN.fill([0, 0, 0]) # Clears the screen for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Checks for any keyboard input elif event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN and snake.direction != Direction.UP: # Move down snake.direction = Direction.DOWN
class Board: def __init__(self, screen): self.screen = screen self.segments = [] self.blockSize = 20 self.segmentLife = 3 self.stillPlaying = True self.padding = 3 self.food = Food(self.screen) self.randomizeFood() self.score = 0 self.insert(Segment()) self.paused = False self.messages = [] def draw(self): self.drawSegments() self.food.draw() self.drawScore() self.drawMessages() def drawSegments(self): for segment in self.segments: segment.draw(self.screen) def drawMessages(self): for message in self.messages: message.draw(self.screen) self.messages = [] def drawScore(self): scoreText = "Score: " + str(self.score) self.messages.append(Message(scoreText)) def insert(self, segment): self.segments.insert(0, segment) def updateSegments(self): survivingSegments = [] for segment in self.segments: segment.update() if segment.life > 0: survivingSegments.append(segment) self.segments = survivingSegments def update(self, direction='right'): if self.stillPlaying and not self.paused: self.updateSnake(direction) self.draw() elif not self.stillPlaying: self.draw() deathMessage = "You have died. Press space to reset or q to quit." self.messages.append(Message(deathMessage, self.screen.get_rect().centerx - TextRenderer.getRenderedWidth(deathMessage)/2, self.screen.get_rect().centery)); else: self.draw() def updateSnake(self, direction='right'): self.updateSegments() self.moveSnake(direction) if (not self.snakeIsInsideScreen(self.screen)) or (self.segments[0].getRect().collidelist(self.segments[1:]) != -1): self.stillPlaying = False if(self.collidingWithFood()): self.increaseLength(5) self.score += 1 self.randomizeFood() def snakeIsInsideScreen(self, screen): return screen.get_rect().contains(self.segments[0].getRect()) def moveSnake(self, direction): if(direction == 'right'): self.insert(Segment(self.segments[0].x + self.blockSize+self.padding, self.segments[0].y, self.segmentLife, self.blockSize)) elif(direction == 'left'): self.insert(Segment(self.segments[0].x - self.blockSize-self.padding, self.segments[0].y, self.segmentLife, self.blockSize)) elif(direction == 'up'): self.insert(Segment(self.segments[0].x, self.segments[0].y - self.blockSize-self.padding, self.segmentLife, self.blockSize)) elif(direction == 'down'): self.insert(Segment(self.segments[0].x, self.segments[0].y + self.blockSize+self.padding, self.segmentLife, self.blockSize)) def collidingWithFood(self): return self.segments[0].getRect().colliderect(self.food.getRect()) def increaseLength(self, length): self.segmentLife += length def randomizeFood(self): self.food.getRect().x = random.choice(range(10, self.screen.get_rect().width-(self.blockSize+self.padding+10))) self.food.getRect().y = random.choice(range(10, self.screen.get_rect().height-(self.blockSize+self.padding+10))) if(self.isCollidingWithSnake(self.food)): self.randomizeFood() def isCollidingWithSnake(self, collideableObject): return collideableObject.getRect().collidelist(self.segments) != -1
def test_food_class(): """ Test Food class. """ try: ice_cream_cone = Food("ice cream cone", 10, 1) assert ice_cream_cone.get_food_type() == "ice cream cone" assert ice_cream_cone.get_decay_value() == 10 assert ice_cream_cone.get_cleaning_value() == 1 ice_cream_cone.set_food_type("strawberry ice cream cone") assert ice_cream_cone.get_food_type() == "strawberry ice cream cone" carrot = Food("carrot", 2, 10) carrot.set_decay_value(1) carrot.set_cleaning_value(15) assert carrot.get_decay_value() == 1 assert carrot.get_cleaning_value() == 15 print("All Food class tests pass!") except: message_1 = sys.exc_info()[0] message_2 = sys.exc_info()[2] print("Caught an error: {}\n {}".format(message_1, message_2))
class Snake(object): """This class draws and operates the line for Snake game""" def __init__(self, pen, food_pen): """Constructor for Square class. This funcion is called upon initialization. It saves a turtle object as a class member, start line length to 5, creates list of Squares, set direction to 'r', default speed to 1, creates food for snake and creates snake itself. Parameters ---------- pen : turtle Turtle object that will draw the square food_pen : turtle Turtle object that will draw the food Returns ------- None """ self.speed = 1 self.snake = [] self.direction = 'r' self.length = 5 self.pen = pen self.food_pen = food_pen # creating initial snake for i in range(self.length): square = Square(self.pen) square.set_square(i*-square.size, square.size) self.snake.append(square) self.food = Food(self.food_pen) self.food.create_food() def set_direction(self,value): """Change direction of the snake. Possible directions are: `r`, `l`, `u`, `d`. Parameters ---------- value : str New snake direction Returns ------- None """ if self.direction == 'r' and value != 'l': self.direction = value if self.direction == 'l' and value != 'r': self.direction = value if self.direction == 'u' and value != 'd': self.direction = value if self.direction == 'd' and value != 'u': self.direction = value def self_collision(self): """Check snake collision with itself. Parameters ---------- None Returns ------- collision bool """ collision = False for sqr in range(1,len(self.snake)): if self.snake[0].x == self.snake[sqr].x and self.snake[0].y == self.snake[sqr].y: collision = True return collision def border_collision(self): """Check snake collision with border. Parameters ---------- None Returns ------- collision bool """ collision = False if self.snake[0].x > 200 or self.snake[0].x < -200: collision = True elif self.snake[0].y > 200 or self.snake[0].y < -200: collision = True return collision def draw_snake(self): """Draw snake. Parameters ---------- None Returns ------- None """ for i in range(len(self.snake)): self.snake[i].draw(self.snake[i].x,self.snake[i].y, "black") def move_snake(self): """Move snake. Parameters ---------- None Returns ------- None """ old_x = self.snake[0].x old_y = self.snake[0].y for square in range(len(self.snake)): if square == 0: old_x = self.snake[square].x if self.direction == "r": self.snake[square].x += self.snake[0].size elif self.direction == "l": self.snake[square].x -= self.snake[0].size elif self.direction == "u": self.snake[square].y += self.snake[0].size elif self.direction == "d": self.snake[square].y -= self.snake[0].size else: old_x, self.snake[square].x = self.snake[square].x, old_x old_y, self.snake[square].y = self.snake[square].y, old_y def food_collision(self,x,y): """Check collision with food. Parameters ---------- x Horisontal Coordinate y Vertical Coordinate Returns ------- collision bool """ collision = False # food_collision if self.food.collision_with_food(x,y): # add square to the snake square = Square(self.pen) square.set_square(x,y) self.snake.append(square) # make snake move faster self.increase_speed() # make more food self.food.create_food() self.food.draw_food() # increase the length of the snake self.length += 1 collision = True return collision def increase_speed(self): """Incerease speed of the snake. Parameters ---------- None Returns ------- None """ self.speed += 1
class TestFoodController(unittest.TestCase): def setUp(self): self.tester = Food(models.connect()) self.info = { "name": "peanut butter", "quantity": 100, "calories": 578, "proteins_g": 29.1, "carbs_g": 11.8, "fats_g": 46.1 } def test_food_is_added(self): self.tester.add(self.info) self.food_atributes = (self.tester.get("peanut butter")).__dict__ self.dict = {} self.dict["name"] = self.food_atributes["name"] self.dict["quantity"] = self.food_atributes["quantity"] self.dict["calories"] = self.food_atributes["calories"] self.dict["proteins_g"] = self.food_atributes["proteins_g"] self.dict["carbs_g"] = self.food_atributes["carbs_g"] self.dict["fats_g"] = self.food_atributes["fats_g"] self.assertEqual(self.info, self.dict) self.tester.remove_by_name("peanut butter") def test_add_same_food_twice(self): self.tester.add(self.info) self.assertIsNone(self.tester.add(self.info)) self.tester.remove_by_name("peanut butter") def test_update_field_name(self): self.tester.add(self.info) self.tester.update_field("peanut butter", "name", "seeds butter") self.assertEqual( "seeds butter", (self.tester.get("seeds butter")).__dict__["name"]) self.tester.remove_by_name("seeds butter") def test_update_field_calories(self): self.tester.add(self.info) self.tester.update_field("peanut butter", "calories", 500) self.assertEqual( 500, (self.tester.get("peanut butter")).__dict__["calories"]) self.tester.remove_by_name("peanut butter") def test_update_field_proteins(self): self.tester.add(self.info) self.tester.update_field("peanut butter", "proteins_g", 60) self.assertEqual( 60, (self.tester.get("peanut butter")).__dict__["proteins_g"]) self.tester.remove_by_name("peanut butter") def test_update_field_carbs(self): self.tester.add(self.info) self.tester.update_field("peanut butter", "carbs_g", 60) self.assertEqual( 60, (self.tester.get("peanut butter")).__dict__["carbs_g"]) self.tester.remove_by_name("peanut butter") def test_update_field_fats(self): self.tester.add(self.info) self.tester.update_field("peanut butter", "fats_g", 60) self.assertEqual( 60, (self.tester.get("peanut butter")).__dict__["fats_g"]) self.tester.remove_by_name("peanut butter") def test_remove_existing_food_record(self): self.tester.add(self.info) self.tester.remove_by_name("peanut butter") self.assertIsNone(self.tester.get("peanut butter")) def test_remove_not_existing_food_record(self): self.assertIsNone(self.tester.remove_by_name("peanut butter")) def test_get_not_existing_food_record(self): self.assertIsNone(self.tester.get("peanut butter")) def test_get_existing_food_record(self): self.tester.add(self.info) self.assertEqual( "peanut butter", (self.tester.get("peanut butter")).name) self.tester.remove_by_name("peanut butter")
def drive(self, max_iterations=500, random_seed=0, initial_pop=50): """ Args: max_iterations: Integer. The maximum number of iterations the simulation should run. random_seed: Integer. Seed for the random number generator. initial_pop: Integer. The initial population for the population. Returns: None. """ # Dictionary to keep track of results self.results = defaultdict(list) # Seed the random number generator. random.seed(random_seed) # Create a dictionary that will hold the number of newborns that will # be added to the simulation. people_born = { k: 0 for k in range(9) } # Set the maximum number of iterations that the simulation will run. max_sim_time = max_iterations # Initialize a population. population = Population() # Initialize an air instance for modeling oxygen consumption. air = Air(population) # Initialize a power instance for modeling power consumption. power = Power(population) # Initial Iteration cur_sim_time = 0 start = time.time() # Add initial population initial_ages = [10, 18, 20, 25, 28, 30, 32, 35, 40, 45, 50, 55] for add_count in range (initial_pop): init_age = cur_sim_time - initial_ages[add_count % len(initial_ages)]*12.0 population.add_person(Person(init_age, population.get_rand_death_time(cur_sim_time), random.random())) print 'added', people_born.get(cur_sim_time % 9, 0), 'people in', time.time()-start start = time.time() total_kcal = population.kcal_requirements(cur_sim_time) print 'completed total kcal in:', time.time() - start # Create a facility for population # Crop area of 25000 feeds about 30 people facility = Facility(30000.0/30.0*(initial_pop+30), initial_pop+30) # Food initialization food = Food(facility, total_kcal) # Create a disaster object for the population - this models uncertainty # events that may adversely affect the population & food disaster = Disaster(population, food) # Write initial loop results self._write_results(population=population.num_people(), food=food.produced_food, kcals=total_kcal, facility_crop=facility.crop_area, facility_personnel=facility.personnel_capacity, air=air.oxygen_consumed(), power=power.power_consumed()) # Main iteration loop for cur_sim_time in range(1, max_sim_time): print 'current sim time:', cur_sim_time start = time.time() # Diasters if random.random() <= 0.01: #ratio = random.random()/10.0 #disaster.create_disaster(ratio) #print 'DISASTER killed', ratio, 'in:', time.time() - start death_from_disaster = random.randint(1,20) disaster.create_disaster(death_from_disaster) print 'DISASTER killed', death_from_disaster, 'people and', (death_from_disaster+10)*2500.0, 'food in:', time.time() - start start = time.time() # If enough food, expand facility. Assume 3 month build time if food.remaining_food > 2500*10 and (facility.personnel_capacity - population.num_people()) <= 10: facility.start_pod_construction(cur_sim_time, 3) facility.add_pod(cur_sim_time) # Adding newborns born_count = 0 for add_count in range (people_born.get(cur_sim_time % 9, 0)): if population.num_people() < facility.personnel_capacity: population.add_person(Person(cur_sim_time, population.get_rand_death_time(cur_sim_time), random.random())) born_count += 1 print 'added', born_count, 'people in', time.time()-start # Removing the dead start = time.time() people_to_kill = len(population.death_dict.get(cur_sim_time, [])) population.remove_dead(cur_sim_time) print 'removed', people_to_kill, 'people in:', time.time() - start # Calculating total kcal start = time.time() total_kcal = population.kcal_requirements(cur_sim_time) print 'completed total kcal in:', time.time() - start # Food consumption food_delta = food.update_food(total_kcal) print 'produced food = ', food.produced_food, '; remaining food = ', food.remaining_food # if not enough food if food_delta < 0: # people who are unfed will die, starting with oldest people while (food_delta < 0): food_delta = food_delta + population.people[0].kcal_requirements(cur_sim_time) population.remove_person(0) population.generate_death_dict() # Calculating how many newborns to be created in 9 months time num_people = population.num_people() num_adults = population.num_adults(cur_sim_time) # newborns based on number of adults. Average US birthrate in 2014: 0.01342 (indexmundi.com) people_born[cur_sim_time % 9] = random.randint(np.rint(num_adults*0.01),np.rint(num_adults*0.020)) print 'total people:', num_people, 'and total adults:', num_adults, 'and total kcal:', total_kcal print 'total capacity:', facility.personnel_capacity print('-'*100) # Record results of the iteration. self._write_results(population=num_people, food=food.produced_food, kcals=total_kcal, facility_crop=facility.crop_area, facility_personnel=facility.personnel_capacity, air=air.oxygen_consumed(), power=power.power_consumed()) # If the visualization option has been selected, plot the results # every 10 timesteps. if self.vis and cur_sim_time % 10 == 0: # Add data for the chart. self.vis.add_data(cur_sim_time, { 'Population Count': num_people, 'Adult Count': num_adults, 'Caloric Requirements (Mcal)': total_kcal / 1000.0, 'Produced Food (Mcal)': food.produced_food / 1000.0, 'Air (kg O2)': air.oxygen_consumed(), 'Power Consumption (kWh)': power.power_consumed() }) # Update the chart, re-rendering. self.vis.update() # If visualization has been selected, if self.vis: # Save the last rendered chart as a png image. self.vis.savefig() # Return the results dict. return self.results
def step(self): self.fish.update(self.food) if self.eaten(self.fish, self.food): self.fish.energy += 10 self.numEaten += 1 self.food = Food(self.fish.x, self.fish.y, self.fish.z)
random.seed(seed) print("Seed for world =", seed) ## global vars canvasWidth = 530 canvasHeight = 530 ## Tkinter Stuff root = Tk() c = Canvas(root, width=canvasWidth, height=canvasHeight) pixies = [] foods = [] ## call class c.create_rectangle(0, 0, canvasWidth, canvasHeight, fill="#19722f") for i in range(10): x = random.random() * canvasWidth y = random.random() * canvasHeight pixies.append(Pixie(c, x, y)) c.pack() # the simulation while True: if len(foods) < 1000: foods.append(Food(c)) for pixie in pixies: pixie.goTo(c, foods) c.update() root.mainloop()
# parse options try: opts, args = getopt.getopt(args, "ho:i:t:n:", ["help"]) except getopt.GetoptError, err: rtfm(str(err)) # set options out_dir = in_dir = None listtype = None num_people = None for opt, arg in opts: if opt == '-o': out_dir = arg elif opt == '-i': in_dir = arg elif opt == '-n': num_people = int(arg) elif opt == '-t': if arg not in ('recipes', 'shoppinglist'): rtmf("invalid type: %s" % arg) listtype = arg elif opt in ('-h', '--help'): usage() sys.exit() # not correctly filled if None in (out_dir,in_dir,listtype,num_people): rtfm("missing required options") # generate list food = Food() food.load_dir(in_dir) GENERATORS[listtype](food, out_dir, num_people) if __name__ == '__main__': main(sys.argv[1:])
def __init__(self, food_row, food_col): self.player = None self.enemy = None if food_row <= 0 or food_row >= World.TOTAL_ROWS - 1: raise RuntimeError('Invalid food_row') if food_col <= 0 or food_col >= World.TOTAL_COLS - 1: raise RuntimeError('Invalid food_col') self.grid = [] for row in range(World.TOTAL_ROWS): col_list = [None] * World.TOTAL_COLS self.grid.append(col_list) ''' Map: wwwwwwwwwwwwwwwwwwww w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w wwwwwwwwwwwwwwwwwwww ''' # initialize top row for col in range(World.TOTAL_COLS): self.grid[0][col] = Wall(0, col) # initialize bot row for col in range(World.TOTAL_COLS): self.grid[World.BOT_ROW][col] = Wall(World.RIGHT_COL, col) # initialize left col for row in range(1, World.BOT_ROW): self.grid[row][0] = Wall(row, 0) # initialize right col for row in range(1, World.BOT_ROW): self.grid[row][World.RIGHT_COL] = Wall(row, World.RIGHT_COL) # put food in specified row, col self.food = Food(food_row, food_col) self.grid[food_row][food_col] = self.food # create SubWorlds self.subworlds = [] ''' Each SubWorld has 5 rows and 5 cols SW0 SW1 SW2 SW3 SW4 SW5 SW6 SW7 SW8 SW9 SW10 SW11 SW12 SW13 SW14 SW15 ''' row_iter = 0 col_iter = 0 while row_iter < World.TOTAL_ROWS: col_iter = 0 while col_iter < World.TOTAL_COLS: row_range = range(row_iter, row_iter + World.NUM_SUBWORLD_ROWS) col_range = range(col_iter, col_iter + World.NUM_SUBWORLD_COLS) new_world = World.SubWorld(row_range, col_range) new_world.reset_bounds(self) self.subworlds.append(new_world) col_iter += (World.NUM_SUBWORLD_COLS) row_iter += (World.NUM_SUBWORLD_ROWS)
from scoreboard import Scoreboard from food import Food #Kullanımı kolaylaştırmak amacıyla Snake,Scoreboard ve Food olarak üç ayrı class oluşturup module halinde import ediyoruz. screen = Screen() screen.setup(width=600, height=600) screen.bgcolor('black') screen.tracer( False ) #Ekrandaki otomatik update özelliğini kapatır. Manual olarak kendiniz yapmak istiyorsanız bu özelliği kapatmanız gerekiyor. screen.title('My Snake Game') snake = Snake() scoreBoard = Scoreboard() food = Food() #Screen Event Listeners screen.listen() screen.onkey(snake.up, 'Up') screen.onkey(snake.down, 'Down') screen.onkey(snake.left, 'Left') screen.onkey(snake.right, 'Right') game_is_on = True while game_is_on: screen.update( ) # Her hareket edildiğinde görüntüyü update ederiz, sanki bir animasyonun karelerini birleştiriyormuşuz gibi düşünülebilir. time.sleep( 0.075 ) # Burada time.sleep olmamış olsa o kadar hızlı bir animasyon elde ederiz ki, kontrol etmesi imkansızlaşır.
from turtle import Screen from snake import Snake from food import Food from scoreboard import Score import time screen = Screen() screen.setup(width=600, height=600) screen.title("Snake Game") screen.bgcolor("black") screen.tracer(0) snake = Snake() food = Food() score = Score() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") game_is_on = True while game_is_on: screen.update() time.sleep(0.1) snake.move() # detect collision with food and updating score
delay = 0.1 wn = Screen() wn.title("Snake Game") wn.bgcolor("black") wn.setup(width=600, height=600) #Accesses the X on the GUI canvas = wn.getcanvas() root = canvas.winfo_toplevel() #Snake snake = Snake() #Food food = Food() #Score Board scoreboard = ScoreBoard() #Turn off the screen updates wn.tracer(0) #Keyboard bindings wn.listen() wn.onkeypress(snake.go_up, "Up") wn.onkeypress(snake.go_down, "Down") wn.onkeypress(snake.go_left, "Left") wn.onkeypress(snake.go_right, "Right") segments = []
def act1(): from food import Food from drink import Drink from dressing import Dressing food1 = Food('High Five Power Salad', 1580, 476) food2 = Food('Smoked Duck & Honey Nut Salad', 1080, 220) food3 = Food("Grilled Chicken & Egg Salad", 980, 262) food4 = Food('Prosciutto & Mimolette Cheese Salad', 980, 139) food5 = Food('Garlic Shrimp Salad', 1280, 113) food6 = Food('Skip', 0, 0) foods = [food1, food2, food3, food4, food5, food6] dressing1 = Dressing('Classic Caesar', 0, 73) dressing2 = Dressing('Onion Soy', 0, 107) dressing3 = Dressing('Creamy Seasame', 0, 67) dressing4 = Dressing('Honey Mustard', 0, 127) dressing5 = Dressing('Balsamic Vinaigrette', 0, 127) dressing6 = Dressing('Skip', 0, 0) dressings = [ dressing1, dressing2, dressing3, dressing4, dressing5, dressing6 ] drink1 = Drink('Green Smoothie', 360, 126) drink2 = Drink('Homemade Soup', 360, 234) drink3 = Drink('Iced Coffee', 100, 15) drink4 = Drink('Seasonal Smoothie', 500, 245) drink5 = Drink('Skip', 0, 0) drinks = [drink1, drink2, drink3, drink4, drink5] print() print('***** FOOD MENU *****') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print() print('***** DRESSING MENU *****') index = 0 for dressing in dressings: print(str(index) + '. ' + dressing.info()) index += 1 print() print('***** DRINK MENU *****') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') #lim #if choose invalid numbers print('--------------------') while True: food_order = input('Please select a number from the food menu: ') if food_order == '0' or food_order == '1' or food_order == '2' or food_order == '3' or food_order == '4' or food_order == '5' or food_order == '6': selected_food = foods[int(food_order)] else: print("Please insert a valid number.") print() continue break while True: dressing_order = input( 'Please select a number from the dressing menu: ') if dressing_order == '0' or dressing_order == '1' or dressing_order == '2' or dressing_order == '3' or dressing_order == '4' or dressing_order == '5': selected_dressing = dressings[int(dressing_order)] else: print("Please insert a valid number.") print() continue break while True: drink_order = input('Please select a number from the drink menu: ') if drink_order == '0' or drink_order == '1' or drink_order == '2' or drink_order == '3' or drink_order == '4' or drink_order == '5': selected_drink = drinks[int(drink_order)] else: print("Please insert a valid number.") print() continue break count = int( input( 'How many sets would you like to purchase?(10% off when you purchase 3 sets): ' )) result = selected_food.get_total_price( count) + selected_drink.get_total_price(count) #print total # sophia #grace print() print('----------------------------------------------------------') print('Here is your total order:') print() print( str(selected_food.name) + ' ¥' + str(selected_food.price) + ' x ' + str(count)) print( str(selected_dressing.name) + ' ¥' + str(selected_dressing.price) + ' x ' + str(count)) print( str(selected_drink.name) + ' ¥' + str(selected_drink.price) + ' x ' + str(count)) if count >= 3: print('10% discount') else: print(' ') print('----------------------------------------------------------') print('Your total is ' + str(result) + ' Yen') print() print('Thank you for using W-Delivers! We hope to serve you again soon!') print('----------------------------------------------------------') print() print('Your order is on its way') #lim import time for i in range(100): print('.', end='') time.sleep(1)
def shuffleFood(self, food): self.entities.insert(0, Food.randomFood(self)) self.entities.remove(food)
screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake game") screen.tracer(0) #SNAKES STARTING POSITIONS CONFIGURATION STARTING_POSITIONS_1 = [(80, 0), (60, 0), (40, 0)] STARTING_POSITIONS_2 = [(-60, 0), (-80, 0), (-100, 0)] #GAME OBJECTS snake_1 = Snake("white", STARTING_POSITIONS_1) snake_2 = Snake("red", STARTING_POSITIONS_2) snakes = [snake_1, snake_2] food_1 = Food() food_2 = Food() foods = [food_1, food_2] #SCOREBOARD POSITIONS SCORE_1_POSITION = (200, 280) SCORE_2_POSITION = (-200, 280) score_1 = Scoreboard("white", SCORE_1_POSITION) score_2 = Scoreboard("red", SCORE_2_POSITION) scores = {snake_1: score_1, snake_2: score_2} #CONTROL CONFIGURATION screen.listen() screen.onkey(snake_1.up, "Up")