我正在试着做一个蛇游戏,但是我无法正确记录得分和高分。每当蛇收集到一个项目,发生的只是高分增加,而不是总得分。
from tkinter import *
from settings import *
import random
import turtle
import pygame as pg
import keyboard
from os import path
global game_state
class Snake:
def __init__(self):
self.body_size = BODY_PARTS
self.coordinates = []
self.squares = []
for i in range(0, BODY_PARTS):
self.coordinates.append([0, 0])
for x, y in self.coordinates:
square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag="snake")
self.squares.append(square)
class Food:
def __init__(self):
x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-1) * SPACE_SIZE
y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE
self.coordinates = [x, y]
canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag="food")
class TryAgain:
def __init__(self):
x = (GAME_WIDTH / SPACE_SIZE)-1 * SPACE_SIZE
y = (GAME_HEIGHT / SPACE_SIZE) - 1 * SPACE_SIZE
self.coordinates = [x, y]
def show_title_screen():
canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/4,
font=('times new roman',70), text="SNAKE!", fill="Green", tag="title")
canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2,
font=('times new roman',22), text="Use the arrow keys to move", fill="Green", tag="title")
def next_turn(snake, food):
x, y = snake.coordinates[0]
if direction == "up":
y -= SPACE_SIZE
elif direction == "down":
y += SPACE_SIZE
elif direction == "left":
x -= SPACE_SIZE
elif direction == "right":
x += SPACE_SIZE
snake.coordinates.insert(0, (x, y))
square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)
snake.squares.insert(0, square)
if x == food.coordinates[0] and y == food.coordinates[1]:
global score
global high_score
score += 1
label.config(text="Score:{}".format(score))
if score >= high_score:
high_score = score
label.config(text="High Score:{}".format(high_score))
canvas.delete("food")
food = Food()
else:
del snake.coordinates[-1]
canvas.delete(snake.squares[-1])
del snake.squares[-1]
if check_collisions(snake):
game_over()
else:
window.after(SPEED, next_turn, snake, food)
def change_direction(new_direction):
global direction
if new_direction == 'left':
if direction != 'right':
direction = new_direction
elif new_direction == 'right':
if direction != 'left':
direction = new_direction
elif new_direction == 'up':
if direction != 'down':
direction = new_direction
elif new_direction == 'down':
if direction != 'up':
direction = new_direction
def check_collisions(snake):
x, y = snake.coordinates[0]
if x < 0 or x >= GAME_WIDTH:
return True
elif y < 0 or y >= GAME_HEIGHT:
return True
for body_part in snake.coordinates[1:]:
if x == body_part[0] and y == body_part[1]:
return True
return False
def game_over():
canvas.delete(ALL)
canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/4,
font=('times new roman',70), text="GAME OVER", fill="orange", tag="gameover")
button = TryAgain()
def load_data(self):
self.dir = path.dirname(__dirname__)
with open(path.join(self.dir, HS_FILE), 'w') as f:
try:
self.highscore = int(f.read())
except:
self.highscore = 0
window = Tk()
window.title("Snake game")
window.resizable(False, False)
score = 0
high_score = 0
direction = 'down'
label = Label(window, text="Score:{}".format(score), font=('times new roman', 40))
label.pack()
label = Label(window, text="High Score:{}".format(high_score), font=('times new roman', 40))
label.pack()
canvas = Canvas(window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH)
canvas.pack()
window.update()
window_width = window.winfo_width()
window_height = window.winfo_height()
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x = int((screen_width/2) - (window_width/2))
y = int((screen_height/2) - (window_height/2))
window.geometry(f"{window_width}x{window_height}+{x}+{y}")
show_title_screen()
window.bind('<Left>', lambda event: change_direction('left'))
window.bind('<Right>', lambda event: change_direction('right'))
window.bind('<Up>', lambda event: change_direction('up'))
window.bind('<Down>', lambda event: change_direction('down'))
snake = Snake()
food = Food()
next_turn(snake, food)
window.mainloop()
在一个例子中,我试图重新排列涉及“score”和“high score”的画布代码,并试图使它在high score大于score时开始计数,但仍然不起作用。
1条答案
按热度按时间dced5bon1#
我对tkinter一无所知。但我认为问题出在这一点上:
您对两个标签使用了相同的变量名。
当你更新分数时:
变量名
label
仅指高分标签。我认为可以通过为两个标签使用不同的变量名来解决这个问题,例如
score_label
和high_score_label
。