This is the 21st day of my participation in the August More Text Challenge
Topic request
Let’s start with the requirements:
Game programming: Define a turtle and a fish and try to write a game
- Assume that the game scenario has a range (x,y) of 0<=x<=10,0<=y<=10
- The game generates 1 turtle and 10 fish
- They all move in random directions
- A turtle has a maximum movement of 2 (it can randomly choose 1 or 2 to move) and a fish has a maximum movement of 1
- When moving to the edge of the scene, automatically move in the opposite direction
- Turtle starts at 100 health (Max)
- Each time the tortoise moves, it expends 1
- When the tortoise and fish coordinate overlap, the tortoise eats the fish, the tortoise gains 20 strength
- Fish don’t count strength yet
- The game ends when turtle health reaches 0 (die) or fish number reaches 0
Scene graph
Code implementation
import random
# the turtle class
class Turtle:
def __init__(self) :
self.power=100 # physical
# Turtle coordinates
self.x=random.randint(0.10)
self.y=random.randint(0.10)
# The way turtles move: the direction of movement is random
def move(self) :
# Calculate the new position after the move (only four possibilities)
new_x=self.x+random.choice([1.2, -1, -2])
new_y=self.y+random.choice([1.2, -1, -2])
# Determine if the move is out of bounds
if new_x<0:
self.x=0-new_x
elif new_x>10:
self.x=10-(new_x-10)
else:
# Move the turtle without crossing the line
self.x=new_x
if new_y<0:
self.y=0-new_y
elif new_y>10:
self.y=10-(new_y-10)
else:
# Move the turtle without crossing the line
self.y=new_y
self.power-=1 Each time the tortoise moves, it expends 1
def eat(self) :
self.power+=20 If a turtle eats a fish, the turtle gains 20 strength
if self.power>100:
self.power=100 # Turtle Stamina 100 (upper limit)
# fish
class Fish:
def __init__(self) :
# fish coordinates
self.x=random.randint(0.10)
self.y=random.randint(0.10)
def move(self) :
# Calculate the new position after the move (only four possibilities)
new_x=self.x+random.choice([1, -1])
new_y=self.y+random.choice([1, -1])
# Determine if the move is out of bounds
if new_x<0:
self.x=0-new_x
elif new_x>10:
self.x=10-(new_x-10)
else:
# Move the fish without crossing the line
self.x=new_x
if new_y<0:
self.y=0-new_y
elif new_y>10:
self.y=10-(new_y-10)
else:
# Move the fish without crossing the line
self.y=new_y
# Start testing data
tur=Turtle() Generate 1 turtle
fish=[] # Generate 10 fish
for item in range(10):
fish.append(Fish()) # Place the resulting fish in the tank
# Determine if the game is over: The game ends when the turtle health is 0 (die) or the fish number is 0
if tur.power<0 or len(fish)==0:
print("Game Over ~")
# Game on
# First the tortoise takes the first step
# print(tur.x,tur.y) # print(tur.x,tur.y
tur.move()
# print(tur.x,tur.y) # print(tur.x,tur.y
for item in fish:
item.move()
if item.x==tur.x and item.y==tur.y:
tur.eat()
fish.remove(item)
print("A dead fish.")
print("Latest health of turtle is % D"%tur.power)
Copy the code
Improved: Improved turtle eating fish with PyGame
Let’s take a look at the final result
The picture is taken from the online small fish that case, the functions are as follows:
- Is through the direction key operation turtle, fish
- Check the turtle’s X and y coordinates and the fish’s X and y coordinates while eating the fish, and kill the fish in the collision area
- Background music and fish eating music playing
- Score accumulation
- Smooth swimming of fish (control frame rate)
The implementation code
import random
import pygame
import sys
from pygame.locals import * Import some commonly used functions
pygame.init()
screen=pygame.display.set_mode([640.480])
pygame.display.set_caption('Turtle eats fish') # define window title as' turtle eats fish '
background = pygame.image.load("C:\\Users\\Administrator\\Desktop\\game\\images\\haidi.jpg").convert()
fishImg = pygame.image.load("C:\\Users\\Administrator\\Desktop\\game\\images\\fish.png").convert_alpha()
wuguiImg = pygame.image.load("C:\\Users\\Administrator\\Desktop\\game\\images\\turtle.png").convert_alpha()
# Turtle eats fish music mp3 format no, WAV format
eatsound = pygame.mixer.Sound("C:\\Users\\Administrator\\Desktop\\achievement.wav")
# Background music
pygame.mixer.music.load("C:\\Users\\Administrator\\Desktop\\game_music.mp3")
pygame.mixer.music.play(loops=0, start=0.0)
# Result text display
count=0
font =pygame.font.SysFont("arial".40)
score = font.render("score %d"%count, True, (255.255.255))
w_width = wuguiImg.get_width()-5 Get the width of the turtle image and save it for fish
w_height = wuguiImg.get_height()-5 Get the height of the turtle image
y_width = fishImg.get_width()-5 # Get the width of the fish picture
y_height = fishImg.get_height()-5 # Get the height of the fish image
fpsClock=pygame.time.Clock() Create a new Clock object that can be used to track the total time
# the turtle class
class Turtle:
def __init__(self) :
self.power=100 # physical
# Turtle coordinates
self.x=random.randint(0.500)
self.y=random.randint(0.400)
# The way turtles move: the direction of movement is random
def move(self,new_x,new_y) :
# Determine if the move is out of bounds
if new_x<0:
self.x=0-new_x
elif new_x>640:
self.x=640-(new_x-640)
else:
# Move the turtle without crossing the line
self.x=new_x
if new_y<0:
self.y=0-new_y
elif new_y>480:
self.y=480-(new_y-480)
else:
# Move the turtle without crossing the line
self.y=new_y
self.power-=1 Each time the tortoise moves, it expends 1
def eat(self) :
self.power+=20 If a turtle eats a fish, the turtle gains 20 strength
if self.power>100:
self.power=100 # Turtle Stamina 100 (upper limit)
# fish
class Fish:
def __init__(self) :
# fish coordinates
self.x=random.randint(0.500)
self.y=random.randint(0.400)
def move(self) :
new_x=self.x+random.choice([-10])
if new_x<0:
self.x=650
else:
self.x=new_x
# Start testing data
tur=Turtle() Generate 1 turtle
fish=[] # Generate 10 fish
for item in range(10):
newfish=Fish()
fish.append(newfish) # Place the resulting fish in the tank
# PyGame has an event loop that constantly checks what the user is doing. Event loop, how to break the loop (pyGame created window on the right side of the plug is not used until defined)
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
if event.type == KEYDOWN:
# Control the movement of the turtle through the up, down and left direction keys
if event.key==pygame.K_LEFT:
tur.move(tur.x-10,tur.y)
if event.key==pygame.K_RIGHT:
tur.move(tur.x+10,tur.y)
if event.key==pygame.K_UP:
tur.move(tur.x,tur.y-10)
if event.key==pygame.K_DOWN:
tur.move(tur.x,tur.y+10)
screen.blit(background, (0.0)) # Draw the background image
screen.blit(score,(500.20))# draw score
# draw fish
for item in fish:
screen.blit(fishImg, (item.x, item.y))
# pygame.time.delay(100)
item.move() # fish mobile
screen.blit(wuguiImg, (tur.x, tur.y)) # Draw turtle
# Determine if the game is over: The game ends when the turtle health is 0 (die) or the fish number is 0
if tur.power<0 or len(fish)==0:
print("Game Over ~")
sys.exit()
for item in fish:
# print (" fish ", item. X, item. Y, y_width, y_height)
# print(" turtle ",tur.x,tur.y,w_width,w_height)
if ((tur.x < item.x + y_width) and (tur.x + w_width > item.x) and (tur.y < item.y + y_height) and (w_height + tur.y > item.y)) :
tur.eat() The way turtles eat fish
fish.remove(item) # the fish die
Eat Fish music
eatsound.play()
count=count+1 # accumulation
score = font.render("score %d"%count, True, (255.255.255))
print("A dead fish.")
print("Latest health of turtle is % D"%tur.power)
pygame.display.update() # Update to the game window
fpsClock.tick(10) By calling fpsclock. tick(10) once per frame, the program will never run at more than 10 frames per second
Copy the code